-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
36 lines (31 loc) · 783 Bytes
/
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
package main
import (
"context"
"encoding/json"
"net/http"
)
type ApiServer struct {
svc Service
}
func NewApiServer(svc Service) *ApiServer {
return &ApiServer{
svc: svc,
}
}
func (s *ApiServer) Start(listenAddr string) error {
http.HandleFunc("/", s.handleGetCatFact)
return http.ListenAndServe(listenAddr, nil)
}
func (s *ApiServer) handleGetCatFact(w http.ResponseWriter, r *http.Request) {
fact, err := s.svc.GetCatFact(context.Background())
if err != nil {
writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, fact)
}
func writeJSON(w http.ResponseWriter, s int, v any) error {
w.WriteHeader(s)
w.Header().Add("Content-Type", "application/json")
return json.NewEncoder(w).Encode(v)
}