This repository has been archived by the owner on Nov 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
169 lines (141 loc) · 4.45 KB
/
api.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package main
import (
"fmt"
"net/http"
"strconv"
"time"
"encoding/json"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
// StatusWriter to log response status code
type StatusWriter struct {
http.ResponseWriter
Status int
}
// NewStatusResponseWriter to create a new StatusWriter handler for HTTP logging
func NewStatusResponseWriter(w http.ResponseWriter) *StatusWriter {
return &StatusWriter{
ResponseWriter: w,
Status: http.StatusOK,
}
}
// WriteHeader to write status code to response
func (sw *StatusWriter) WriteHeader(code int) {
sw.Status = code
sw.ResponseWriter.WriteHeader(code)
}
// LoggingMiddleware to log HTTP requests
func LoggingMiddleware(r *mux.Router) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
sw := NewStatusResponseWriter(w)
defer func() {
log.Printf("%s %s %v %d %s %s", req.RemoteAddr, req.Method, time.Since(start), sw.Status, req.URL.Path, req.URL.RawQuery)
}()
next.ServeHTTP(w, req)
})
}
}
// handle health checks
func handleHealth(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "OK")
}
// shopsHandler to expose shops over HTTP with a database connection
type shopsHandler struct {
db *gorm.DB
}
// ServeHTTP to implement the handle interface for serving shops
func (h *shopsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var shops []Shop
trx := h.db.Find(&shops)
if trx.Error == nil {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(shops)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
}
// shopHandler to expose shops over HTTP with a database connection
type shopHandler struct {
db *gorm.DB
}
// ServeHTTP to implement the handle interface for serving shop
func (h *shopHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
id := vars["id"]
var shop Shop
trx := h.db.First(&shop, id)
if trx.Error == nil {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(shop)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
}
// productsHandler to expose products over HTTP with a database connection
type productsHandler struct {
db *gorm.DB
}
// ServeHTTP to implement the handle interface for serving products
func (h *productsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var products []Product
var trx *gorm.DB
availableFilter := r.URL.Query().Get("available")
if availableFilter != "" {
available, err := strconv.ParseBool(availableFilter)
if err != nil {
log.Warnf("cannot parse available query to boolean: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
trx = h.db.Preload("Shop").Where(map[string]interface{}{"available": available}).Find(&products)
} else {
trx = h.db.Preload("Shop").Find(&products)
}
if trx.Error == nil {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(products)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
}
// productHandler to expose product over HTTP with a database connection
type productHandler struct {
db *gorm.DB
}
// ServeHTTP to implement the handle interface for serving product
func (h *productHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
var product Product
trx := h.db.Preload("Shop").First(&product, id)
if trx.Error == nil {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(product)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
}
// StartAPI to handle HTTP requests
func StartAPI(db *gorm.DB, config APIConfig) error {
router := mux.NewRouter().StrictSlash(true)
router.Path("/health").HandlerFunc(handleHealth)
router.Path("/shops").Handler(&shopsHandler{db: db})
router.Path("/shops/{id:[0-9]+}").Handler(&shopHandler{db: db})
router.Path("/products").Handler(&productsHandler{db: db})
router.Path("/products/{id:[0-9]+}").Handler(&productHandler{db: db})
// register middlewares
router.Use(LoggingMiddleware(router))
log.Printf("starting API on %s", config.Address)
if config.Certfile != "" && config.Keyfile != "" {
return http.ListenAndServeTLS(config.Address, config.Certfile, config.Keyfile, router)
}
return http.ListenAndServe(config.Address, router)
}