-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
121 lines (102 loc) · 2.46 KB
/
main.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package main
import (
"flag"
"fmt"
"net/http"
"strconv"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/labstack/gommon/log"
"github.com/ww24/lirc-web-api/config"
"github.com/ww24/lirc-web-api/lirc"
)
var (
// -ldflags "-X main.version=$API_VERSION"
version string
outputAPIVersion bool
apiPort int
frontendPath string
)
func wrapError(err error) error {
return &response{
code: http.StatusInternalServerError,
Status: "ng",
Message: err.Error(),
}
}
func init() {
flag.BoolVar(&outputAPIVersion, "v", false, "output version")
flag.IntVar(&apiPort, "p", 3000, "set API port")
flag.StringVar(&frontendPath, "f", "./frontend", "frontend path")
flag.Parse()
}
func main() {
if outputAPIVersion {
fmt.Println(version)
return
}
e := echo.New()
e.Logger.SetLevel(log.INFO)
e.Logger.Infof("API version: %s", version)
e.Logger.Infof("Running mode: %s", config.Mode)
e.Pre(middleware.RemoveTrailingSlash())
e.GET("/status", func(c echo.Context) error {
client, err := lirc.New()
if err != nil {
return c.JSON(http.StatusInternalServerError, &status{
Status: "ng",
Message: err.Error(),
})
}
defer client.Close()
lircdVersion, err := client.Version()
if err != nil {
return c.JSON(http.StatusInternalServerError, &status{
Status: "ng",
Message: err.Error(),
})
}
return c.JSON(http.StatusOK, &status{
Status: "ok",
Message: "LIRC Web API works",
Version: version,
LIRCDVersion: lircdVersion,
})
})
// create api v1 group and set error handling middleware
apiv1g := e.Group("/api/v1", func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
msg := "unknown"
defer func() {
cause := recover()
if cause != nil {
e.Logger.Errorf("Panic:%v", cause)
if err, ok := cause.(error); ok && config.IsDev() {
msg = err.Error()
}
c.JSON(http.StatusInternalServerError, &response{
Status: "ng",
Message: msg,
})
}
}()
err := next(c)
if err != nil {
if res, ok := err.(*response); ok {
if res.Status == "ok" {
return c.JSON(res.code, res)
}
e.Logger.Errorf("InternalServerError:%s", res)
if config.IsProd() {
res.Message = msg
}
return c.JSON(http.StatusInternalServerError, res)
}
}
return err
}
})
apiv1(apiv1g)
e.Static("/", frontendPath)
e.Logger.Fatal(e.Start(":" + strconv.Itoa(apiPort)))
}