-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
89 lines (76 loc) · 2.44 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
package v1
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"github.com/go-chi/chi"
database "github.com/dylanlott/exchange/db"
)
// ValidBearer is a hardcoded bearer token for demonstration purposes.
const ValidBearer = "123456"
// HelloResponse is the JSON representation for a customized message
type HelloResponse struct {
Message string `json:"message"`
Version string `json:"version"`
}
func jsonResponse(w http.ResponseWriter, data interface{}, c int) {
dj, err := json.MarshalIndent(data, "", " ")
if err != nil {
http.Error(w, "Error creating JSON response", http.StatusInternalServerError)
log.Println(err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(c)
fmt.Fprintf(w, "%s", dj)
}
// HelloWorld returns a basic "Hello World!" message
func HelloWorld(w http.ResponseWriter, r *http.Request) {
response := HelloResponse{
Message: "Tribal Exchange API V1",
Version: "0.0.1",
}
jsonResponse(w, response, http.StatusOK)
}
// HelloName returns a personalized JSON message
func HelloName(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
response := HelloResponse{
Message: fmt.Sprintf("Hello %s!", name),
}
jsonResponse(w, response, http.StatusOK)
}
// RequireAuthentication is an example middleware handler that checks for a
// hardcoded bearer token. This can be used to verify session cookies, JWTs
// and more.
func RequireAuthentication(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Make sure an Authorization header was provided
token := r.Header.Get("Authorization")
if token == "" {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
token = strings.TrimPrefix(token, "Bearer ")
// This is where token validation would be done. For this boilerplate,
// we just check and make sure the token matches a hardcoded string
if token != ValidBearer {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
// Assuming that passed, we can execute the authenticated handler
next.ServeHTTP(w, r)
})
}
// NewRouter returns an HTTP handler that implements the routes for the API
func NewRouter(db *database.DB) http.Handler {
r := chi.NewRouter()
// Require authentication on all endpoints
r.Use(RequireAuthentication)
// Register the API routes
r.Get("/", HelloWorld)
r.Get("/{name}", HelloName)
return r
}