-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
107 lines (93 loc) · 2.21 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Package server defines rest api endpoints for gleek
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"strconv"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/jwtauth"
"github.com/saromanov/gleek/config"
"github.com/saromanov/gleek/internal/storage"
pb "github.com/saromanov/gleek/proto"
log "go.uber.org/zap"
)
var tokenAuth *jwtauth.JWTAuth
type server struct {
router *chi.Mux
address string
st *storage.Storage
}
// createAccount makes a new task
func (s *server) createTask(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
account := &pb.Task{}
err := json.NewDecoder(r.Body).Decode(account)
if err != nil {
panic(err)
}
s.st.CreateTask(account)
w.WriteHeader(http.StatusCreated)
}
// getTask returns task by id
func (s *server) getTask(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
id := chi.URLParam(r, "id")
if id == "" {
return
}
parsedInt, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return
}
s.st.GetTask(uint(parsedInt))
w.WriteHeader(http.StatusCreated)
}
func (s *server) makeHandlers() {
s.router.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(tokenAuth))
r.Use(jwtauth.Authenticator)
})
s.router.Group(func(r chi.Router) {
r.Post("/v1/tasks", s.createTask)
r.Get("/v1/tasks/{id}", s.getTask)
})
}
func (s *server) startServer() {
fmt.Printf("server is started at %s", s.address)
srv := &http.Server{
Addr: s.address,
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: s.router,
}
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Error(err)
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(ctx)
fmt.Printf("shutting down server")
}
// New makes http endpoints and handler
func New(st *storage.Storage, c *config.Config) {
tokenAuth = jwtauth.New("HS256", []byte("testtoken"), nil)
r := chi.NewRouter()
s := &server{
st: st,
router: r,
address: c.Address,
}
s.makeHandlers()
s.startServer()
}