/
webery.go
87 lines (69 loc) · 2.03 KB
/
webery.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
package main
import (
"flag"
"net/http"
log "github.com/Sirupsen/logrus"
"github.com/altlinux/logfile-go"
"github.com/altlinux/pidfile-go"
"github.com/altlinux/webery/pkg/ahttp"
"github.com/altlinux/webery/pkg/ahttp/api"
"github.com/altlinux/webery/pkg/ahttp/middleware/mlog"
"github.com/altlinux/webery/pkg/config"
"github.com/altlinux/webery/pkg/context"
"github.com/altlinux/webery/pkg/db"
storage "github.com/altlinux/webery/pkg/db/mongo"
)
var (
configFile = flag.String("config", "", "Path to configuration file")
)
type Server struct {
Cfg *config.Config
DB db.Session
}
func (s *Server) Handler(w http.ResponseWriter, req *http.Request) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx = context.WithValue(ctx, "app.database", s.DB)
ctx = context.WithValue(ctx, "app.config", s.Cfg)
ctx = context.WithValue(ctx, "http.endpoints", api.Endpoints)
mlog.Handler(api.Handler)(ctx, ahttp.NewResponseWriter(w), req)
}
func main() {
flag.Parse()
cfg, err := config.NewConfig(*configFile)
if err != nil {
log.Fatal(err)
}
log.SetLevel(cfg.Logging.Level.Level)
log.SetFormatter(&log.TextFormatter{
FullTimestamp: cfg.Logging.FullTimestamp,
DisableTimestamp: cfg.Logging.DisableTimestamp,
DisableColors: cfg.Logging.DisableColors,
DisableSorting: cfg.Logging.DisableSorting,
})
pidFile, err := pidfile.OpenPidfile(cfg.Global.Pidfile)
if err != nil {
log.Fatal("Unable to open pidfile: ", err.Error())
}
defer pidFile.Close()
if err := pidFile.Check(); err != nil {
log.Fatal("Check failed: ", err.Error())
}
if err := pidFile.Write(); err != nil {
log.Fatal("Unable to write pidfile: ", err.Error())
}
logFile, err := logfile.OpenLogfile(cfg.Global.Logfile)
if err != nil {
log.Fatal("Unable to open log: ", err.Error())
}
defer logFile.Close()
log.SetOutput(logFile)
dbi := storage.NewSession(cfg.Mongo)
defer dbi.Close()
server := Server{
Cfg: cfg,
DB: dbi,
}
http.HandleFunc("/", server.Handler)
log.Fatal(http.ListenAndServe(cfg.Global.Address, nil))
}