English 中文(简体)
Golang OpenAPI Generator add custom header to request
原标题:

Is it possible to add a custom header that is not specified in the openapi.yaml to the request?

I have something like:

res, err := s.client.MyApi.
        SomeOperation(context.Background(), id).
        SomeOperationRequest(req).
        Execute()

And I would like to add a header to this request. Is there something like "AddHeader()". Or can I pass it by context somehow?

I am using the OpenAPITools generator.

问题回答

if your req used for keep body params/headers only and underhood it implement ClientRequestWriter interface for create actual request (where request created from your object is used for: https://github.com/go-openapi/runtime/blob/da56347e36dc1a470118d4306d2821572c3ad14f/client/request.go#L107), if so, you can decorate WriteToRequest method (from ClientRequestWriter interface):

type decoratedRequest struct {
  SomeOperationRequest // it must be same type for which defined WriteToRequest method, probably it will be pointer to SomeOperationRequest type
  // here you can add custom headers params if you want
}

func (r *decoratedRequest) WriteToRequest(req ClientRequest, reg strfmt.Registry) error
 if err := r.SomeOperationRequest.WriteToRequest(req, reg); err != nil {
   return err
 }

//here you manualy edit actual request to the server
 return req.SetHeaderParam("your-header", "your-value")
}

and production code will look like:

res, err := s.client.MyApi.
        SomeOperation(context.Background(), id).
        SomeOperationRequest(decoratedRequest{SomeOperationRequest: req}).
        Execute()

PS: in your case to make the actual request to the server may be used another interface, but idea is the same

PSS: this will be work, but idiomatic way would be to edit openapi.yaml

Add custom headers to the DefaultHeader map before calling the API

s.client.GetConfig().DefaultHeader["some-header"] = "value"




相关问题
How to set response filename without forcing "save as" dialog

I am returning a stream in some response setting the appropriate content-type header. The behavior I m looking for is this: If the browser is able to render content of the given content type then it ...

Which Http redirects status code to use?

friendfeed.com uses 302. bit.ly uses 301. I had decided to use 303. Do they behave differently in terms of support by browsers ?

Does HttpWebRequest send 200 OK automatically?

Background: I am implementing Paypal IPN handler. This great article on Paypal states that I am required to send a 200 OK back to Paypal after I read the response. The processing of IPN request is ...

Java HTTPAUTH

我试图把桌面应用程序连接起来,我是同D.icio.us api @ Delicious Alan书写的,简单地向他们提供我的用户名和密码,并请他把书记上写给我......。

Finding out where curl was redirected

I m using curl to make php send an http request to some website somewhere and have set CURLOPT_FOLLOWLOCATION to 1 so that it follows redirects. How then, can I find out where it was eventually ...

热门标签