登录
首页 >  Golang >  Go问答

如何使用 go-kit 将请求标头作为响应标头发送

来源:stackoverflow

时间:2024-04-13 10:51:28 100浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《如何使用 go-kit 将请求标头作为响应标头发送》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我正在使用 go-kit 在 go 中开发服务休息。我需要发送标头响应。此标头响应应具有与请求标头相同的值。

这是我的 transport.go 的一部分:

func MakeHandler(m **http.ServeMux) http.Handler {
    const URL = "..."

    var serverOptions []kithttp.ServerOption

    logger := log.NewLogfmtLogger(os.Stderr)

    var svc repositories.SignDocumentRepository

    impl := persistence.NewSignerDocumentRepository()

    svc = middleware.LoggingMiddlewareSignDocument{Logger: logger, Next: impl}

    registerHandler := kithttp.NewServer(
        makeSignDocumentEndpoint(svc),
        decodeRequest,
        encodeResponse,
        serverOptions...,
    )

    r := mux.NewRouter()
    r.Handle(URL, handlers.LoggingHandler(os.Stdout, registerHandler))
    (*m).Handle(URL, r)

    return nil
}


func decodeRequest(_ context.Context, r *http.Request) (interface{}, error) {
    return r, nil
}

func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
    w.Header().Set("headerA", "val1")
    w.Header().Set("headerB", "") // This header should be equal that a header request
    switch response.(type) {
    case model.MsgRsHdr:
        w.WriteHeader(http.StatusPartialContent)
    default:
        w.WriteHeader(http.StatusAccepted)
    }
    if response != nil {
        return json.NewEncoder(w).Encode(response)
    }
    return nil
}

如何在encoderesponse方法中获取请求标头?


解决方案


您可以使用 ServerBefore*http.request 放入上下文中,并可以在 encoderesponse 中获取它来读取请求标头。

type ctxRequestKey struct{}

func putRequestInCtx(ctx context.Context, r *http.Request, _ Request) context.Context {
    return context.WithValue(ctx, ctxRequestKey{}, r)
}

func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
    r := ctx.Value(ctxRequestKey{}).(*http.Request)
    // can use r.Header.Get here to read request here.
}

serverOptions := []kithttp.ServerOptions{
    kithttp.ServerBefore(putRequestInCtx),
}

registerHandler := kithttp.NewServer(
        makeSignDocumentEndpoint(svc),
        decodeRequest,
        encodeResponse,
        serverOptions...,
)

到这里,我们也就讲完了《如何使用 go-kit 将请求标头作为响应标头发送》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>