-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers_api.go
39 lines (34 loc) · 962 Bytes
/
handlers_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
package main
import (
"encoding/json"
mux "github.com/julienschmidt/httprouter"
"io"
"io/ioutil"
"net/http"
)
func ApiQuoteAll(w http.ResponseWriter, r *http.Request, _ mux.Params) {
var quotes Quotes
quotes = FindAll()
HandleError(json.NewEncoder(w).Encode(quotes))
}
func ApiQuoteRandom(w http.ResponseWriter, r *http.Request, _ mux.Params) {
var quote Quote
quote = FindRandom()
HandleError(json.NewEncoder(w).Encode(quote))
}
func ApiQuoteCreate(w http.ResponseWriter, r *http.Request, _ mux.Params) {
var quote Quote
// Read request body and close it
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
HandleError(err)
defer r.Body.Close()
// Save JSON to quote struct
if err := json.Unmarshal(body, "e); err != nil {
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
}
CreateQuote(quote)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusCreated)
}