| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- package transport
- import (
- "context"
- "encoding/json"
- "errors"
- "net/http"
- "standard/gokit/restful/endpoint"
- )
- // Transport/transport.go 主要负责HTTP、gRpc、thrift等相关的逻辑
- // 这里有两个关键函数
- // DecodeRequest & EncodeResponse 函数签名是固定的哟
- // func DecodeRequest(c context.Context, request *http.Request) (interface{}, error)
- // func EncodeResponse(c context.Context, w http.ResponseWriter, response interface{}) error
- func HelloDecodeRequest(c context.Context, request *http.Request) (interface{}, error) {
- // 这里主要就是通过 request 拿到对应的参数构造成在 EndPoint中定义的 Request结构体即可
- name := request.URL.Query().Get("name")
- if name == "" {
- return nil, errors.New("无效参数")
- }
- // 这里返回的是
- return endpoint.HelloRequest{Name: name}, nil
- }
- // HelloEncodeResponse 通过响应封装成 EndPoint中定义的 Response结构体即可
- func HelloEncodeResponse(c context.Context, w http.ResponseWriter, response interface{}) error {
- // 这里将Response返回成有效的json格式给http
- // 设置请求头信息
- w.Header().Set("Content-Type", "application/json;charset=utf-8")
- // 使用内置json包转换
- return json.NewEncoder(w).Encode(response)
- }
- func ByeDecodeRequest(c context.Context, request *http.Request) (interface{}, error) {
- // 这里主要就是通过 request 拿到对应的参数构造成在 EndPoint中定义的 Request结构体即可
- name := request.URL.Query().Get("name")
- if name == "" {
- return nil, errors.New("无效参数")
- }
- // 这里返回的是
- return endpoint.ByeRequest{Name: name}, nil
- }
- // HelloEncodeResponse 通过响应封装成 EndPoint中定义的 Response结构体即可
- func ByeEncodeResponse(c context.Context, w http.ResponseWriter, response interface{}) error {
- // 这里将Response返回成有效的json格式给http
- // 设置请求头信息
- w.Header().Set("Content-Type", "application/json;charset=utf-8")
- // 使用内置json包转换
- return json.NewEncoder(w).Encode(response)
- }
|