-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhttp.go
57 lines (50 loc) · 1.31 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"bytes"
"encoding/json"
"muvtuberdriver/model"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"golang.org/x/exp/slog"
)
// TextInFromHTTP listen addr, wait TextIn from requests and send them to textInChan:
//
// POST routePath
// Content-Type: application/json
// { "author": "author", "content": "content" }
//
// routePath is the path of the route, default is "/".
func TextInFromHTTP(addr string, routePath string, textInChan chan<- *model.TextIn) {
if strings.TrimSpace(routePath) == "" {
routePath = "/"
}
// no logger
r := gin.New()
r.Use(gin.Recovery())
r.POST(routePath, func(c *gin.Context) {
var textIn model.TextIn
if err := c.BindJSON(&textIn); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
slog.Info("[TextInFromHTTP] recv TextIn from HTTP.", "author", textIn.Author, "priority", textIn.Priority, "content", textIn.Content)
textInChan <- &textIn
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
r.Run(addr)
}
func TextOutToHttp(addr string, textOut *model.TextOut) {
if addr == "" {
return
}
j, err := json.Marshal(textOut)
if err != nil {
slog.Error("[TextOutToHttp] marshal json error", "err", err)
return
}
http.Post(addr, "application/json", bytes.NewReader(j))
}
func init() {
gin.SetMode(gin.ReleaseMode)
}