package Services
import (
"context"
"fmt"
"github.com/go-kit/kit/endpoint"
)
type UserRequest struct { //封装User请求结构体,包含参数名和方法
Uid int `json:"uid"`
Method string
}
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 := "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
}
}
Transport
package Services
import (
"context"
"encoding/json"
"errors"
mymux "github.com/gorilla/mux"
"net/http"
"strconv"
)
func DecodeUserRequest(c context.Context, r *http.Request) (interface{}, error) { //这个函数决定了使用哪个request来请求
vars := mymux.Vars(r)
if uid, ok := vars["uid"]; ok {
uid, _ := strconv.Atoi(uid)
return UserRequest{Uid: uid, Method: r.Method}, nil //组装请求参数和方法
}
return nil, errors.New("参数错误") //如果发生错误返回给客户端这个错误,如果没有返回endpoint的执行结果
}
func EncodeUserResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
w.Header().Set("Content-type", "application/json")
return json.NewEncoder(w).Encode(response)
}
EndPoint
package Services
import (
"context"
"fmt"
"github.com/go-kit/kit/endpoint"
)
type UserRequest struct { //封装User请求结构体
Uid int `json:"uid"`
Method string
}
type UserResponse struct {
Result string `json:"result"`
}
func GenUserEnPoint(userService IUserService) endpoint.Endpoint { //当EncodeUserRequest和DecodeUserResponse都不报错的时候才会走这个函数
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
}
}