Home > Net >  How can I override content type header of every responses for http.Client?
How can I override content type header of every responses for http.Client?

Time:06-29

I've got a http.Client in go and I want it to update every content type for every response to application/json (even though it might not be the case) even before it process the response.

Which attribute shall I override?

Context: the underlying issue there's a bug in the third party API where the real content type is application/json but it's set to the other thing (incorrectly).

Code snippet:

...
    requestURL := fmt.Sprintf("http://localhost:%d", serverPort)
    req, err := http.NewRequest(http.MethodGet, requestURL, nil)
    if err != nil {
        fmt.Printf("client: could not create request: %s\n", err)
        os.Exit(1)
    }

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Printf("client: error making http request: %s\n", err)
        os.Exit(1)
    }

    fmt.Printf("client: got response!\n")
    fmt.Printf("client: status code: %d\n", res.StatusCode)

    resBody, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Printf("client: could not read response body: %s\n", err)
        os.Exit(1)
    }
    fmt.Printf("client: response body: %s\n", resBody)
}

CodePudding user response:

package main

import (
    "fmt"
    "net/http"
)

type MyRoundTripper struct {
    httprt http.RoundTripper
}

func (rt MyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
    res, err := rt.httprt.RoundTrip(req)

    if err != nil {
        fmt.Printf("Error: %v", err)
    } else {
        res.Header.Set("Content-Type", "application/json")
    }
    return res, err
}

func main() {

    client := &http.Client{Transport: MyRoundTripper{http.DefaultTransport}}
    resp, err := client.Get("https://example.com")

    if err != nil {
        // handle error
    }

    fmt.Printf("% v\n", resp.Header)
}
  • Related