-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
89 lines (80 loc) · 1.67 KB
/
server.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/reconquest/hierr-go"
"net/http"
"errors"
)
type Server struct {
router *gin.Engine
commands chan<- VKCommand
}
func NewServer(commands chan<- VKCommand, verbose bool) *Server {
if !verbose {
gin.SetMode(gin.ReleaseMode)
}
return &Server{
router: gin.Default(),
commands: commands,
}
}
func (proxy *Server) Run(addr ...string) error {
proxy.router.POST("/method/:name", proxy.handleMessagesSend)
return proxy.router.Run(addr...)
}
func (proxy *Server) handleMessagesSend(ctx *gin.Context) {
request := ctx.Request
if err := request.ParseForm(); err != nil {
abort(
ctx,
http.StatusBadRequest,
hierr.Errorf(err, "unable to parse form data"),
)
return
}
request.ParseMultipartForm(32 << 10) // 32 MB
accessToken := request.Form.Get("access_token")
if accessToken == "" {
accessToken = ctx.Query("access_token")
}
if accessToken == "" {
abort(
ctx,
http.StatusBadRequest,
errors.New("access_token is required"),
)
return
}
payload := make(map[string]interface{})
for k, v := range request.Form {
if v == nil || k == "access_token" {
continue
}
switch len(v) {
case 0:
continue
case 1:
payload[k] = v[0]
case 2:
payload[k] = v
}
}
proxy.commands <- VKCommand{
AccessToken: accessToken,
Method: fmt.Sprintf("API.%s", ctx.Param("name")),
Payload: payload,
}
ctx.JSON(http.StatusOK, gin.H{"success": true})
}
func abort(ctx *gin.Context, code int, err error) {
if code >= http.StatusInternalServerError {
logger.Error(err)
}
ctx.Error(err)
ctx.JSON(code, gin.H{
"success": false,
"error": err.Error(),
})
ctx.Abort()
}