-
Notifications
You must be signed in to change notification settings - Fork 1
/
serve.go
76 lines (63 loc) · 1.5 KB
/
serve.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
package routes
import (
"context"
"fmt"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"github.com/wrfly/yasuser/config"
"github.com/wrfly/yasuser/filter"
s "github.com/wrfly/yasuser/shortener"
)
const MAX_URL_LENGTH = 1e3
var urlBufferPool = sync.Pool{
New: func() interface{} {
return make([]byte, MAX_URL_LENGTH+1)
},
}
// Serve routes
func Serve(conf config.SrvConfig,
shortener s.Shortener, filter filter.Filter) error {
sigChan := make(chan os.Signal)
signal.Notify(sigChan, os.Interrupt, os.Kill)
srv := newServer(conf, shortener, filter)
e := gin.New()
e.GET("/", srv.handleIndex())
e.POST("/", srv.handleLongURL())
e.GET("/:URI", srv.handleURI())
// go tool pprof
if conf.Pprof {
e.GET("/:URI/pprof/", func(c *gin.Context) {
pprof.Index(c.Writer, c.Request)
})
e.GET("/:URI/pprof/:x", func(c *gin.Context) {
pprof.Index(c.Writer, c.Request)
})
}
httpServer := http.Server{
Addr: fmt.Sprintf(":%d", conf.Port),
Handler: e,
}
errChan := make(chan error)
go func() {
errChan <- httpServer.ListenAndServe()
}()
logrus.Infof("Server running at [ http://0.0.0.0:%d ], with domain [ %s ]",
conf.Port, conf.Domain)
select {
case <-sigChan:
logrus.Info("Shuting down the server")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
err := httpServer.Shutdown(ctx)
logrus.Info("Server shutdown")
return err
case err := <-errChan:
return err
}
}