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

2021-02-25  本文已影响0人  EasyNetCN

本示例根据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)
    }
}
上一篇 下一篇

猜你喜欢

热点阅读