-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
265 lines (248 loc) · 5.5 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package main
import (
"fmt"
"github.com/valyala/fasthttp"
"log"
"net/url"
"os"
"path/filepath"
fasthttpWebsocket "github.com/fasthttp/websocket"
"github.com/gofiber/contrib/websocket"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/proxy"
"github.com/gofiber/fiber/v2/middleware/session"
"github.com/kirsle/configdir"
"github.com/yejun614/dev-proxy/data"
)
const (
VERSION = "v1.0"
)
var (
DB *data.Data[ProxyData]
App *fiber.App
store = session.New()
wsFunc = websocket.New(websocketHandler)
wsChan = make(chan string, 10)
)
type ProxyData struct {
Addr string `json:"addr" xml:"addr" form:"addr"`
Proxies map[string]string `json:"proxies" xml:"proxies" form:"proxies"`
Statics map[string]string `json:"statics" xml:"statics" form:"statics"`
}
func addStatics() {
for key := range DB.Data.Statics {
value := DB.Data.Statics[key]
if _, err := os.Stat(value); os.IsNotExist(err) {
log.Printf("%s: %s directory not found\n", key, value)
continue
}
App.Static(key, value)
}
}
func hello(c *fiber.Ctx) error {
return c.SendString("DEV PROXY SERVER")
}
func sessionRedirect(c *fiber.Ctx) error {
// session
sess, err := store.Get(c)
if err != nil {
log.Fatal(err)
}
sessKey := sess.Get("key")
// get key and url
key := c.Params("key")
log.Printf("key: %s\n", key)
// check proxies
_, check := DB.Data.Proxies[key]
if !check {
_, check = DB.Data.Statics[key]
}
if check {
if key != "favicon.ico" {
// set session
sess.Set("key", key)
log.Printf("session save: %s\n", key)
}
} else if sessKey != nil {
// redirect
log.Printf("session redirect: %s\n", c.Path())
if sessKey == "" {
c.Path(fmt.Sprintf("/%s", c.Path()[1:]))
} else {
c.Path(fmt.Sprintf("/%s/%s", sessKey, c.Path()[1:]))
}
}
// session save
if err := sess.Save(); err != nil {
log.Fatal(err)
}
// next
return c.Next()
}
func proxyAnother(c *fiber.Ctx) error {
// get key and url
key := c.Params("key")
// check proxies
proxyAddr, check := DB.Data.Proxies[key]
if !check {
key = ""
proxyAddr, check = DB.Data.Proxies[key]
if !check {
// not found error
return c.SendStatus(fiber.StatusNotFound)
}
}
// proxy url
path := c.OriginalURL()[len(key)+1:]
proxyUrl, err := url.JoinPath(proxyAddr, path)
if err != nil {
log.Fatal(err)
}
// regenerate for path
proxyUrl, err = url.PathUnescape(proxyUrl)
if err != nil {
log.Fatal(err)
}
// websocket
if websocket.IsWebSocketUpgrade(c) {
c.Locals("allowed", true)
log.Println("websocket start")
log.Printf("chan send %s\n", proxyUrl)
wsChan <- proxyUrl
return wsFunc(c)
}
// create proxy url
log.Printf("Proxy: %s -> %s\n", c.Path(), proxyUrl)
// create proxy client
client := &fasthttp.Client{
ReadBufferSize: 40890,
}
// let's proxy
if err := proxy.DoRedirects(c, proxyUrl, 100, client); err != nil {
return err
}
// add cors headers
c.Append("Access-Control-Allow-Origin", "*")
// set session
sess, err := store.Get(c)
if err != nil {
log.Fatal(err)
}
sess.Set("key", key)
if err := sess.Save(); err != nil {
log.Fatal(err)
}
// done
return nil
}
func websocketHandler(c *websocket.Conn) {
var (
closeChan = make(chan bool)
client *fasthttpWebsocket.Conn
)
proxyUrl, err := url.Parse(<-wsChan)
if err != nil {
log.Println(err)
return
}
proxyUrl.Scheme = "ws"
log.Printf("ws proxyUrl: %s\n", proxyUrl.String())
client, _, err = fasthttpWebsocket.DefaultDialer.Dial(proxyUrl.String(), nil)
if err != nil {
log.Println(err)
return
}
defer client.Close()
go func() {
var (
mt int
msg []byte
err error
)
for {
// client -> proxy
if mt, msg, err = c.ReadMessage(); err != nil {
log.Println(err)
break
}
// debug
log.Printf("client -> proxy: %s\n", string(msg))
// proxy -> server
if err = client.WriteMessage(mt, msg); err != nil {
log.Println(err)
break
}
}
closeChan <- true
log.Println("ws closed from client")
}()
go func() {
var (
mt int
msg []byte
err error
)
for {
// proxy <- server
if mt, msg, err = client.ReadMessage(); err != nil {
log.Println(err)
break
}
// debug
log.Printf("client <- proxy: %s\n", string(msg))
// client <- proxy
if err = c.WriteMessage(mt, msg); err != nil {
log.Println(err)
break
}
}
closeChan <- true
log.Println("ws closed from server")
}()
<-closeChan
log.Println("websocket done")
}
func StartServer() {
// config path
configFile := "./proxy.dev.json"
configPath := configdir.LocalConfig("dev-proxy")
err := configdir.MakePath(configPath)
if err == nil {
configFile = filepath.Join(configPath, "./proxy.dev.json")
}
log.Printf("config file: %s\n", configFile)
// database
DB = data.New[ProxyData](configFile, ProxyData{
Addr: "localhost:8000",
})
// create fiber app
App = fiber.New()
// add middlewares
App.Use(logger.New())
App.Use(cors.New())
// admin routes
admin := App.Group("/dev-proxy/")
admin.Get("/hello", hello)
admin.Get("/admin", adminGetPage)
admin.Get("/data", adminGetData)
admin.Post("/data", adminPostData)
// session redirect middleware
App.Use("/:key/*", sessionRedirect)
// add statics
addStatics()
// add routes
App.All("/:key/*", proxyAnother)
// root routes
App.All("/", proxyAnother)
// start fiber app
log.Println("Press Ctrl+C to shut down the server.")
App.Listen(DB.Data.Addr)
}
func main() {
for {
log.Println("Server Start")
StartServer()
}
}