-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
72 lines (53 loc) · 1.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
package main
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"net/http"
"github.com/mahendrarathore1742/priceFetcher/types"
)
type JSONAPIServer struct {
listenAddr string
svc PriceService
}
// Custom define http head function
type APIFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request) error
func MakeAPIFunc(fn APIFunc) http.HandlerFunc {
ctx := context.Background()
return func(w http.ResponseWriter, r *http.Request) {
ctx = context.WithValue(ctx, "requestID", rand.Intn(100000000))
if err := fn(ctx, w, r); err != nil {
WriteJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()})
}
}
}
func NewJsonAPiServer(listenAddr string, svc PriceService) *JSONAPIServer {
return &JSONAPIServer{
svc: svc,
listenAddr: listenAddr,
}
}
func (s *JSONAPIServer) Run() {
http.HandleFunc("/", MakeAPIFunc(s.handleFetchPrice))
http.ListenAndServe(s.listenAddr, nil)
}
func (s *JSONAPIServer) handleFetchPrice(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
ticker := r.URL.Query().Get("ticker")
if len(ticker) == 0 {
return fmt.Errorf("invalid 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)
}