-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
161 lines (140 loc) · 3.78 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package main
import (
"errors"
"fmt"
"net/http"
"os"
"reflect"
"runtime"
"runtime/debug"
"strings"
"github.com/eukarya-inc/reearth-plateauview/server/putil"
"github.com/eukarya-inc/reearth-plateauview/server/tool"
"github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
cms "github.com/reearth/reearth-cms-api/go"
"github.com/reearth/reearth-cms-api/go/cmswebhook"
"github.com/reearth/reearthx/appx"
"github.com/reearth/reearthx/log"
"github.com/reearth/reearthx/rerror"
"github.com/samber/lo"
"golang.org/x/net/http2"
)
func main() {
conf := lo.Must(NewConfig())
if len(os.Args) > 1 && os.Args[1] != "" {
tool.Main(&tool.Config{
CMS_BaseURL: conf.CMS_BaseURL,
CMS_Token: conf.CMS_Token,
}, os.Args[1:])
return
}
main2(conf)
}
func main2(conf *Config) {
log.Infof("reearth-plateauview\n")
log.Infof("config: %s", conf.Print())
if conf.GCParcent > 0 {
debug.SetGCPercent(conf.GCParcent)
}
logger := log.NewEcho()
e := echo.New()
e.HideBanner = true
e.HidePort = true
e.Logger = logger
e.HTTPErrorHandler = errorHandler(e.DefaultHTTPErrorHandler)
e.Validator = &customValidator{validator: validator.New()}
e.Use(
middleware.Recover(),
echo.WrapMiddleware(appx.RequestIDMiddleware()),
logger.AccessLogger(),
middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: conf.Origin,
}),
)
e.GET("/ping", func(c echo.Context) error {
return c.JSON(http.StatusOK, "pong")
}, putil.NoCacheMiddleware)
e.GET("/proxy/*", proxyHandlerFunc, ACAOHeaderOverwriteMiddleware)
services := lo.Must(Services(conf))
serviceNames := lo.Map(services, func(s *Service, _ int) string { return s.Name })
webhookHandlers := []cmswebhook.Handler{}
for _, s := range services {
if s.Echo != nil {
g := e.Group("")
if !s.DisableNoCache {
g.Use(putil.NoCacheMiddleware)
}
lo.Must0(s.Echo(g))
}
if s.Webhook != nil {
webhookHandlers = append(webhookHandlers, s.Webhook)
}
}
cmsWebhookHandler(
e.Group("/webhook"),
[]byte(conf.CMS_Webhook_Secret),
webhookHandlers,
)
log.Infof("enabled services: %v", serviceNames)
addr := fmt.Sprintf("[::]:%d", conf.Port)
log.Infof("http server started on %s", addr)
log.Fatalf("%v", e.StartH2CServer(addr, &http2.Server{}))
}
func errorHandler(next func(error, echo.Context)) func(error, echo.Context) {
return func(err error, c echo.Context) {
if c.Response().Committed {
return
}
code, msg := errorMessage(err, func(f string, args ...interface{}) {
c.Echo().Logger.Errorf(f, args...)
})
if err := c.JSON(code, map[string]string{
"error": msg,
}); err != nil {
next(err, c)
}
}
}
func errorMessage(err error, log func(string, ...interface{})) (int, string) {
code := http.StatusBadRequest
msg := err.Error()
if err2, ok := err.(*echo.HTTPError); ok {
code = err2.Code
if msg2, ok := err2.Message.(string); ok {
msg = msg2
} else if msg2, ok := err2.Message.(error); ok {
msg = msg2.Error()
} else {
msg = "error"
}
if err2.Internal != nil {
log("echo internal err: %+v", err2)
}
} else if errors.Is(err, rerror.ErrNotFound) {
code = http.StatusNotFound
msg = "not found"
} else if errors.Is(err, cms.ErrNotFound) {
code = http.StatusNotFound
msg = "not found"
} else {
if ierr := rerror.UnwrapErrInternal(err); ierr != nil {
code = http.StatusInternalServerError
msg = "internal server error"
}
}
return code, msg
}
type customValidator struct {
validator *validator.Validate
}
func (cv *customValidator) Validate(i any) error {
if err := cv.validator.Struct(i); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
return nil
}
func funcName(i interface{}) string {
return strings.TrimPrefix(runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name(), "main.")
}