go语言服务消费

import (
    "fmt"
    "github.com/micro/go-micro/client/selector"
    "github.com/micro/go-micro/registry"
    "github.com/micro/go-plugins/registry/consul"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    consulReg:=consul.NewRegistry(
        registry.Addrs("127.0.0.1:8500"))
    getService,err:=consulReg.GetService("product")
    if err!=nil{
        log.Fatal("err")
    }
    next:=selector.RoundRobin(getService)
    node,err := next()
    if err!=nil{
        log.Fatal("err")
    }
    // path:路由地址,method:请求方式,address:服务器地址
    data,err:=callAPI(node.Address,"/v1/prods","GET")
    fmt.Println(data)
}

func callAPI(addr string,path string,method string) (string,error) {
    req,_:=http.NewRequest(method,"http://"+addr+path,nil)
    client:=http.DefaultClient
    res,err:=client.Do(req)
    if err!=nil{
        return "",err
    }
    defer res.Body.Close()
    buf,_:=ioutil.ReadAll(res.Body)
    return string(buf),nil
}
原文地址:https://www.cnblogs.com/huqi96/p/14389005.html