-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
66 lines (52 loc) · 1.43 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
package main
import (
"context"
"encoding/json"
"math/rand"
"net/http"
"github.com/AnimeshRy/reddit-api/types"
)
type PriceResponse struct {
Ticker string `json:"ticker"`
Price float64 `json:"price"`
}
type APIFunc func(context.Context, http.ResponseWriter, *http.Request) error
type JSONAPIServer struct {
listenAddr string
svc PriceFetcher
}
func NewJSONAPIServer(listenAddr string, svc PriceFetcher) *JSONAPIServer {
return &JSONAPIServer{
listenAddr: listenAddr,
svc: svc,
}
}
func (s *JSONAPIServer) Run() {
http.HandleFunc("/", makeHTTPHandlerFunc(s.handleFetchPrice))
http.ListenAndServe(s.listenAddr, nil)
}
func makeHTTPHandlerFunc(apiFn APIFunc) http.HandlerFunc {
ctx := context.Background()
ctx = context.WithValue(ctx, "requestID", rand.Intn(10000000))
return func(w http.ResponseWriter, r *http.Request) {
if err := apiFn(ctx, w, r); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()})
}
}
}
func (s *JSONAPIServer) handleFetchPrice(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
ticker := r.URL.Query().Get("ticker")
price, err := s.svc.FetchPrice(ctx, ticker)
if err != nil {
return err
}
priceResp := types.PriceResponse{
Price: price,
Ticker: ticker,
}
return writeJSON(w, http.StatusOK, &priceResp)
}
func writeJSON(w http.ResponseWriter, s int, v any) error {
w.WriteHeader(s)
return json.NewEncoder(w).Encode(v)
}