标签:gen content shang errors coder coding func turn 为知笔记
package Services
type IUserService interface {
GetName(userid int) string
}
type UserService struct{}
func (this UserService) GetName(userid int) string {
if userid == 101 {
return "jerry"
}
return "guest"
}
package Services
import (
"context"
"github.com/go-kit/kit/endpoint"
)
type UserRequest struct { //封装User请求结构体
Uid int `json:"uid"`
}
type UserResponse struct {
Result string `json:"result"`
}
func GenUserEnPoint(userService IUserService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
r := request.(UserRequest) //通过类型断言获取请求结构体
result := userService.GetName(r.Uid) //
return UserResponse{Result: result}, nil
}
}
package Services
import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
)
func DecodeUserRequest(c context.Context, r *http.Request) (interface{}, error) { //这个函数决定了使用哪个request结构体来请求
if r.URL.Query().Get("uid") != "" {
uid, _ := strconv.Atoi(r.URL.Query().Get("uid"))
return UserRequest{Uid: uid}, nil
}
return nil,errors.New("参数错误")/
}
func EncodeUserResponse(ctx context.Context,w http.ResponseWriter,response interface{}) error{
w.Header().Set("Content-type","application/json") //设置响应格式为json,这样客户端接收到的值就是json,就是把我们设置的UserResponse给json化了
return json.NewEncoder(w).Encode(response)//判断响应格式是否正确
}
标签:gen content shang errors coder coding func turn 为知笔记
原文地址:https://www.cnblogs.com/hualou/p/12076155.html