|
| 1 | +//go:build js |
| 2 | + |
| 3 | +package httplog_fetch |
| 4 | + |
| 5 | +import ( |
| 6 | + "slices" |
| 7 | + "strings" |
| 8 | + |
| 9 | + fetch "github.com/aperturerobotics/bifrost/util/js-fetch" |
| 10 | + "github.com/sirupsen/logrus" |
| 11 | +) |
| 12 | + |
| 13 | +var logHeaders = []string{"range", "content-range", "content-type", "content-length", "accept"} |
| 14 | + |
| 15 | +// Fetch uses the JS Fetch API to make requests with logging. |
| 16 | +// |
| 17 | +// if le is nil, all logging is disabled. |
| 18 | +// if verbose is set, both successful and failed calls are logged. |
| 19 | +func Fetch(le *logrus.Entry, url string, opts *fetch.Opts, verbose bool) (*fetch.Response, error) { |
| 20 | + // Request details |
| 21 | + if le != nil { |
| 22 | + method := "GET" |
| 23 | + if opts != nil && opts.Method != "" { |
| 24 | + method = opts.Method |
| 25 | + } |
| 26 | + |
| 27 | + le = le.WithFields(logrus.Fields{ |
| 28 | + "method": method, |
| 29 | + "url": url, |
| 30 | + }) |
| 31 | + |
| 32 | + if opts != nil && opts.Headers != nil { |
| 33 | + // Parse and log some headers from the request |
| 34 | + for hdr, hdrVal := range opts.Headers { |
| 35 | + hdr = strings.ToLower(hdr) |
| 36 | + if slices.Contains(logHeaders, hdr) { |
| 37 | + le = le.WithField(hdr, hdrVal) |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + if verbose { |
| 43 | + le.Debug("starting request") |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + resp, err := fetch.Fetch(url, opts) |
| 48 | + |
| 49 | + if le != nil { |
| 50 | + if resp != nil { |
| 51 | + le = le.WithField("status", resp.Status) |
| 52 | + for hdr, hdrVal := range resp.Headers { |
| 53 | + hdr = strings.ToLower(hdr) |
| 54 | + if slices.Contains(logHeaders, hdr) { |
| 55 | + le = le.WithField(hdr, hdrVal) |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + if err != nil { |
| 61 | + le.WithError(err).Warn("request errored") |
| 62 | + } else if resp.Status >= 400 { |
| 63 | + le.Warn("request failed") |
| 64 | + } else if verbose { |
| 65 | + le.Debug("request succeeded") |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return resp, err |
| 70 | +} |
0 commit comments