-
Notifications
You must be signed in to change notification settings - Fork 971
/
main.go
176 lines (161 loc) · 4.63 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/*
* Copyright (c) 2021 yedf. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
// package main is the entry of dtm server
package main
import (
"bytes"
"compress/gzip"
"embed"
"fmt"
"io"
"io/fs"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"github.com/dtm-labs/dtm/dtmsvr/config"
"github.com/dtm-labs/dtm/dtmsvr/entry"
_ "github.com/dtm-labs/dtm/dtmsvr/microservices"
"github.com/dtm-labs/logger"
"github.com/gin-gonic/gin"
)
// Version defines version info. It is set by -ldflags.
var Version string
func main() {
app, conf := entry.Main(&Version)
if app != nil {
addAdmin(app, conf)
q := make(chan os.Signal, 1)
signal.Notify(q, syscall.SIGINT, syscall.SIGTERM)
<-q
logger.Infof("Shutdown dtm server...")
}
}
//go:embed admin/dist
var admin embed.FS
var target = ""
func getSub(f1 fs.FS, subs ...string) fs.FS {
var err error
for _, sub := range subs {
f1, err = fs.Sub(f1, sub)
logger.FatalIfError(err)
}
return f1
}
func addAdmin(app *gin.Engine, conf *config.Type) {
// for released dtm, serve admin from local files because the build output has been embed
// for testing users, proxy admin to target because the build output has not been embed
dist := getSub(admin, "admin", "dist")
index, err := dist.Open("index.html")
var router gin.IRoutes = app
if len(conf.AdminBasePath) > 0 {
router = app.Group(conf.AdminBasePath)
}
if err == nil {
cont, err := io.ReadAll(index)
logger.FatalIfError(err)
_ = index.Close()
cont = bytesTryReplaceIndex(cont, conf)
renderIndex := func(c *gin.Context) {
c.Data(200, "text/html; charset=utf-8", cont)
}
router.StaticFS("/assets", http.FS(getSub(dist, "assets")))
router.GET("/admin/*name", renderIndex)
router.GET("/", renderIndex)
router.GET("/favicon.ico", func(ctx *gin.Context) {
http.StripPrefix(conf.AdminBasePath, http.FileServer(http.FS(dist))).ServeHTTP(ctx.Writer, ctx.Request)
})
logger.Infof("admin is served from dir 'admin/dist/'")
} else {
router.GET("/", proxyAdmin(conf))
router.GET("/assets/*name", proxyAdmin(conf))
router.GET("/admin/*name", proxyAdmin(conf))
lang := os.Getenv("LANG")
if strings.HasPrefix(lang, "zh_CN") {
target = "cn-admin.dtm.pub"
} else {
target = "admin.dtm.pub"
}
logger.Infof("admin is proxied to %s", target)
}
logger.Infof("admin is running at: http://localhost:%d%s", conf.HTTPPort, conf.AdminBasePath)
}
func proxyAdmin(conf *config.Type) func(c *gin.Context) {
return func(c *gin.Context) {
u := &url.URL{}
u.Scheme = "http"
u.Host = target
proxy := httputil.NewSingleHostReverseProxy(u)
originalDirector := proxy.Director
proxy.Director = func(r *http.Request) {
originalDirector(r)
p := strings.TrimPrefix(r.URL.Path, conf.AdminBasePath)
rp := strings.TrimPrefix(r.URL.RawPath, conf.AdminBasePath)
r.URL.Path = p
r.URL.RawPath = rp
}
proxy.Transport = &transport{RoundTripper: http.DefaultTransport, conf: conf}
proxy.ErrorHandler = func(rw http.ResponseWriter, req *http.Request, err error) {
logger.Warnf("http: proxy error: %v", err)
ret := fmt.Sprintf("http proxy error %v", err)
_, _ = rw.Write([]byte(ret))
}
logger.Debugf("proxy admin to %s", target)
c.Request.Host = target
proxy.ServeHTTP(c.Writer, c.Request)
}
}
// bytesTryReplaceIndex replace index.html base path
func bytesTryReplaceIndex(source []byte, conf *config.Type) []byte {
source = bytes.Replace(source, []byte("\"assets/"), []byte("\"" conf.AdminBasePath "/assets/"), -1)
source = bytes.Replace(source, []byte("PUBLIC-PATH-VARIABLE"), []byte(conf.AdminBasePath), -1)
return source
}
type transport struct {
http.RoundTripper
conf *config.Type
}
func (t *transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
resp, err = t.RoundTripper.RoundTrip(req)
if err != nil {
return nil, err
}
//modify html only
if !strings.Contains(resp.Header.Get("Content-Type"), "text/html") {
return resp, err
}
var reader io.ReadCloser
switch resp.Header.Get("Content-Encoding") {
case "gzip":
reader, err = gzip.NewReader(resp.Body)
defer func() {
if tmpErr := reader.Close(); err == nil && tmpErr != nil {
err = tmpErr
}
}()
default:
reader = resp.Body
}
delete(resp.Header, "Content-Encoding")
b, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
err = resp.Body.Close()
if err != nil {
return nil, err
}
b = bytesTryReplaceIndex(b, t.conf)
body := io.NopCloser(bytes.NewReader(b))
resp.Body = body
resp.ContentLength = int64(len(b))
resp.Header.Set("Content-Length", strconv.Itoa(len(b)))
return resp, nil
}