github.com/jshiv/can-go@v0.2.1-0.20210224011015-069e90e90bdf/pkg/candebug/http.go (about) 1 package candebug 2 3 import ( 4 "bytes" 5 "net/http" 6 "path" 7 "strconv" 8 "time" 9 10 "go.einride.tech/can/pkg/cantext" 11 "go.einride.tech/can/pkg/descriptor" 12 "go.einride.tech/can/pkg/generated" 13 ) 14 15 func ServeMessagesHTTP(w http.ResponseWriter, r *http.Request, msgs []generated.Message) { 16 base := path.Base(r.URL.Path) 17 // if path ends with a message name, serve only that message 18 for _, m := range msgs { 19 if m.Descriptor().Name == base { 20 serveMessagesHTTP(w, r, []generated.Message{m}) 21 return 22 } 23 } 24 serveMessagesHTTP(w, r, msgs) 25 } 26 27 func serveMessagesHTTP(w http.ResponseWriter, _ *http.Request, msgs []generated.Message) { 28 var buf []byte 29 for i, m := range msgs { 30 buf = appendMessage(buf, m) 31 if i != len(msgs)-1 { 32 buf = append(buf, "\n\n\n"...) 33 } 34 } 35 w.Header().Set("Content-Type", "text/plain; charset=utf-8") 36 w.WriteHeader(http.StatusOK) 37 _, _ = w.Write(buf) 38 } 39 40 func appendMessage(buf []byte, m generated.Message) []byte { 41 name := m.Descriptor().Name 42 sep := append(bytes.Repeat([]byte{'='}, len(name)), '\n') 43 buf = append(buf, name...) 44 buf = append(buf, '\n') 45 buf = append(buf, sep...) 46 buf = cantext.AppendID(buf, m.Descriptor()) 47 buf = append(buf, '\n') 48 buf = cantext.AppendSender(buf, m.Descriptor()) 49 buf = append(buf, '\n') 50 buf = cantext.AppendSendType(buf, m.Descriptor()) 51 buf = append(buf, '\n') 52 if m.Descriptor().SendType == descriptor.SendTypeCyclic { 53 if enabler, ok := m.(interface{ IsCyclicTransmissionEnabled() bool }); ok { 54 buf = append(buf, "Enabled: "...) 55 buf = strconv.AppendBool(buf, enabler.IsCyclicTransmissionEnabled()) 56 buf = append(buf, '\n') 57 } 58 buf = cantext.AppendCycleTime(buf, m.Descriptor()) 59 buf = append(buf, '\n') 60 } 61 if m.Descriptor().DelayTime != 0 { 62 buf = cantext.AppendDelayTime(buf, m.Descriptor()) 63 buf = append(buf, '\n') 64 } 65 buf = append(buf, sep...) 66 if timer, ok := m.(interface{ ReceiveTime() time.Time }); ok { 67 buf = append(buf, "Received: "...) 68 buf = appendTime(buf, timer.ReceiveTime()) 69 buf = append(buf, '\n') 70 buf = append(buf, sep...) 71 } 72 if timer, ok := m.(interface{ TransmitTime() time.Time }); ok { 73 buf = append(buf, "Transmitted: "...) 74 buf = appendTime(buf, timer.TransmitTime()) 75 buf = append(buf, '\n') 76 buf = append(buf, sep...) 77 } 78 f := m.Frame() 79 for i, s := range m.Descriptor().Signals { 80 buf = cantext.AppendSignal(buf, s, f.Data) 81 if i < len(m.Descriptor().Signals)-1 { 82 buf = append(buf, '\n') 83 } 84 } 85 return buf 86 } 87 88 func appendTime(buf []byte, t time.Time) []byte { 89 if t.IsZero() { 90 buf = append(buf, "never"...) 91 return buf 92 } 93 buf = append(buf, time.Since(t).String()...) 94 buf = append(buf, " ago ("...) 95 buf = t.AppendFormat(buf, "15:04:05.000000000") 96 buf = append(buf, ")"...) 97 return buf 98 }