-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (64 loc) · 2.01 KB
/
main.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"
"flag"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gorilla/mux"
)
func getCakeHandler(w http.ResponseWriter, r *http.Request, u User) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(u.FavoriteCake))
}
func wrapJwt(jwt *JWTService, f func(http.ResponseWriter, *http.Request, *JWTService)) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
f(rw, r, jwt)
}
}
func main() {
os.Setenv("CAKE_ADMIN_EMAIL", "[email protected]")
os.Setenv("CAKE_ADMIN_PASSWORD", "admin1111")
go send()
go metrics()
flag.Parse()
hub := newHub()
go hub.run()
r := mux.NewRouter()
users := NewInMemoryUserStorage()
userService := UserService{repository: users}
jwtService, err := NewJWTService("pubkey.rsa", "privkey.rsa")
if err != nil {
panic(err)
}
r.HandleFunc("/cake", logRequest(jwtService.jwtAuth(users, getCakeHandler))).Methods(http.MethodGet)
r.HandleFunc("/user/register", logRequest(userService.Register)).Methods(http.MethodPost)
r.HandleFunc("/user/jwt", logRequest(wrapJwt(jwtService, userService.JWT))).Methods(http.MethodPost)
r.HandleFunc("/user/me", logRequest(userService.Profile)).Methods(http.MethodGet)
r.HandleFunc("/user/favorite_cake", logRequest(userService.ChangeCake)).Methods(http.MethodPost)
r.HandleFunc("/user/email", logRequest(userService.ChangeEmail)).Methods(http.MethodPost)
r.HandleFunc("/user/password", logRequest(userService.ChangePassword)).Methods(http.MethodPost)
r.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
serveWs(hub, w, r, jwtService, *users)
})
srv := http.Server{
Addr: ":8000",
Handler: r,
}
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
go func() {
<-interrupt
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(ctx)
}()
log.Println("Server started, hit Ctrl+C to stop")
err = srv.ListenAndServe()
if err != nil {
log.Println("Server exited with error:", err)
}
log.Println("Good bye :)")
}