Go Chassis教程三–编写客户端
1、编写main.go
type Client struct { } //在这个方法中,调用上面编写的服务 func (r *Client) SayHi(b *restful.Context) { req, _ :=rest.NewRequest(http.MethodGet, "http://RESTServer/sayhello/world", nil)//这里要填写需要调用哪个服务,填写服务名即可,然后就是他的api路径 restInvoker :=core.NewRestInvoker()//并发安全,可全局使用 resp, err :=restInvoker.ContextDo(context.TODO(), req)//执行调用,这时go chassis介入,执行一些列用户不可见的计算和操作 if err != nil { log.Println(err) return } b.Write(httputil.ReadBody(resp))//读出服务端body体并直接透传返回 return } func (r *Client) SayHi1(b *restful.Context) { req, _ :=rest.NewRequest(http.MethodGet, "http://RESTServer/sayhello1/world", nil)//这里要填写需要调用哪个服务,填写服务名即可,然后就是他的api路径 restInvoker :=core.NewRestInvoker()//并发安全,可全局使用 resp, err :=restInvoker.ContextDo(context.TODO(), req)//执行调用这时go chassis介入,执行一些列用户不可见的计算和操作 if err != nil { log.Println(err) return } b.Write(httputil.ReadBody(resp))//读出服务端body体并直接透传返回 return } func (r *Client) URLPatterns() []restful.Route { return []restful.Route{ {Method: http.MethodGet, Path: "/sayhello", ResourceFunc: r.SayHi}, {Method: http.MethodGet, Path: "/sayhello1", ResourceFunc: r.SayHi1}, } } func main() { chassis.RegisterSchema("rest", &Client{}) //Init framework if err := chassis.Init(); err != nil { openlog.Error("Init failed." + err.Error()) return } chassis.Run() }
2、chassis.yaml
servicecomb: registry: address: http://127.0.0.1:30100 protocols: # what kind of server you want to launch rest: #launch a http server listenAddress: 127.0.0.1:8000
3、microservice.yaml
servicecomb: service: name: RESTClient #name your consumer
4、导入
export CHASSIS_HOME=/home/qiao/www/go/gomall/cn.inzhong.cart/client
5、执行
go run .