/
http_srv.go
130 lines (110 loc) · 3.42 KB
/
http_srv.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
package server
import (
"fmt"
"github.com/ninjahome/web-bridge/util"
"log"
"net/http"
"os"
"path/filepath"
"runtime/debug"
"strings"
"time"
)
const (
staticFileDir = "assets"
)
type MainService struct {
}
func httpRecover(url string) {
if r := recover(); r != nil {
stack := debug.Stack()
util.LogInst().Error().Str("method", url).
Str("panic", fmt.Sprintf("%v", r)).
Str("stack", string(stack)).
Msg("api service failed")
}
}
func NewMainService() *MainService {
bh := &MainService{}
http.Handle("/"+staticFileDir+"/", http.StripPrefix("/"+staticFileDir+"/", http.HandlerFunc(bh.assetsRouter)))
for route, fileName := range cfgHtmlFileRouter {
http.HandleFunc(route, bh.simpleRouter(fileName))
}
for route, twService := range cfgActionRouter {
var url, action = route, twService
http.HandleFunc(url, func(writer http.ResponseWriter, request *http.Request) {
defer httpRecover(url)
util.LogInst().Debug().Str("url", url).Send()
if request.Method != http.MethodPost && request.Method != http.MethodGet {
http.Error(writer, "", http.StatusMethodNotAllowed)
return
}
if request.ContentLength > util.MaxReqContentLen {
err := fmt.Errorf("content length too large (%d>%d)", request.ContentLength, util.MaxReqContentLen)
http.Error(writer, err.Error(), http.StatusRequestEntityTooLarge)
return
}
if !action.NeedToken {
action.Action(writer, request, nil)
return
}
var token = validateUsrRights(request)
if token == nil {
http.Redirect(writer, request, "/signIn", http.StatusFound)
return
}
action.Action(writer, request, token)
})
}
return bh
}
func (bh *MainService) Start() {
cfg := _globalCfg
if cfg.UseHttps {
if cfg.SSLCertFile == "" || cfg.SSLKeyFile == "" {
panic("HTTPS needs ssl key and cert files")
}
fmt.Print("HTTPS Mode")
panic(http.ListenAndServeTLS(":443", cfg.SSLCertFile, cfg.SSLKeyFile, nil))
} else {
fmt.Print("Simple HTTP")
panic(http.ListenAndServe(":"+cfg.HttpPort, nil))
}
}
func (bh *MainService) simpleRouter(fileName string) func(http.ResponseWriter, *http.Request) {
return func(writer http.ResponseWriter, request *http.Request) {
bh.assetsStaticFile(writer, request, fileName)
}
}
func (bh *MainService) assetsRouter(writer http.ResponseWriter, request *http.Request) {
realUrlPath := request.URL.Path
if strings.HasSuffix(realUrlPath, ".map") {
realUrlPath = strings.TrimSuffix(realUrlPath, ".map")
}
bh.assetsStaticFile(writer, request, realUrlPath)
}
func (bh *MainService) assetsStaticFile(writer http.ResponseWriter, request *http.Request, fileName string) {
fPath := filepath.Join(staticFileDir, fileName)
fileInfo, err := os.Stat(fPath)
if err != nil {
if os.IsNotExist(err) {
http.Error(writer, "File not found", http.StatusNotFound)
} else {
http.Error(writer, "Internal Server Error", http.StatusInternalServerError)
}
log.Print(err)
return
}
modTime := fileInfo.ModTime()
if _globalCfg.RefreshContent {
writer.Header().Set("Cache-Control", "max-age=0, no-store, must-revalidate")
} else {
writer.Header().Set("Cache-Control", "public, max-age=1036000") // 缓存10天
}
writer.Header().Set("Last-Modified", modTime.UTC().Format(http.TimeFormat))
if t, err := time.Parse(http.TimeFormat, request.Header.Get("If-Modified-Since")); err == nil && modTime.Before(t.Add(1*time.Second)) {
writer.WriteHeader(http.StatusNotModified)
return
}
http.ServeFile(writer, request, fPath)
}