Skip to content

yunnysunny/consul-balancer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

consul-balancer

Go Reference codecov

The client balancer of consul. It only supports http protocol now.

License

MIT

Usage

Install via go get.

go get github.com/yunnysunny/consul-balancer

Send request to specified service.

import (
    "github.com/yunnysunny/consul-balancer/http"
    "github.com/valyala/fasthttp"
)
func doGet(serviceName string, tags []string) {
    serviceConfig := &http.ServiceConfig {
        ServiceName: serviceName,
        Tags: tags,	
        TimeoutSeconds4Ready: 10,	
    }
    balancer, err := http.NewHttpBalancer(serviceConfig)
    if err != nil {
        fmt.Errorf("init balancer failed: %v", err)
        return
    }

    req := fasthttp.AcquireRequest()
    defer fasthttp.ReleaseRequest(req)
    req.SetRequestURI("/get")
    resp := fasthttp.AcquireResponse()
    defer fasthttp.ReleaseResponse(resp)

    err = balancer.Do(req, resp)
    if err != nil {
        fmt.Errorf("send request failed: %v", err)
        return
    }

    result := string(resp.Body())
    fmt.Logf("response result: %s", result)
}

consul-balancer use fasthttp to process http request. Be careful to use the reference of fasthttp.Response's internal buffer. In the code for example, resp.Body() return a slice that points to Response's internal buffer, after call fasthttp.ReleaseResponse, fasthttp will reuse the internal buffer, and the content of buffer may be changed. So the safety usage is copying the bytes gotten from Response before release it. See the issue of #1013 #1109 of fasthttp.