Created
November 21, 2019 17:35
-
-
Save jordansissel/692e26a5307deb15e6cdaf39e3f2953d to your computer and use it in GitHub Desktop.
go-elasticsearch w/ setting custom trusted CA certs and custom headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/base64" | |
"crypto/x509" | |
"fmt" | |
"github.com/elastic/go-elasticsearch/v8" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
) | |
type CustomRoundTripper struct { | |
http.RoundTripper | |
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 { | |
panic(err) | |
} | |
return | |
} | |
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) | |
crt.AddCACerts(cafile) | |
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) | |
os.Exit(1) | |
} | |
resp, err := es.Ping() | |
if err != nil { | |
fmt.Printf("Error pinging ES: %s\n", err) | |
os.Exit(1) | |
} | |
fmt.Printf("Response: %s\n", resp) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment