github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/monitor/monitor.go (about) 1 package monitor 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "github.com/bigzoro/my_simplechain/p2p" 7 "github.com/bigzoro/my_simplechain/rpc" 8 "log" 9 "net/http" 10 ) 11 12 type MonitorService struct { 13 port string 14 } 15 16 type PublicMonitorAPI struct { 17 monitorService *MonitorService 18 } 19 20 func New(port string) *MonitorService { 21 return &MonitorService{port} 22 } 23 24 func NewPublicMonitorAPI(monitorService *MonitorService) *PublicMonitorAPI { 25 return &PublicMonitorAPI{monitorService} 26 } 27 func (service *MonitorService) Protocols() []p2p.Protocol { return []p2p.Protocol{} } 28 29 func (service *MonitorService) APIs() []rpc.API { 30 return []rpc.API{ 31 { 32 Namespace: "monitor", 33 Version: "1.0", 34 Service: NewPublicMonitorAPI(service), 35 Public: true, 36 }, 37 } 38 } 39 40 func (service *MonitorService) Start(p2pServer *p2p.Server) error { 41 http.HandleFunc("/info", getRunningStatus) 42 addr := fmt.Sprintf(":%s", service.port) 43 log.Println("Listen ", addr) 44 err := http.ListenAndServe(addr, nil) 45 if err != nil { 46 return err 47 } 48 return nil 49 } 50 51 func (service *MonitorService) Stop() error { 52 return nil 53 } 54 55 func getRunningStatus(w http.ResponseWriter, r *http.Request) { 56 if r.Method != "GET" { 57 w.WriteHeader(http.StatusBadRequest) 58 return 59 } 60 setHeader(w) 61 m := map[string]bool{ 62 "ProcessStatus": true, 63 } 64 resDate(w, m) 65 } 66 67 func resDate(w http.ResponseWriter, data interface{}) { 68 s, err := json.Marshal(data) 69 if err != nil { 70 resErr(err, w) 71 return 72 } 73 fmt.Fprintf(w, string(s)) 74 } 75 func setHeader(w http.ResponseWriter) { 76 w.Header().Set("Access-Control-Allow-Origin", "*") 77 w.Header().Add("Access-Control-Allow-Headers", "Content-Type") 78 w.Header().Set("Content-Type", "application/json") 79 } 80 81 func resErr(err error, w http.ResponseWriter) { 82 res := RespErr{ 83 Code: 400, 84 Msg: err.Error(), 85 } 86 s, _ := json.Marshal(res) 87 88 _, _ = fmt.Fprintf(w, string(s)) 89 } 90 91 type RespErr struct { 92 Code int 93 Msg string 94 }