eventServer.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package eventServer
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "github.com/sirupsen/logrus"
  6. "io/ioutil"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. // MQDEvent (MQTT Data Event) 用于mqtt传输事件
  12. type MQDEvent struct {
  13. EventCode string `json:"eventCode"`
  14. EId int `json:"eId"`
  15. Ip string `json:"ip"`
  16. Type string `json:"type"`
  17. StartTime string `json:"startTime"`
  18. Name string `json:"name"`
  19. Data []byte `json:"data"`
  20. }
  21. func StartEventServer() {
  22. http.HandleFunc("/event", handler)
  23. logrus.Fatal("事件监听服务启动失败", http.ListenAndServe(":8850", nil))
  24. }
  25. func handler(w http.ResponseWriter, r *http.Request) {
  26. go func() {
  27. //监听主机应答固定,直接先应答
  28. w.WriteHeader(200)
  29. w.Header().Add("Date", time.Now().String())
  30. w.Header().Add("Connection", "close")
  31. }()
  32. //logRequest(r)
  33. contentType := r.Header.Get("Content-Type")
  34. if strings.Contains(contentType, "application/xml") {
  35. bytes, err := ioutil.ReadAll(r.Body)
  36. if err != nil {
  37. logrus.Error("事件处理-读取错误:", err)
  38. return
  39. }
  40. var event EventNotificationAlert
  41. err = xml.Unmarshal(bytes, &event)
  42. if err != nil {
  43. logrus.Error("事件处理-解析错误:", err)
  44. return
  45. }
  46. //处理事件 todo 邮箱
  47. handleEvent_(event)
  48. } else if strings.Contains(contentType, "multipart/form-data") {
  49. fmt.Println("multipart/form-data 事件")
  50. //handleMultipart(r)
  51. } else {
  52. logrus.WithField("Content-Type", contentType).Error("该Content-Type没有写处理逻辑")
  53. return
  54. }
  55. }
  56. func handleEvent_(event EventNotificationAlert) string {
  57. var eType string
  58. if event.EventType == "duration" {
  59. eType = event.DurationList.Duration[0].RelationEvent
  60. } else {
  61. eType = event.EventType
  62. }
  63. return fmt.Sprintf("事件类型:%s,时间:%s", sMap[eType], timeFmt(event.DateTime))
  64. }
  65. func timeFmt(str string) string {
  66. s := strings.Split(str, "T")
  67. t := s[0]
  68. s1 := strings.Split(s[1], ".")
  69. s2 := strings.Split(s1[0], "+")
  70. return t + " " + s2[0]
  71. }
  72. func logRequest(req *http.Request) {
  73. // 打印请求行
  74. fmt.Printf("%s %s %s\n", req.Method, req.URL.Path, req.Proto)
  75. // 打印请求头
  76. for name, headers := range req.Header {
  77. for _, h := range headers {
  78. fmt.Printf("%v: %v\n", name, h)
  79. }
  80. }
  81. // 打印请求体
  82. body, _ := ioutil.ReadAll(req.Body)
  83. fmt.Printf("%s\n", body)
  84. }