-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
108 lines (80 loc) · 2.54 KB
/
main.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"cloud.google.com/go/datastore"
"github.com/julienschmidt/httprouter"
"github.com/utsavgupta/go-unison/example/webapp/ent"
"github.com/utsavgupta/go-unison/example/webapp/repo"
)
const (
namespace = "unison-demo"
)
func writeResponse(statusCode int, body interface{}, resp http.ResponseWriter) {
bodyJSON, err := json.Marshal(body)
if err != nil {
strBody, ok := body.(string)
if ok {
resp.WriteHeader(statusCode)
resp.Write([]byte(strBody))
return
}
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte("error"))
return
}
resp.Header().Set("content-type", "application/json")
resp.WriteHeader(statusCode)
resp.Write(bodyJSON)
}
func newHandleGetAllArtists(artistRepo repo.ArtistLoader) httprouter.Handle {
return func(resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
artists, err := artistRepo.LoadAllArtists(req.Context())
if err != nil {
writeResponse(http.StatusInternalServerError, "error", resp)
return
}
writeResponse(http.StatusOK, ent.Artists{Items: artists}, resp)
}
}
func newHandleGetAllAlbums(albumRepo repo.AlbumLoader) httprouter.Handle {
return func(resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
albums, err := albumRepo.LoadAllAlbums(req.Context())
if err != nil {
writeResponse(http.StatusInternalServerError, "error", resp)
return
}
writeResponse(http.StatusOK, ent.Albums{Items: albums}, resp)
}
}
func newHandleGetAlbumsForArtist(albumRepo repo.AlbumLoader) httprouter.Handle {
return func(resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
artistID := params.ByName("artistID")
if artistID == "" {
writeResponse(http.StatusBadRequest, "artist id missing", resp)
return
}
albums, err := albumRepo.LoadAllAlbumsByArtist(req.Context(), artistID)
if err != nil {
fmt.Println(err)
writeResponse(http.StatusInternalServerError, "error", resp)
return
}
writeResponse(http.StatusOK, ent.Albums{Items: albums}, resp)
}
}
func main() {
dsClient, err := datastore.NewClient(context.Background(), "*detect-project-id*")
if err != nil {
panic(err)
}
artistRepo := repo.NewArtistLoader(dsClient, namespace)
albumRepo := repo.NewAlbumLoader(dsClient, namespace)
r := httprouter.New()
r.GET("/artists", newHandleGetAllArtists(artistRepo))
r.GET("/artists/:artistID/albums", newHandleGetAlbumsForArtist(albumRepo))
r.GET("/albums", newHandleGetAllAlbums(albumRepo))
http.ListenAndServe(":8080", r)
}