http请求解析必须在transport层完成,endpoint只处理纯结构体输入输出;service层须完全解耦框架类型,确保可测试性与复用性。

Go-Kit 的 transport 和 endpoint 到底谁该处理 HTTP 解析?
HTTP 请求解析(比如读 json body、校验 Content-Type、提取 Authorization header)必须放在 transport 层,绝不能丢进 endpoint 或业务逻辑里。
原因很简单:endpoint 是协议无关的——它只认结构体输入输出;同一套 endpoint 要能被 HTTP、gRPC、甚至本地函数调用复用。一旦你在 endpoint 里写 r.Body 或 json.Unmarshal,就等于给它焊死了 HTTP。
-
transport层负责把*http.Request拆成干净的 Go 结构体,再喂给endpoint -
endpoint只接收已解包的request struct,返回response struct - 常见错误:在
MakeXXXEndpoint里直接读http.Request—— 这会让单元测试只能走 HTTP mock,失去快速验证业务逻辑的能力
怎么写一个不耦合 HTTP 的 endpoint?
核心是让 endpoint 的输入输出类型完全脱离 net/http。典型反例是让它接收 *http.Request 或返回 http.ResponseWriter。
正确做法:定义两个纯结构体,比如 CreateUserRequest 和 CreateUserResponse,然后用 kit/endpoint 的 Endpoint 类型封装业务函数:
type CreateUserRequest struct {
Name string `json:"name"`
Email string `json:"email"`
}
type CreateUserResponse struct {
ID int64 `json:"id"`
Error string `json:"error,omitempty"`
}
func MakeCreateUserEndpoint(svc UserService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(CreateUserRequest)
id, err := svc.CreateUser(ctx, req.Name, req.Email)
if err != nil {
return CreateUserResponse{Error: err.Error()}, nil
}
return CreateUserResponse{ID: id}, nil
}
}
- 注意
request interface{}的强制类型断言——这是 Go-Kit 的约定,不是 bug - 别在
endpoint里做日志、限流、认证——这些属于middleware,应套在endpoint外层 - 如果业务函数本身带 ctx,就直接传;不要在
endpoint里 new context 或 cancel
transport/http.NewServer 的 decode 和 encode 函数容易漏掉什么?
decode 不只是 json.Unmarshal,它还得处理路径参数、query 参数、header 字段;encode 也不能只写 json.Marshal,得记得设 Content-Type,还要区分 200 和 error 状态码。
典型遗漏点:
- 没检查
r.Method,导致 POST 接口被 GET 调用时静默失败 - 忽略
r.URL.Query().Get("page")这类 query 参数,硬塞进 body 解析 -
encode里没判断response.Error != "",所有错误都返回 200 + error 字段,前端难做状态分流 - 没设
w.Header().Set("Content-Type", "application/json; charset=utf-8"),某些老客户端会解析失败
示例片段(简化):
func decodeCreateUserRequest(_ context.Context, r *http.Request) (interface{}, error) {
if r.Method != "POST" {
return nil, errors.New("method not allowed")
}
var req CreateUserRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, err
}
return req, nil
}
func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if resp, ok := response.(CreateUserResponse); ok && resp.Error != "" {
w.WriteHeader(http.StatusBadRequest)
}
return json.NewEncoder(w).Encode(response)
}
为什么 service 层接口不能依赖 transport 或 endpoint 包?
因为 service 是纯业务契约,它的实现要能脱离框架跑单元测试,也要能被 CLI、定时任务、消息队列消费者直接调用。
一旦你 import 了 github.com/go-kit/kit/endpoint 或 github.com/go-kit/kit/transport/http,就等于把业务和传输细节绑死了。
- service 接口方法参数必须是基本类型或自定义结构体,禁止出现
context.Context以外的框架类型(比如endpoint.Context) - 别在 service 方法里调
log.With或metrics.Inc—— 这些是 middleware 的事 - 常见坑:为了“方便”在 service 里直接调
http.DefaultClient.Do去调其他服务 —— 这会让测试必须启 HTTP server,破坏隔离性
分层真正的价值不在代码目录上划线,而在于你能把 UserService 实现替换成内存版、mock 版、DB 版,且 transport 层完全无感。










