This repository has been archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
97 lines (78 loc) · 1.79 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
package main
import (
"context"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/iand/meridian/ipfs"
"github.com/ipfs/go-ipfs/core/corehttp"
)
type Server struct {
Addr string
Net string
Gateway *ipfs.Gateway
mux *http.ServeMux
}
// New creates a new server with default values.
func NewServer(gw *ipfs.Gateway) *Server {
return &Server{
Addr: ":2525",
Net: "tcp",
Gateway: gw,
}
}
// Serve starts the server and blocks until the process receives a terminating operating system signal.
func (s *Server) Serve(ctx context.Context) error {
if s.Addr == "" {
s.Addr = ":2525"
}
if s.Net == "" {
s.Net = "tcp"
}
listener, err := net.Listen(s.Net, s.Addr)
if err != nil {
return fmt.Errorf("fatal error listening on %s: %w", s.Addr, err)
}
if err := s.registerHandlers(); err != nil {
return fmt.Errorf("fatal error registering handlers: %w", err)
}
hs := &http.Server{
Addr: s.Addr,
Handler: s,
}
go hs.Serve(listener)
s.waitSignal()
return nil
}
// waitSignal blocks waiting for operating system signals
func (s *Server) waitSignal() {
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
signalloop:
for sig := range ch {
switch sig {
case syscall.SIGINT, syscall.SIGTERM:
break signalloop
// TODO: support HUP to reload config
}
}
}
func (s *Server) registerHandlers() error {
s.mux = http.NewServeMux()
headers := make(map[string][]string)
corehttp.AddAccessControlHeaders(headers)
cfg := corehttp.GatewayConfig{
Writable: false,
Headers: headers,
}
gwHandler := corehttp.NewGatewayHandler(cfg, s.Gateway)
s.mux.Handle("/ipfs/", gwHandler)
s.mux.Handle("/ipns/", gwHandler)
return nil
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mux.ServeHTTP(w, r)
}