-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.go
89 lines (77 loc) · 2.29 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"context"
"crypto/tls"
"github.com/azak-azkaran/cascade/utils"
"github.com/azak-azkaran/goproxy"
//"github.com/urfave/negroni"
"net/http"
"syscall"
"time"
)
// CurrentServer the running httpserver
var CurrentServer *http.Server
// true if the server has started
var running = false
// RunServer : Starts the Server which selects the Mode in which it should be running,
func RunServer() {
go func() {
counter := 5
for CurrentServer == nil {
utils.Sugar.Warn("Server was not created waiting for a one second")
time.Sleep(1 * time.Second)
counter = counter - 1
if counter <= 0 {
utils.Sugar.Error("Server was not created in time")
stopChan <- syscall.SIGINT
}
}
running = true
err := CurrentServer.ListenAndServe()
if err != nil {
if err == http.ErrServerClosed {
utils.Sugar.Info("Server was closed")
} else {
utils.Sugar.Error("Error while running server: ", err)
}
}
running = false
}()
utils.Sugar.Info("Server started")
}
//ShutdownCurrentServer Shuts down the current server with a 1 Second timeout
func ShutdownCurrentServer() {
if CurrentServer != nil {
shutdown(1*time.Second, CurrentServer)
CurrentServer = nil
ClearHostList()
}
}
func shutdown(timeout time.Duration, server *http.Server) {
utils.Sugar.Info("Starting shutdown with Timout: ", timeout)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
err := server.Shutdown(ctx)
if err != nil {
utils.Sugar.Error("Error while shutdown: ", err)
}
}
func create(proxy *goproxy.ProxyHttpServer, addr string, config *Yaml) *http.Server {
return &http.Server{
Addr: addr + ":" + config.LocalPort,
Handler: ConfigureRouter(proxy, addr, config.Verbose),
// Disable HTTP/2.
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}
}
// CreateServer creates a proxy server on addr:port
func CreateServer(config *Yaml) *http.Server {
utils.Sugar.Warn("Creating Proxy on: localhost", ":", config.LocalPort)
proxy := CASCADE.Run(config.Verbose, config.ProxyURL, config.Username, config.Password)
HandleCustomProxies(config.proxyRedirectList)
CurrentServer = create(proxy, "localhost", config)
return CurrentServer
}