github.com/devstream-io/devstream@v0.13.3/internal/response/response.go (about) 1 package response 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "github.com/devstream-io/devstream/internal/log" 7 8 "gopkg.in/yaml.v3" 9 ) 10 11 type StatusCode int 12 type MessageText string 13 14 type Response struct { 15 Status StatusCode `json:"status" yaml:"status"` 16 Message MessageText `json:"message" yaml:"message"` 17 Log string `json:"log" yaml:"log"` 18 } 19 20 var ( 21 StatusOK StatusCode = 0 22 StatusError StatusCode = 1 23 ) 24 25 var ( 26 MessageOK MessageText = "OK" 27 MessageError MessageText = "ERROR" 28 ) 29 30 func New(status StatusCode, message MessageText, log string) *Response { 31 return &Response{ 32 Status: status, 33 Message: message, 34 Log: log, 35 } 36 } 37 38 func (r *Response) Print(format string) { 39 log.Debugf("Format: %s", format) 40 switch format { 41 case "json": 42 r.printJSON() 43 case "yaml": 44 r.printYAML() 45 default: 46 r.printRaw() 47 } 48 } 49 50 func (r *Response) printRaw() { 51 fmt.Println(r.toRaw()) 52 } 53 54 func (r *Response) printJSON() { 55 fmt.Println(r.toJSON()) 56 } 57 58 func (r *Response) printYAML() { 59 fmt.Println(r.toYAML()) 60 } 61 62 func (r *Response) toRaw() string { 63 return r.Log 64 } 65 66 func (r *Response) toJSON() string { 67 str, err := json.Marshal(r) 68 if err != nil { 69 return err.Error() 70 } 71 return string(str) 72 } 73 74 func (r *Response) toYAML() string { 75 str, err := yaml.Marshal(r) 76 if err != nil { 77 return err.Error() 78 } 79 return string(str) 80 }