1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package eventServer
- import (
- "encoding/xml"
- "fmt"
- "github.com/sirupsen/logrus"
- "io/ioutil"
- "net/http"
- "strings"
- "time"
- )
- // MQDEvent (MQTT Data Event) 用于mqtt传输事件
- type MQDEvent struct {
- EventCode string `json:"eventCode"`
- EId int `json:"eId"`
- Ip string `json:"ip"`
- Type string `json:"type"`
- StartTime string `json:"startTime"`
- Name string `json:"name"`
- Data []byte `json:"data"`
- }
- func StartEventServer() {
- http.HandleFunc("/event", handler)
- logrus.Fatal("事件监听服务启动失败", http.ListenAndServe(":8850", nil))
- }
- func handler(w http.ResponseWriter, r *http.Request) {
- go func() {
- //监听主机应答固定,直接先应答
- w.WriteHeader(200)
- w.Header().Add("Date", time.Now().String())
- w.Header().Add("Connection", "close")
- }()
- //logRequest(r)
- contentType := r.Header.Get("Content-Type")
- if strings.Contains(contentType, "application/xml") {
- bytes, err := ioutil.ReadAll(r.Body)
- if err != nil {
- logrus.Error("事件处理-读取错误:", err)
- return
- }
- var event EventNotificationAlert
- err = xml.Unmarshal(bytes, &event)
- if err != nil {
- logrus.Error("事件处理-解析错误:", err)
- return
- }
- //处理事件 todo 邮箱
- handleEvent_(event)
- } else if strings.Contains(contentType, "multipart/form-data") {
- fmt.Println("multipart/form-data 事件")
- //handleMultipart(r)
- } else {
- logrus.WithField("Content-Type", contentType).Error("该Content-Type没有写处理逻辑")
- return
- }
- }
- func handleEvent_(event EventNotificationAlert) string {
- var eType string
- if event.EventType == "duration" {
- eType = event.DurationList.Duration[0].RelationEvent
- } else {
- eType = event.EventType
- }
- return fmt.Sprintf("事件类型:%s,时间:%s", sMap[eType], timeFmt(event.DateTime))
- }
- func timeFmt(str string) string {
- s := strings.Split(str, "T")
- t := s[0]
- s1 := strings.Split(s[1], ".")
- s2 := strings.Split(s1[0], "+")
- return t + " " + s2[0]
- }
- func logRequest(req *http.Request) {
- // 打印请求行
- fmt.Printf("%s %s %s\n", req.Method, req.URL.Path, req.Proto)
- // 打印请求头
- for name, headers := range req.Header {
- for _, h := range headers {
- fmt.Printf("%v: %v\n", name, h)
- }
- }
- // 打印请求体
- body, _ := ioutil.ReadAll(req.Body)
- fmt.Printf("%s\n", body)
- }
|