-
Notifications
You must be signed in to change notification settings - Fork 39
/
server.go
75 lines (65 loc) · 2.08 KB
/
server.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
package main
import (
"fmt"
"net/http"
"os"
"github.com/chengjoey/web-terminal/views"
"github.com/gin-gonic/gin"
)
var (
EnvGOPATH = os.Getenv("GOPATH")
TemplateFiles = fmt.Sprintf("%s/src/github.com/chengjoey/web-terminal/templates/*.html", EnvGOPATH)
StaticFiles = fmt.Sprintf("%s/src/github.com/chengjoey/web-terminal/templates/static", EnvGOPATH)
)
//对产生的任何error进行处理
func JSONAppErrorReporter() gin.HandlerFunc {
return jsonAppErrorReporterT(gin.ErrorTypeAny)
}
func jsonAppErrorReporterT(errType gin.ErrorType) gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
detectedErrors := c.Errors.ByType(errType)
if len(detectedErrors) > 0 {
err := detectedErrors[0].Err
var parsedError *views.ApiError
switch err.(type) {
//如果产生的error是自定义的结构体,转换error,返回自定义的code和msg
case *views.ApiError:
parsedError = err.(*views.ApiError)
default:
parsedError = &views.ApiError{
Code: http.StatusInternalServerError,
Message: err.Error(),
}
}
c.IndentedJSON(parsedError.Code, parsedError)
return
}
}
}
//设置所有跨域请求
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
func main() {
server := gin.Default()
server.LoadHTMLGlob(TemplateFiles)
server.Static("/static", StaticFiles)
server.Use(JSONAppErrorReporter())
server.Use(CORSMiddleware())
server.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", nil)
})
server.GET("/ws", views.ShellWs)
server.Run("0.0.0.0:5001")
}