目标
- 程序中可以支持其他http method 如post, delete
准备对应的结构
源代码
本文中的程序代码:https://github.com/CalvinQiang/go-kit-test
提交点:使用httpMethod执行不同的服务方法
main.go 增加httpMethod
- 这里我们看到, r.Methods是支持传入多个httpMethod
r := goMux.NewRouter() // 这里我们引入了第三方路由
r.Methods("GET", "DELETE").Path(`/user/{uid:\d+}`).Handler(serverHandler) // 设置path格式的路由
UserService.go中新增删除方法
type IUserService interface {
GetName(userId int) string
DelUser(userId int) string
}
UserEndPoint.go中
- 根据httpMethod请求不同方法
- UserRequest增加保存方法的字段
type UserRequest struct {
Uid int `json:"uid"`
Method string
}
func GetUserEndPoint(userService service.IUserService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
r := request.(UserRequest)
if r.Method == "GET" {
result := userService.GetName(r.Uid)
return UserResponse{Result: result}, nil
} else if r.Method == "DELETE" {
result := userService.DelUser(r.Uid)
return UserResponse{Result: result}, nil
} else {
return nil, errors.New("未知方法,无法处理")
}
}
}
运行程序
-
请求 DELETE http://127.0.0.1:8080/user/101,正常解析
-
请求 DELETE http://127.0.0.1:8080/user/1999,正常解析
-
请求 http://127.0.0.1:8080/user1111,找不到预定义的路由