Add custom logger to redact headers

This commit is contained in:
Neeraj Gupta 2023-09-08 20:12:58 +05:30
parent 1e02b9ba36
commit b6ace6dc35
2 changed files with 80 additions and 7 deletions

View file

@ -1,19 +1,46 @@
package api
import (
"context"
"errors"
"github.com/go-resty/resty/v2"
)
const (
TokenHeader = "X-Auth-Token"
TokenQuery = "token"
)
var (
RedactedHeaders = []string{TokenHeader, " X-Request-Id"}
)
type Client struct {
restClient *resty.Client
authToken *string
}
func NewClient() *Client {
type Params struct {
Debug bool
Trace bool
}
func NewClient(p Params) *Client {
c := resty.New()
c.EnableTrace()
if p.Trace {
c.EnableTrace()
}
if p.Debug {
c.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
logRequest(req)
return nil
})
c.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
logResponse(resp)
return nil
})
}
c.SetError(&Error{})
c.SetBaseURL("https://api.ente.io")
return &Client{
@ -21,10 +48,6 @@ func NewClient() *Client {
}
}
func authReq(ctx context.Context, fn func(*resty.Request) (*resty.Response, error)) (*resty.Response, error) {
return fn(ctx.Value("auth").(*resty.Request))
}
// Error type for resty.Error{}
type Error struct{}

50
internal/api/log.go Normal file
View file

@ -0,0 +1,50 @@
package api
import (
"fmt"
"github.com/go-resty/resty/v2"
"strings"
)
func logRequest(req *resty.Request) {
fmt.Println("Request:")
fmt.Printf("Method: %s\n", req.Method)
fmt.Printf("URL: %s\n", req.URL)
fmt.Println("Headers:")
for k, v := range req.Header {
redacted := false
for _, rh := range RedactedHeaders {
if strings.ToLower(k) == strings.ToLower(rh) {
redacted = true
break
}
}
if redacted {
fmt.Printf("%s: %s\n", k, "REDACTED")
} else {
fmt.Printf("%s: %s\n", k, v)
}
}
}
func logResponse(resp *resty.Response) {
fmt.Println("Response:")
fmt.Printf("Status Code: %d\n", resp.StatusCode())
fmt.Printf("Protocol: %s\n", resp.Proto())
fmt.Printf("Time Duration: %s\n", resp.Time())
fmt.Println("Headers:")
for k, v := range resp.Header() {
redacted := false
for _, rh := range RedactedHeaders {
if strings.ToLower(k) == strings.ToLower(rh) {
redacted = true
break
}
}
if redacted {
fmt.Printf("%s: %s\n", k, "REDACTED")
} else {
fmt.Printf("%s: %s\n", k, v)
}
}
}