-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgorilla_mux_example.go
55 lines (47 loc) · 1.01 KB
/
gorilla_mux_example.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
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"io"
"io/ioutil"
"net/http"
)
type Book struct {
Title string `json:"title"`
Author string `json:"author"`
}
var books []Book
func getBooks(w http.ResponseWriter, r *http.Request) {
if len(books) == 0 {
_, _ = io.WriteString(w, "No books found")
return
}
s, _ := json.Marshal(books)
if _, err := io.WriteString(w, string(s)); err != nil {
panic(err)
}
}
func addBook(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%+v", r)
var book Book
b, _ := ioutil.ReadAll(r.Body)
if err := json.Unmarshal(b, &book); err != nil {
panic(err)
}
books = append(books, book)
fmt.Printf("%+v", book)
if _, err := io.WriteString(w, "New book added"); err != nil {
panic(err)
}
}
func main() {
r := mux.NewRouter()
//GET Request
r.HandleFunc("/books", getBooks).Methods(http.MethodGet)
//POST Request
r.HandleFunc("/books", addBook).Methods(http.MethodPost)
if err := http.ListenAndServe(":8000", r); err != nil {
panic(err)
}
}