-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
105 lines (79 loc) · 2.3 KB
/
http.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
package profile
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi"
"github.com/pkg/errors"
"github.com/dzeban/conduit/app"
"github.com/dzeban/conduit/jwt"
"github.com/dzeban/conduit/transport"
)
type Server struct {
router *chi.Mux
service *Service
}
func NewHTTP(store Store, secret []byte) (*Server, error) {
s := &Server{
router: chi.NewRouter(),
service: NewService(store),
}
s.router.
With(jwt.Auth(secret, jwt.AuthTypeOptional)).
Get("/{username}", transport.WithError(s.HandleGet))
// Endpoints protected by JWT auth
s.router.Group(func(r chi.Router) {
r.Use(jwt.Auth(secret, jwt.AuthTypeRequired))
r.Post("/{username}/follow", transport.WithError(s.HandleFollow))
r.Delete("/{username}/follow", transport.WithError(s.HandleUnfollow))
})
return s, nil
}
type Response struct {
Profile app.Profile `json:"profile"`
}
// ServeHTTP implements http.handler interface and uses router ServeHTTP method
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
func (s *Server) HandleGet(w http.ResponseWriter, r *http.Request) error {
username := chi.URLParam(r, "username")
currentUser, _ := app.UserFromContext(r.Context())
p, err := s.service.Get(username, currentUser)
if err != nil {
return err
}
jsonProfile, err := json.Marshal(Response{Profile: *p})
if err != nil {
return app.InternalError(errors.Wrap(err, "json.Marshal"))
}
w.Write(jsonProfile)
return nil
}
func (s *Server) HandleFollow(w http.ResponseWriter, r *http.Request) error {
username := chi.URLParam(r, "username")
currentUser, _ := app.UserFromContext(r.Context())
p, err := s.service.Follow(currentUser, username)
if err != nil {
return err
}
jsonProfile, err := json.Marshal(Response{Profile: *p})
if err != nil {
return app.InternalError(errors.Wrap(err, "json.Marshal"))
}
w.Write(jsonProfile)
return nil
}
func (s *Server) HandleUnfollow(w http.ResponseWriter, r *http.Request) error {
username := chi.URLParam(r, "username")
currentUser, _ := app.UserFromContext(r.Context())
p, err := s.service.Unfollow(currentUser, username)
if err != nil {
return err
}
jsonProfile, err := json.Marshal(Response{Profile: *p})
if err != nil {
return app.InternalError(errors.Wrap(err, "json.Marshal"))
}
w.Write(jsonProfile)
return nil
}