From 72e4690e59f75da2adce358d18bfbce2ec34d15e Mon Sep 17 00:00:00 2001 From: Tomer Froumin Date: Mon, 1 Apr 2024 23:55:27 +0300 Subject: [PATCH] Added option to define custom headers to log requests (#18) --- constant.go | 20 +++++++++++++++++++- http.go | 12 +++++++++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/constant.go b/constant.go index 1edfcdb..4d55d58 100644 --- a/constant.go +++ b/constant.go @@ -1,6 +1,12 @@ package coralogix -import "time" +import ( + "bufio" + "net/http" + "net/textproto" + "strings" + "time" +) const ( // MaxLogBufferSize is maximum log buffer size (default=128MiB) @@ -49,4 +55,16 @@ var ( // TimeDeltaURL is the Coralogix time delay url endpoint TimeDeltaURL string = GetEnv("CORALOGIX_TIME_DELTA_URL", "https://api.coralogix.com:443/sdk/v1/time") + + // Headers is the list of headers added to each send logs request + Headers http.Header = func() http.Header { + headers := GetEnv("CORALOGIX_HEADERS", "") + tp := textproto.NewReader(bufio.NewReader(strings.NewReader(headers))) + mimeHeader, err := tp.ReadMIMEHeader() + if err != nil { + mimeHeader = map[string][]string{} + } + mimeHeader.Set("Content-Type", "application/json") + return http.Header(mimeHeader) + }() ) diff --git a/http.go b/http.go index deacd96..e6daa82 100644 --- a/http.go +++ b/http.go @@ -2,7 +2,7 @@ package coralogix import ( "bytes" - "io/ioutil" + "io" "net/http" "strconv" "time" @@ -17,8 +17,14 @@ func SendRequest(Bulk *Bulk) int { for Attempt := 1; uint(Attempt) <= HTTPSendRetryCount; Attempt++ { DebugLogger.Println("About to send bulk to Coralogix server. Attempt number:", Attempt) - response, err := client.Post(LogURL, "application/json", bytes.NewBuffer(Bulk.ToJSON())) + request, err := http.NewRequest("POST", LogURL, bytes.NewBuffer(Bulk.ToJSON())) + if err != nil { + DebugLogger.Println("Can't create HTTP request:", err) + continue + } + request.Header = Headers + response, err := client.Do(request) if err != nil { DebugLogger.Println("Can't execute HTTP request:", err) continue @@ -53,7 +59,7 @@ func GetTimeSync() (bool, float64) { } if response.StatusCode == 200 { - response, _ := ioutil.ReadAll(response.Body) + response, _ := io.ReadAll(response.Body) ServerTime, err := strconv.ParseFloat(string(response), 64) if err != nil {