-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.go
92 lines (72 loc) · 2.15 KB
/
core.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
package core
import (
"net/http"
"net/http/httputil"
"github.com/gin-gonic/gin"
)
type TorimaPackageStatus = int
const (
AuthNeeded TorimaPackageStatus = iota
Authed
NoAuthNeeded
ForceStop
Keep
)
type TorimaPackageTarget interface{ *http.Request | *http.Response }
type TorimaPackageContext[T TorimaPackageTarget] struct {
Proxy *TorimaProxy
Target T
GinContext *gin.Context
PackageStatus TorimaPackageStatus
}
type TorimaDirectorPackageContext = TorimaPackageContext[*http.Request]
type TorimaModifyResponsePackageContext = TorimaPackageContext[*http.Response]
type TorimaDirector func(*TorimaDirectorPackageContext) (TorimaPackageStatus, error)
type TorimaModifyResponse func(*TorimaModifyResponsePackageContext) (TorimaPackageStatus, error)
type TorimaDirectors []func(*TorimaDirectorPackageContext) (TorimaPackageStatus, error)
type TorimaModifyResponses []func(*TorimaModifyResponsePackageContext) (TorimaPackageStatus, error)
type TorimaProxyWebPage = func(proxy *TorimaProxy, c *gin.RouterGroup)
type TorimaProxy struct {
Directors TorimaDirectors
ModifyResponses TorimaModifyResponses
ProxyWebPages []TorimaProxyWebPage
Engine *gin.Engine
Database *Database
ErrorHandler *gin.HandlerFunc
Config *TorimaConfig
RequestCount int
}
func NewOchancoProxy(
r *gin.Engine,
directors TorimaDirectors,
modifyResponses TorimaModifyResponses,
proxyWebPages []TorimaProxyWebPage,
config *TorimaConfig,
database *Database,
) TorimaProxy {
proxy := TorimaProxy{}
proxy.Directors = directors
proxy.ModifyResponses = modifyResponses
proxy.ProxyWebPages = proxyWebPages
proxy.Database = database
proxy.Engine = r
proxy.Config = config
specialPath := r.Group("/torima")
for _, webPage := range proxy.ProxyWebPages {
webPage(&proxy, specialPath)
}
r.NoRoute(func(c *gin.Context) {
director := func(req *http.Request) {
proxy.Director(req, c)
}
modifyResp := func(resp *http.Response) error {
return proxy.ModifyResponse(resp, c)
}
proxy := httputil.ReverseProxy{
Director: director,
ModifyResponse: modifyResp,
}
proxy.ServeHTTP(c.Writer, c.Request)
})
return proxy
}