-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
63 lines (51 loc) · 1.41 KB
/
app.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
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
type Service struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Versions uint `json:"versions"`
}
type ServiceRepository interface {
Services(ctx context.Context) ([]Service, error)
Service(ctx context.Context, id int) (*Service, error)
}
type ServiceHandler struct {
repository ServiceRepository
}
func NewServiceHandler(serviceRepo ServiceRepository) ServiceHandler {
return ServiceHandler{repository: serviceRepo}
}
func (h *ServiceHandler) GetServices(w http.ResponseWriter, r *http.Request) {
services, err := h.repository.Services(r.Context())
if err != nil {
log.Println("Something bad happened", err)
http.Error(w, "Badness", http.StatusInternalServerError)
}
json.NewEncoder(w).Encode(services)
}
func (h *ServiceHandler) GetService(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
http.Error(w, "Invalid service ID", http.StatusBadRequest)
return
}
service, err := h.repository.Service(r.Context(), id)
if err != nil {
log.Println("Something bad happened", err)
http.Error(w, "Badness", http.StatusInternalServerError)
}
if service != nil {
json.NewEncoder(w).Encode(service)
return
}
http.Error(w, "Service not found", http.StatusNotFound)
}