-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
87 lines (69 loc) · 2.36 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
//go:generate mockgen -destination=./mocks/http_mock.go -package mocks github.com/AraiYuno/golang-rest-api/internal/api/http Users,DB
package http
import (
"context"
"encoding/json"
"net/http"
"github.com/AraiYuno/golang-rest-api/internal/users/model"
"github.com/gorilla/mux"
)
// Users represents a type that can provide CRUD operations on users.
type Users interface {
CreateUser(ctx context.Context, user *model.User) (*model.User, error)
GetUser(ctx context.Context, id string) (*model.User, error)
FindUsers(ctx context.Context, filters []model.Filter, offset, limit int64) ([]*model.User, error)
UpdateUser(ctx context.Context, user *model.User) (*model.User, error)
DeleteUser(ctx context.Context, id string) error
}
// DB represents a type that can be used to interact with the database.
type DB interface {
PingContext(ctx context.Context) error
}
// Server represents a HTTP server that can handle requests for this microservice.
type Server struct {
users Users
db DB
}
// New will instantiate a new instance of Server.
func New(u Users, db DB) *Server {
return &Server{
users: u,
db: db,
}
}
// AddRoutes will add the routes this server supports to the router.
func (s *Server) AddRoutes(r *mux.Router) error {
r.HandleFunc("/health", s.healthCheck).Methods(http.MethodGet)
r = r.PathPrefix("/v1").Subrouter()
r.HandleFunc("/user", s.createUser).Methods(http.MethodPost)
r.HandleFunc("/user/{id}", s.getUser).Methods(http.MethodGet)
r.HandleFunc("/user/{id}", s.updateUser).Methods(http.MethodPut)
r.HandleFunc("/user/{id}", s.deleteUser).Methods(http.MethodDelete)
// Not the most RESTful way of doing this as it won't really be cachable but provides easier parsing of the inputs for now
r.HandleFunc("/users/search", s.searchUsers).Methods(http.MethodPost)
return nil
}
func (s *Server) healthCheck(w http.ResponseWriter, r *http.Request) {
if err := s.db.PingContext(r.Context()); err != nil {
handleError(r.Context(), w, err)
return
}
w.WriteHeader(http.StatusOK)
}
func handleResponse(ctx context.Context, w http.ResponseWriter, data interface{}) {
jsonRes := struct {
Data interface{} `json:"data"`
}{
Data: data,
}
dataBytes, err := json.Marshal(jsonRes)
if err != nil {
handleError(ctx, w, err)
return
}
if _, err := w.Write(dataBytes); err != nil {
handleError(ctx, w, err)
return
}
w.WriteHeader(http.StatusOK)
}