带有 go-swagger 响应头的 GoLang

标签 go header httpresponse go-swagger

我是 golang 的新手,正在尝试设置我的响应 header 。我有两个要设置的标题。我认为我误解了一些基本的东西。我还使用 go-swagger 生成我的端点。

我的问题是我似乎只能设置两个 header 之一。 Swagger 在返回时(在“if success” block 中)提供了一个函数“auth.NewAuthLoginUserOK().WithProfileHeader("pickles)”。如何设置两个 header 参数?

func AuthLoginRouteHandler(params auth.AuthLoginUserParams) middleware.Responder {
    transactionId := redFalconLogger.GetTransactionId()
    redFalconLogger.LogDebug("AuthLoginRouteHandler", transactionId)

    email := params.Body.Email
    password := params.Body.Password

    //Check to ensure that they are not nil
    if email == "" || password == ""{
        redFalconLogger.LogError("Got an empty string on a username/password", transactionId)
        return auth.NewAuthLoginUserBadRequest()
    }

    //use pointers to limit in flight private data
    pointerEmail := &email
    pointerPassword := &password

    //Call the auth domain
    success := authDomain.LoginUser(pointerEmail,pointerPassword,transactionId)

    if success {
        return auth.NewAuthLoginUserOK().WithProfileKeyHeader("pickles")
    }
    redFalconLogger.LogDebug("Failed Login: ", transactionId)
    return auth.NewAuthLoginUserBadRequest()
}

提前谢谢你。

最佳答案

go-swagger 将为结果对象规范中定义的每个响应 header 生成一个方法(auth.NewAuthLoginUserOK() 返回的内容)

如果您在生成的规范中定义了多个响应 header ,只需链接调用即可。

return auth.NewAuthLoginUserOK().WithProfileKeyHeader("pickles").WithOtherHeader("cucumbers")

您应该尽量避免偏离规范。如果您绝对需要编写规范中未指定的 header ,则响应对象将具有一个 ServeHTTP 方法,您可以使用该方法获取标准库的 ResponseWriter。

    return auth.NewAuthLoginUserOK().ServeHTTP(func(rw http.ResponseWriter, r *http.Request) {
        // Try and avoid this
        rw.Header().Add("profile", "pickles")
        rw.Header().Add("other-header", "cucumbers")
    })

关于带有 go-swagger 响应头的 GoLang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51332756/

相关文章:

servlets - 如何防止在重定向网址末尾添加 jsessionid

python - 将 javascript 添加到 Django 重定向 (HttpResponse)

api - 使用PowerApps进行Rest API调用

Golang crypto/tls 内存泄漏

go - Go Lang ioutil.writeFile函数使目录和文件只读

复除法

html5 : using header or footer tag twice?

go - 如何创建启用了服务管理 API 的 Google Cloud 项目?

mysql - go-sql-driver/mysql - 将 float64 插入 mariadb(双列)给出不受支持的类型 func() float64,一个 func

c++ - 如何在 C++ 中声明外部类指针?