Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用go工具包将请求标头作为响应标头发送_Go - Fatal编程技术网

如何使用go工具包将请求标头作为响应标头发送

如何使用go工具包将请求标头作为响应标头发送,go,Go,我正在使用Go工具包开发一个Go中的服务rest。我需要发送一个标题响应。此标头响应应具有与请求标头相同的值 这是我的交通工具的一部分。开始: func MakeHandler(m **http.ServeMux) http.Handler { const URL = "..." var serverOptions []kithttp.ServerOption logger := log.NewLogfmtLogger(os.Stderr)

我正在使用Go工具包开发一个Go中的服务rest。我需要发送一个标题响应。此标头响应应具有与请求标头相同的值

这是我的交通工具的一部分。开始:

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方法中获取请求头?

您可以使用将
*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...,
)