-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
107 lines (84 loc) · 2.24 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package gatego
import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"time"
"github.com/hvuhsg/gatego/internal/config"
"github.com/hvuhsg/gatego/pkg/multimux"
)
type gategoServer struct {
*http.Server
}
func newServer(ctx context.Context, config config.Config, useOtel bool) (*gategoServer, error) {
multimuxer, err := createMultiMuxer(ctx, config.Services, useOtel)
if err != nil {
return nil, err
}
addr := fmt.Sprintf("%s:%d", config.Host, config.Port)
// Start HTTP server.
server := &http.Server{
Addr: addr,
BaseContext: func(_ net.Listener) context.Context { return ctx },
ReadTimeout: time.Second,
WriteTimeout: 10 * time.Second,
Handler: multimuxer,
}
return &gategoServer{Server: server}, nil
}
func createMultiMuxer(ctx context.Context, services []config.Service, useOtel bool) (*multimux.MultiMux, error) {
mm := multimux.NewMultiMux()
for _, service := range services {
for _, path := range service.Paths {
handler, err := NewHandler(ctx, useOtel, service, path)
if err != nil {
return nil, err
}
mm.RegisterHandler(service.Domain, path.Path, handler)
}
}
return mm, nil
}
func (gs *gategoServer) serve(certfile *string, keyfile *string) (chan error, error) {
supportTLS, err := checkTLSConfig(certfile, keyfile)
if err != nil {
return nil, err
}
serveErr := make(chan error, 1)
go func() {
if supportTLS {
log.Default().Printf("Serving proxy with TLS %s\n", gs.Addr)
serveErr <- gs.ListenAndServeTLS(*certfile, *keyfile)
} else {
log.Default().Printf("Serving proxy %s\n", gs.Addr)
serveErr <- gs.ListenAndServe()
}
}()
return serveErr, nil
}
func checkTLSConfig(certfile *string, keyfile *string) (bool, error) {
if keyfile == nil || certfile == nil || *keyfile == "" || *certfile == "" {
return false, nil
}
if !fileExists(*keyfile) {
return false, fmt.Errorf("can't find keyfile at '%s'", *keyfile)
}
if !fileExists(*certfile) {
return false, fmt.Errorf("can't find certfile at '%s'", *certfile)
}
return true, nil
}
func fileExists(filepath string) bool {
_, err := os.Stat(filepath)
if os.IsNotExist(err) {
return false
}
// If we cant check the file info we probably can't open the file
if err != nil {
return false
}
return true
}