Go-swagger: Inject (dynamic) header to each request

Created on 17 Jun 2019  路  4Comments  路  Source: go-swagger/go-swagger

I have a generated client, but I need to add an authorization header to each request the client makes. Before I started to use autogenerated clients, I would do something like this:

api.BeforeDoRequest(func(request \*http.Request) { request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", "my-special-token")) })

and in the client code, I would have something like this:

if c.beforeDoRequestFunc != nil {
    c.beforeDoRequestFunc(req)
}

This would add a header to all requests my client does. Now I'm wondering: does go-swagger support something like this?

generate client question

All 4 comments

Yes, you just need to override the default transport with your own RoundTripper

Wow, nice man! I now did this:

package main

import (
    "fmt"
    "net/http"
)

func newTransport() *customTransport {
    return &customTransport{
        originalTransport: http.DefaultTransport,
    }
}

type customTransport struct {
    originalTransport http.RoundTripper
}

func (c *customTransport) RoundTrip(r *http.Request) (*http.Response, error) {

    r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))

    resp, err := c.originalTransport.RoundTrip(r)
    if err != nil {
        return nil, err
    }

    return resp, nil
}

And used this custom roundTripper like this:

        HTTPClient: &http.Client{
            Timeout:   time.Second * 10,
            Transport: newTransport(),
        },

Works fine man! Any suggestions for improvements?

If you're doing this for bearer auth, you can also generate the code with a security principal (the type of your user)
The code will then allow you to use an auth writer one of which is bearer token.
You can see the default ones here: https://github.com/go-openapi/runtime/blob/master/client/auth_info.go

This auth writer then gets passed to the authInfo runtime.ClientAuthInfoWriter parameter in your client call, after the struct that contains all the request parameters.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alihalabyah picture alihalabyah  路  4Comments

ikouchiha47 picture ikouchiha47  路  4Comments

alexec picture alexec  路  3Comments

Ragnar-BY picture Ragnar-BY  路  3Comments

TheImpressionist picture TheImpressionist  路  4Comments