-
Notifications
You must be signed in to change notification settings - Fork 9
/
server.go
65 lines (57 loc) · 1.48 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
package putiosync
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"time"
"github.com/cenkalti/log"
)
const (
serverReadTimeout = 5 * time.Second
serverWriteTimeout = 10 * time.Second
serverShutdownTimeout = 5 * time.Second
)
type httpServer struct {
srv *http.Server
}
func newServer(addr string) *httpServer {
m := http.NewServeMux()
m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("putio-sync")) })
m.HandleFunc("/syncing", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(fmt.Sprintf("%v", syncing))) })
m.HandleFunc("/trigger", func(w http.ResponseWriter, r *http.Request) { triggerSync() })
m.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
b, _ := json.Marshal(map[string]string{"status": syncStatus})
_, _ = w.Write(b)
})
s := &httpServer{
srv: &http.Server{
Addr: addr,
Handler: m,
ReadTimeout: serverReadTimeout,
WriteTimeout: serverWriteTimeout,
},
}
return s
}
func (s *httpServer) Close() {
s.srv.Close()
}
func (s *httpServer) Start() {
l, err := net.Listen("tcp4", s.srv.Addr)
if err != nil {
log.Fatal(err)
}
log.Infoln("Server is listening on", l.Addr().String())
go func() {
if err := s.srv.Serve(l); err != http.ErrServerClosed {
log.Fatal(err)
}
}()
}
func (s *httpServer) Shutdown() error {
ctx, cancel := context.WithTimeout(context.Background(), serverShutdownTimeout)
defer cancel()
return s.srv.Shutdown(ctx)
}