/
app.go
116 lines (96 loc) · 2.29 KB
/
app.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
package web
import (
"context"
"embed"
"github.com/gin-contrib/gzip"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/zgwit/iot-master/v2/internal/web/api"
"github.com/zgwit/iot-master/v2/pkg/log"
"mime"
"net/http"
"path"
"strings"
"time"
)
func init() {
err := mime.AddExtensionType(".js", "application/javascript")
if err != nil {
log.Error(err)
}
}
//go:embed all:www
var wwwFiles embed.FS
var server *http.Server
func Serve(addr string) {
gin.SetMode(gin.ReleaseMode)
//GIN初始化
//app := gin.Default()
app := gin.New()
app.Use(gin.Recovery())
//if cfg.Debug {
app.Use(gin.Logger())
//启用session
app.Use(sessions.Sessions("iot-master", cookie.NewStore([]byte("iot-master"))))
//开启压缩
//if cfg.Compress {
app.Use(gzip.Gzip(gzip.DefaultCompression)) //gzip.WithExcludedPathsRegexs([]string{".*"})
//注册前端接口
api.RegisterRoutes(app.Group("/api"))
//前端静态文件
//app.StaticFS("/www", http.FS(wwwFiles))
wwwFS := http.FS(wwwFiles)
app.Use(func(c *gin.Context) {
if c.Request.Method == http.MethodGet {
//支持前端框架的无“#”路由
fn := path.Join("www", c.Request.URL.Path) //删除查询参数
f, err := wwwFS.Open(fn)
if err == nil {
defer f.Close()
stat, err := f.Stat()
if err != nil {
c.Next() //500错误
return
}
if !stat.IsDir() {
http.ServeContent(c.Writer, c.Request, fn, stat.ModTime(), f)
return
}
}
//默认首页
f, err = wwwFS.Open("www/index.html")
if err != nil {
c.Next()
return
}
defer f.Close()
fn += ".html" //避免DetectContentType
http.ServeContent(c.Writer, c.Request, fn, time.Now(), f)
}
})
//监听HTTP
//if err := app.Run(cfg.Addr); err != nil {
// log.Fatal("HTTP 服务启动错误", err)
//}
log.Println("Web服务启动", addr)
server = &http.Server{
Addr: resolvePort(addr),
Handler: app,
}
err := server.ListenAndServe()
if err != nil {
log.Fatal("Web服务启动错误", err)
}
}
func Close() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return server.Shutdown(ctx)
}
func resolvePort(addr string) string {
if strings.IndexByte(addr, ':') == -1 {
return ":" + addr
}
return addr
}