TransPoint代码
package Services
import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
)
func GetUserInfo_Request(_ context.Context, request *http.Request, r interface{}) error {
user_request := r.(UserRequest)
request.URL.Path += "/user/" + strconv.Itoa(user_request.Uid)
return nil
}
func GetUserInfo_Response(_ context.Context, res *http.Response) (response interface{}, err error) {
if res.StatusCode > 400 {
return nil, errors.New("no data")
}
var user_response UserResponse
err = json.NewDecoder(res.Body).Decode(&user_response)
if err != nil {
return nil, err
}
return user_response, err
}
调用代码
package main
import (
"context"
"fmt"
httptransport "github.com/go-kit/kit/transport/http"
. "gomicro2/Services"
"net/url"
"os"
)
func main() {
tgt,_:=url.Parse("http://127.0.0.1:8080")
//创建一个直连client,这里我们必须写两个func,一个是如何请求,一个是响应我们怎么处理
client:=httptransport.NewClient("GET",tgt,GetUserInfo_Request,GetUserInfo_Response)
/*
func GenUserEnPoint(userService IUserService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
r := request.(UserRequest) //通过类型断言获取请求结构体
result := "nothings"
if r.Method == "GET" {
result = userService.GetName(r.Uid)
} else if r.Method == "DELETE" {
err := userService.DelUser(r.Uid)
if err != nil {
result = err.Error()
} else {
result = fmt.Sprintf("userid为%d的用户已删除", r.Uid)
}
}
return UserResponse{Result: result}, nil
}
}
*/
getUserInfo:=client.Endpoint() //通过这个拿到了定义在服务端的endpoint也就是上面这段代码return出来的函数,直接在本地就可以调用服务端的代码
ctx:=context.Background()//创建一个上下文
//执行
res,err:=getUserInfo(ctx,UserRequest{Uid:101}) //使用go-kit插件来直接调用服务
if err!=nil{
fmt.Println(err)
os.Exit(1)
}
userinfo:=res.(UserResponse)
fmt.Println(userinfo.Result)
}