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 api
import (
"context"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
mux "github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"github.com/jackyzha0/ctrl-v/db"
)
func cleanup() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := db.Client.Disconnect(ctx); err != nil {
panic(err)
}
log.Print("Shutting down server...")
}
// Define router and start server
func Serve(port int) {
// Sigint trapper
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
cleanup()
os.Exit(0)
}()
// Define Mux Router
r := mux.NewRouter()
r.HandleFunc("/health", healthCheckFunc)
r.HandleFunc("/api", insertFunc).Methods("POST", "OPTIONS")
r.HandleFunc("/api/{hash}", getPasteFunc).Methods("GET", "OPTIONS")
r.HandleFunc("/api/{hash}", getPasteWithPasswordFunc).Methods("POST", "OPTIONS")
http.Handle("/", r)
// Start HTTP server
server := newServer(":"+strconv.Itoa(port), r)
log.Printf("Starting server on %d", port)
defer cleanup()
err := server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}
// Function to create new HTTP server
func newServer(addr string, router http.Handler) *http.Server {
return &http.Server{
Addr: addr,
Handler: router,
ReadTimeout: time.Second * 30,
WriteTimeout: time.Second * 30,
}
}
|