1

我对 golang 很陌生,并试图设置我的响应标头。我有两个要设置的标题。我认为我误解了一些基本的东西。我也在使用 go-swagger 来生成我的端点。

我的问题是我似乎只能设置我的两个标题之一。Swagger 在返回时提供了一个函数“auth.NewAuthLoginUserOK().WithProfileHeader(“pickles)”(在“如果成功”块中)。如何设置两个标头参数?

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()
}

先感谢您。

4

2 回答 2

0

您可以尝试以下解决方案。在你的 swagger.yml 中这样定义

/deviceProvisioningDetails/{deviceId}:
    get:
      tags:
        - tenantManager
      operationId: getDeviceID
      parameters:
            - name: deviceId
              in: path
              description: Device ID
              required: true
              type: string
            - name: requestId
              in: header
              required: true
              description: "request id"
              type: string
      responses:
        200:
          description: OK
          headers:
            tenantId:
              type: string
              description: "Tenant Id"

然后在您的 configure.go 中,您可以返回有效负载。

  return tenant_manager.NewGetDeviceIDOK().WithTenantID(tenantId)
于 2020-01-14T06:19:24.687 回答
0

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

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

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

您应该尽量避免偏离规范。如果您绝对需要编写规范中未指定的标头,则响应对象将具有一个 ServeHTTP 方法,您可以使用它来获取 stdlib 的 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")
    })
于 2018-07-14T01:04:25.967 回答