log.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package api
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/fatih/color"
  6. "github.com/go-resty/resty/v2"
  7. )
  8. func logRequest(req *resty.Request) {
  9. fmt.Println(color.GreenString("Request:"))
  10. fmt.Printf("%s %s\n", color.CyanString(req.Method), color.YellowString(req.URL))
  11. fmt.Println(color.GreenString("Headers:"))
  12. for k, v := range req.Header {
  13. redacted := false
  14. for _, rh := range RedactedHeaders {
  15. if strings.EqualFold(strings.ToLower(k), strings.ToLower(rh)) {
  16. redacted = true
  17. break
  18. }
  19. }
  20. if redacted {
  21. fmt.Printf("%s: %s\n", color.CyanString(k), color.RedString("REDACTED"))
  22. } else {
  23. if len(v) == 1 {
  24. fmt.Printf("%s: %s\n", color.CyanString(k), color.YellowString(v[0]))
  25. } else {
  26. fmt.Printf("%s: %s\n", color.CyanString(k), color.YellowString(strings.Join(v, ",")))
  27. }
  28. }
  29. }
  30. // log query params if present
  31. if len(req.QueryParam) > 0 {
  32. fmt.Println(color.GreenString("Query Params:"))
  33. for k, v := range req.QueryParam {
  34. if k == TokenQuery {
  35. v = []string{"REDACTED"}
  36. }
  37. fmt.Printf("%s: %s\n", color.CyanString(k), color.YellowString(strings.Join(v, ",")))
  38. }
  39. }
  40. }
  41. func logResponse(resp *resty.Response) {
  42. fmt.Println(color.GreenString("Response:"))
  43. if resp.StatusCode() < 200 || resp.StatusCode() >= 300 {
  44. fmt.Printf("%s %s\n", color.CyanString(resp.Proto()), color.RedString(resp.Status()))
  45. } else {
  46. fmt.Printf("%s %s\n", color.CyanString(resp.Proto()), color.YellowString(resp.Status()))
  47. }
  48. fmt.Printf("Time Duration: %s\n", resp.Time())
  49. fmt.Println(color.GreenString("Headers:"))
  50. for k, v := range resp.Header() {
  51. redacted := false
  52. for _, rh := range RedactedHeaders {
  53. if strings.EqualFold(strings.ToLower(k), strings.ToLower(rh)) {
  54. redacted = true
  55. break
  56. }
  57. }
  58. if redacted {
  59. fmt.Printf("%s: %s\n", color.CyanString(k), color.RedString("REDACTED"))
  60. } else {
  61. fmt.Printf("%s: %s\n", color.CyanString(k), color.YellowString(strings.Join(v, ",")))
  62. }
  63. }
  64. }