-
Notifications
You must be signed in to change notification settings - Fork 116
/
server_rest.go
72 lines (59 loc) · 1.59 KB
/
server_rest.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
// Copyright 2018 The SQLer Authors. All rights reserved.
// Use of this source code is governed by a Apache 2.0
// license that can be found in the LICENSE file.
package main
import (
"strings"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
// initialize RESTful server
func initRESTServer() error {
e := echo.New()
e.HideBanner = true
e.HidePort = true
e.Pre(middleware.RemoveTrailingSlash())
e.Use(middleware.CORS())
e.Use(middleware.GzipWithConfig(middleware.GzipConfig{Level: 9}))
e.Use(middleware.Recover())
e.GET("/", routeIndex)
e.Any("/:macro", routeExecMacro, middlewareAuthorize)
return e.Start(*flagRESTListenAddr)
}
// middlewareAuthorize - the authorizer middleware
func middlewareAuthorize(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if strings.HasPrefix(c.Param("macro"), "_") {
return c.JSON(403, map[string]interface{}{
"success": false,
"error": "access not allowed",
})
}
macro := macrosManager.Get(c.Param("macro"))
if macro == nil {
return c.JSON(404, map[string]interface{}{
"success": false,
"error": "resource not found",
})
}
if len(macro.Methods) < 1 {
macro.Methods = []string{c.Request().Method}
}
methodIsAllowed := false
for _, method := range macro.Methods {
method = strings.ToUpper(method)
if c.Request().Method == method {
methodIsAllowed = true
break
}
}
if !methodIsAllowed {
return c.JSON(405, map[string]interface{}{
"success": false,
"error": "method not allowed",
})
}
c.Set("macro", macro)
return next(c)
}
}