github.com/packtpublishing/learning-functional-programming-in-go@v0.0.0-20230130084745-8b849f6d58c4/Chapter07/func-param/src/utils/utils.go (about) 1 package utils 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "net/http" 8 "os" 9 "path" 10 "runtime" 11 "strings" 12 ) 13 14 type APIError struct { 15 ErrorMessage string `json:"error_message"` 16 HTTPStatus int `json:"http_status"` 17 } 18 19 type HttpErrorHandler struct { 20 Caller string 21 Response http.ResponseWriter 22 Request *http.Request 23 } 24 25 const ( 26 ErrorActionErr = iota 27 ErrorActionWarn 28 ErrorActionDebug 29 ErrorActionInfo 30 ) 31 32 func NewHttpErrorHandle(caller string, response http.ResponseWriter, request *http.Request) *HttpErrorHandler { 33 return &HttpErrorHandler{caller, response, request} 34 } 35 36 // HandleError locally, according to the action passed to h.Handle, and then serialized 37 // in json and sent to the remote address via http, then returns true. 38 // Otherwise, if there is no error, h.Handle returns false 39 func (h *HttpErrorHandler) Handle(err error, httpStatus int, action int) bool { 40 if err != nil { 41 _, filepath, line, _ := runtime.Caller(1) 42 _, file := path.Split(filepath) 43 Error.Printf("HttpErrorHandler()->[file:%s line:%d]: %s", file, line, err.Error()) 44 apiErr := &APIError{ 45 ErrorMessage: err.Error(), 46 HTTPStatus: httpStatus, 47 } 48 serialErr, _ := json.Marshal(&apiErr) 49 h.Response.Header().Set("Content-Type", "application/json") 50 h.Response.WriteHeader(httpStatus) 51 io.WriteString(h.Response, string(serialErr)) 52 } 53 return (err != nil) 54 } 55 56 // HandlePanic _Never_ returns on error, instead it panics 57 func FromLineOfFile() string { 58 _, filepath, line, _ := runtime.Caller(1) 59 _, file := path.Split(filepath) 60 return fmt.Sprintf("[file:%s line:%d]", file, line) 61 } 62 63 // HandlePanic _Never_ returns an error, instead it panics 64 func HandlePanic(err error) { 65 if err != nil { 66 _, filePath, lineNo, _ := runtime.Caller(1) 67 _, fileName := path.Split(filePath) 68 msg := fmt.Sprintf("[file:%s line:%d]: %s", fileName, lineNo, err.Error()) 69 panic(msg) 70 } 71 } 72 73 func HandleError(err error, action int) bool { 74 if err != nil { 75 _, filepath, line, _ := runtime.Caller(1) 76 _, file := path.Split(filepath) 77 switch action { 78 case ErrorActionErr: 79 Error.Printf("[file:%s line:%d]: %s", file, line, err.Error()) 80 break 81 case ErrorActionWarn: 82 Error.Printf("[file:%s line:%d]: %s", file, line, err.Error()) 83 break 84 case ErrorActionDebug: 85 Error.Printf("[file:%s line:%d]: %s", file, line, err.Error()) 86 break 87 case ErrorActionInfo: 88 Error.Printf("[file:%s line:%d]: %s", file, line, err.Error()) 89 break 90 } 91 } 92 return (err != nil) 93 } 94 95 func WriteFile(filename string, source io.Reader) error { 96 writer, err := os.Create(filename) 97 if err != nil { 98 return err 99 } 100 defer writer.Close() 101 io.Copy(writer, source) 102 return nil 103 } 104 105 106 // pad str with padWith count times to right 107 func PadRight(str string, padWith string, length int) string { 108 count := length - len(str) 109 if count < 0 { 110 count = 0 111 } 112 return str + strings.Repeat(padWith, count) 113 } 114 115 func InSlice(slice []string, searchFor string) (found bool) { 116 for _, v := range slice { 117 if searchFor == v { 118 found = true 119 } 120 } 121 return found 122 }