Skip to content

Commit

Permalink
Use a temporary workaround to set the Content-Type header
Browse files Browse the repository at this point in the history
This define a custom RoundTripper to add the Content-Type header when
it is needed. This commit should be reverted once hashicorp/consul#10204
is merged and released upstream.

I did not write a test for this change but tested locally and the
header is correctly present for PUT requests but not for GET or DELETE.
  • Loading branch information
remilapeyre committed May 7, 2021
1 parent fe72165 commit 2e00fd1
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions consul/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package consul
import (
"fmt"
"log"
"net/http"
"strings"

consulapi "github.com/hashicorp/consul/api"
Expand Down Expand Up @@ -68,10 +69,20 @@ func (c *Config) Client() (*consulapi.Client, error) {
config.TLSConfig.InsecureSkipVerify = c.InsecureHttps
}

var err error
config.HttpClient, err = consulapi.NewHttpClient(config.Transport, config.TLSConfig)
if err != nil {
return nil, fmt.Errorf("Failed to create http client: %s", err)
// This is a temporary workaround to add the Content-Type header when
// needed until the fix is released in the Consul api client.
config.HttpClient = &http.Client{
Transport: transport{config.Transport},
}

if config.Transport.TLSClientConfig == nil {
tlsClientConfig, err := consulapi.SetupTLSConfig(&config.TLSConfig)

if err != nil {
return nil, fmt.Errorf("failed to create http client: %s", err)
}

config.Transport.TLSClientConfig = tlsClientConfig
}

if c.HttpAuth != "" {
Expand Down Expand Up @@ -99,3 +110,21 @@ func (c *Config) Client() (*consulapi.Client, error) {
}
return client, nil
}

// transport adds the Content-Type header to all requests that might need it
// until we update the API client to a version with
// https://github.com/hashicorp/consul/pull/10204 at which time we will be able
// to remove this hack.
type transport struct {
http.RoundTripper
}

func (t transport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.Body != nil {
// This will not be the appropriate Content-Type for the license and
// snapshot endpoints but this is only temporary and Consul does not
// actually use the header anyway.
req.Header.Add("Content-Type", "application/json")
}
return t.RoundTripper.RoundTrip(req)
}

0 comments on commit 2e00fd1

Please sign in to comment.