-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
70 lines (53 loc) · 1.3 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
package server
import (
"context"
"math/rand"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/mux"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func newRouter() *mux.Router {
r := mux.NewRouter()
InfoLog.Printf("attaching handlers")
r.Handle("/", IndexFileServer())
r.HandleFunc("/paste", PastePostHandler).Methods("POST")
r.HandleFunc("/paste", PastePutHandler).Methods("PUT")
r.HandleFunc("/default", DefaultHandler).Methods("GET")
r.HandleFunc("/{hashID}", FetchHandler).Methods("GET")
return r
}
// Serve exported
func Serve(port string) {
InfoLog.Printf("starting chipku v%s", Version)
r := newRouter()
s := &http.Server{
Addr: ":" + port,
Handler: r,
IdleTimeout: 120 * time.Second,
ReadTimeout: 1 * time.Second,
WriteTimeout: 2 * time.Second,
}
go func() {
InfoLog.Printf("using port %s", port)
err := s.ListenAndServe()
if err != nil {
ErrorLog.Fatal(err)
}
}()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
sig := <-sigChan
DebugLog.Printf("received %s, gracefully shutting down", sig)
tc, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err := s.Shutdown(tc)
if err != nil {
ErrorLog.Printf("could not shutdown gracefully %s", err)
}
}