github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/debug/curl.go (about) 1 package debug 2 3 import ( 4 "os" 5 "strings" 6 7 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/file" 8 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/logger" 9 ) 10 11 var devDebug = false 12 var devDebugMethod = "" 13 14 func init() { 15 devDebugMethod = os.Getenv("TB_DEBUG_CURL") 16 devDebug = len(devDebugMethod) > 0 17 } 18 19 type Debuggable interface { 20 Url() string 21 Body() string 22 Headers() string 23 Method() string 24 Payload() string 25 } 26 27 func shouldDebugCurl(method string) bool { 28 if !devDebug { 29 return false 30 31 } else { 32 if len(devDebugMethod) == 0 { 33 logger.Fatal("Implementation error. Should not happen.") 34 } 35 switch devDebugMethod { 36 case "file": 37 return true 38 case "true": 39 return true 40 case "testing": 41 return true 42 default: 43 // allows for specifying which method to debug (or none) 44 return method == devDebugMethod 45 } 46 } 47 } 48 49 type strDebug string 50 51 func (c strDebug) Url() string { 52 return string(c) 53 } 54 55 func (c strDebug) Body() string { 56 return `curl "[{url}]"` 57 } 58 59 func (c strDebug) Headers() string { 60 return `` 61 } 62 63 func (c strDebug) Method() string { 64 return "" 65 } 66 67 func (c strDebug) Payload() string { 68 return "" 69 } 70 71 func DebugCurlStr(url string) { 72 DebugCurl(strDebug(url)) 73 } 74 75 func DebugCurl(debuggable Debuggable) { 76 if !shouldDebugCurl(debuggable.Method()) { 77 return 78 } 79 80 url := "--url--" 81 payload := "--payload--" 82 headers := "--headers--" 83 if devDebugMethod != "testing" { 84 url = debuggable.Url() 85 payload = debuggable.Payload() 86 headers = debuggable.Headers() 87 } 88 89 var curlCmd = debuggable.Body() 90 curlCmd = strings.Replace(curlCmd, "[{url}]", url, -1) 91 curlCmd = strings.Replace(curlCmd, "[{headers}]", headers, -1) 92 curlCmd = strings.Replace(curlCmd, "[{payload}]", payload, -1) 93 if devDebugMethod == "file" { 94 _ = file.AppendToAsciiFile("./curl.log", curlCmd+"\n") 95 } else { 96 logger.ToggleDecoration() 97 logger.Info(curlCmd) 98 logger.ToggleDecoration() 99 } 100 } 101 102 func CloseDebugger() { 103 if !devDebug { 104 return 105 } 106 logger.Info("Closing curl debugger") 107 }