-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
78 lines (64 loc) · 1.9 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
71
72
73
74
75
76
77
78
package main
import (
"context"
"fmt"
"log"
"net/http"
"web-widgets/scheduler-go/api"
"web-widgets/scheduler-go/data"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
"github.com/jinzhu/configor"
"github.com/unrolled/render"
)
var format = render.New()
// Config is the structure that stores the settings for this backend app
var Config AppConfig
func main() {
configor.New(&configor.Config{ENVPrefix: "APP", Silent: true}).Load(&Config, "config.yml")
dao := data.NewDAO(Config.DB, Config.Server.URL, Config.BinaryData)
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
fmt.Println(Config.Server.Cors)
if len(Config.Server.Cors) > 0 {
c := cors.New(cors.Options{
AllowedOrigins: Config.Server.Cors,
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token", "Remote-Token"},
AllowCredentials: true,
MaxAge: 300,
})
r.Use(c.Handler)
}
// auth
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Remote-Token")
if token == "" {
if r.Method == http.MethodGet {
token = r.URL.Query().Get("token")
}
}
if token != "" {
id, device, err := verifyUserToken([]byte(token))
if err != nil {
log.Println("[token]", err.Error())
} else {
r = r.WithContext(context.WithValue(context.WithValue(r.Context(), "user_id", id), "device_id", device))
}
}
next.ServeHTTP(w, r)
})
})
apiServer := api.BuildAPI(dao)
r.Get("/api/v1", apiServer.ServeHTTP)
r.Post("/api/v1", apiServer.ServeHTTP)
initRoutes(r, dao, apiServer.Events)
log.Printf("Starting webserver at port " + Config.Server.Port)
err := http.ListenAndServe(Config.Server.Port, r)
if err != nil {
log.Println(err.Error())
}
}