通过HttpMethod执行不同的服务方法:
代码实现如下:
package Services
import (
"context"
"fmt"
"github.com/go-kit/kit/endpoint"
)
type UserRequest struct {
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) {
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("参数错误")
}
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 {
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
}
}