github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/modules/robot_notifier/notifier.go (about) 1 package robot_notifier 2 3 import ( 4 "bytes" 5 "context" 6 "encoding" 7 "encoding/json" 8 "io" 9 "net/http" 10 11 "github.com/machinefi/w3bstream/pkg/types" 12 ) 13 14 func Push(ctx context.Context, data interface{}, rspHookFn ...func([]byte) error) (err error) { 15 notifier, ok := types.RobotNotifierConfigFromContext(ctx) 16 if !ok || notifier.IsZero() { 17 return nil 18 } 19 20 var ( 21 msg []byte 22 body []byte 23 ) 24 switch v := data.(type) { 25 case []byte: 26 msg = v 27 case string: 28 msg = []byte(v) 29 case encoding.TextMarshaler: 30 msg, err = v.MarshalText() 31 default: 32 msg, err = json.Marshal(data) 33 } 34 if err != nil { 35 return err 36 } 37 38 rsp, err := http.Post(notifier.URL, "application/json", bytes.NewBuffer(msg)) 39 if err != nil { 40 return err 41 } 42 if len(rspHookFn) > 0 && rspHookFn[0] != nil { 43 body, err = io.ReadAll(rsp.Body) 44 if err != nil { 45 return err 46 } 47 defer rsp.Body.Close() 48 return rspHookFn[0](body) 49 } 50 return nil 51 }