我是 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/