美文网首页
go实现基于Consul服务的POST调用

go实现基于Consul服务的POST调用

作者: EasyNetCN | 来源:发表于2021-02-25 16:21 被阅读0次

    本示例根据consul返回的健康服务地址,随机选择一个,然后发送POST请求,进行服务调用

    WebClient

    package core
    
    import (
        "bytes"
        "encoding/json"
        "errors"
        "fmt"
        "io"
        "math/rand"
        "net/http"
        "net/url"
    
        "github.com/hashicorp/consul/api"
    )
    
    type WebClient struct {
        httpClient  *http.Client
        consulCient *api.Client
    }
    
    func (m *WebClient) Post(service string, path string, bodyValue interface{}) ([]byte, error) {
        serviceEntries, _, err := m.consulCient.Health().Service(service, "", true, nil)
    
        if err != nil {
            return nil, err
        }
    
        if len(serviceEntries) == 0 {
            return nil, errors.New("no service to connect")
        }
    
        bodyValueBytes, err1 := json.Marshal(bodyValue)
    
        if err1 != nil {
            return nil, err
        }
    
        i := rand.Intn(len(serviceEntries))
    
        serviceEntry := serviceEntries[i]
    
        url := &url.URL{
            Scheme: "http",
            Host:   fmt.Sprintf("%s:%d", serviceEntry.Service.Address, serviceEntry.Service.Port),
            Path:   path,
        }
    
        req, reqErr := http.NewRequest("POST", url.String(), bytes.NewReader(bodyValueBytes))
    
        if reqErr != nil {
            return nil, reqErr
        }
    
        req.Header.Set("Content-Type", "application/json;charset=UTF-8")
    
        res, resErr := m.httpClient.Do(req)
    
        if resErr != nil {
            return nil, resErr
        }
    
        if resBytes, err := io.ReadAll(res.Body); err != nil {
            return nil, err
        } else {
            return resBytes, nil
        }
    }
    
    

    WebClient Test

    package core
    
    import (
        "encoding/json"
        "fmt"
        "net/http"
        "testing"
    
        "github.com/hashicorp/consul/api"
    )
    
    func Test_post(t *testing.T) {
        config := api.DefaultConfig()
    
        config.Address = "http://localhost:8500"
    
        consulClient, _ := api.NewClient(config)
        httpClient := &http.Client{}
    
        webClient := &WebClient{httpClient: httpClient, consulCient: consulClient}
    
        searchParam := &PageParam{PageIndex: 1, PageSize: 50}
    
        if resBytes, err := webClient.Post("app-service", "/page-configs/search/page", searchParam); err != nil {
            fmt.Print(err)
        } else {
            result := make(map[string]interface{})
    
            json.Unmarshal(resBytes, &result)
    
            fmt.Print(result)
        }
    }
    

    相关文章

      网友评论

          本文标题:go实现基于Consul服务的POST调用

          本文链接:https://www.haomeiwen.com/subject/rhjufltx.html