-
Notifications
You must be signed in to change notification settings - Fork 8
/
simple_server.go
99 lines (92 loc) · 2.02 KB
/
simple_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
90
91
92
93
94
95
96
97
98
99
package httpproxy
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
)
// SimpleServer is a simplified server, which can be configured as easily as client.
type SimpleServer struct {
ProxyHandler
Server http.Server
Listener net.Listener
Network string
Address string
Username string
Password string
}
// NewSimpleServer creates a new SimpleServer
func NewSimpleServer(addr string) (*SimpleServer, error) {
s := &SimpleServer{}
u, err := url.Parse(addr)
if err != nil {
return nil, err
}
switch u.Scheme {
case "http":
default:
return nil, fmt.Errorf("unsupported protocol '%s'", u.Scheme)
}
host := u.Host
port := u.Port()
if port == "" {
port = "80"
hostname := u.Hostname()
host = net.JoinHostPort(hostname, port)
}
if u.User != nil {
s.Username = u.User.Username()
s.Password, _ = u.User.Password()
s.Authentication = BasicAuth(s.Username, s.Password)
}
s.Server.Handler = &s.ProxyHandler
s.Address = host
s.Network = "tcp"
return s, nil
}
// Run the server
func (s *SimpleServer) Run(ctx context.Context) error {
var listenConfig net.ListenConfig
if s.Listener == nil {
listener, err := listenConfig.Listen(ctx, s.Network, s.Address)
if err != nil {
return err
}
s.Listener = listener
}
s.Address = s.Listener.Addr().String()
return s.Server.Serve(s.Listener)
}
// Start the server
func (s *SimpleServer) Start(ctx context.Context) error {
var listenConfig net.ListenConfig
if s.Listener == nil {
listener, err := listenConfig.Listen(ctx, s.Network, s.Address)
if err != nil {
return err
}
s.Listener = listener
}
s.Address = s.Listener.Addr().String()
go s.Server.Serve(s.Listener)
return nil
}
// Close closes the listener
func (s *SimpleServer) Close() error {
if s.Listener == nil {
return nil
}
return s.Listener.Close()
}
// ProxyURL returns the URL of the proxy
func (s *SimpleServer) ProxyURL() string {
u := url.URL{
Scheme: "http",
Host: s.Address,
}
if s.Username != "" {
u.User = url.UserPassword(s.Username, s.Password)
}
return u.String()
}