Skip to content

Instantly share code, notes, and snippets.

Created Nov 21, 2019
What would you like to do?
go-elasticsearch w/ setting custom trusted CA certs and custom headers
package main
import (
type CustomRoundTripper struct {
Header http.Header
transport *http.Transport
func (crt CustomRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
for k, v := range crt.Header {
log.Printf("Adding header: %s: %s", k, v)
req.Header[k] = v
return crt.transport.RoundTrip(req)
func (crt *CustomRoundTripper) AddCACerts(path string) error {
b, err := ioutil.ReadFile(path)
if err != nil {
log.Printf("Error reading additional ca certs in path %s / error %s", path, err)
return err
ok := crt.transport.TLSClientConfig.RootCAs.AppendCertsFromPEM(b)
if !ok {
log.Printf("No certs were found in the additional ca cert path: %s", path)
return err
return nil
func newCRT() (crt *CustomRoundTripper) {
crt = new(CustomRoundTripper)
crt.transport = http.DefaultTransport.(*http.Transport).Clone()
crt.Header = make(http.Header)
var err error
crt.transport.TLSClientConfig.RootCAs, err = x509.SystemCertPool()
if err != nil {
func main() {
esurl := os.Args[1]
token := os.Args[2]
cafile := os.Args[3]
var err error
crt := newCRT()
//crt.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
crt.Header.Set("Authorization", fmt.Sprintf("ApiKey %s", base64.StdEncoding.EncodeToString([]byte(token))))
log.Printf("%#v", crt.Header)
log.Printf("transport: %#v", crt.transport)
config := elasticsearch.Config{
Addresses: []string{esurl},
Transport: crt,
es, err := elasticsearch.NewClient(config)
if err != nil {
log.Printf("Error creating ES client: %s", err)
resp, err := es.Ping()
if err != nil {
fmt.Printf("Error pinging ES: %s\n", err)
fmt.Printf("Response: %s\n", resp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment