-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
46 lines (40 loc) · 1.26 KB
/
handlers.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
package main
import (
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/render"
)
func corsHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE")
w.Header().Set("Access-Control-Max-Age", "3600")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
w.Header().Set("Access-Control-Allow-Credentials", "true")
if r.Method == "OPTIONS" {
return
}
h.ServeHTTP(w, r)
})
}
func getMovie(w http.ResponseWriter, r *http.Request) {
type context struct {
Title string `json:"title"`
Movie Movie `json:"movie"`
}
id := toInt(chi.URLParam(r, "id"))
movie := getMovieByID(id)
ctx := context{Title: "Proxy", Movie: movie}
render.DefaultResponder(w, r, ctx)
}
func listMovies(w http.ResponseWriter, r *http.Request) {
type context struct {
Title string `json:"title"`
Movies []Movie `json:"movies"`
Count int64 `json:"count"`
}
page := toInt(chi.URLParam(r, "page"))
movies, count := getMovies(page)
ctx := context{Title: "List movies", Movies: movies, Count: count}
render.DefaultResponder(w, r, ctx)
}