-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
43 lines (36 loc) · 901 Bytes
/
server.go
File metadata and controls
43 lines (36 loc) · 901 Bytes
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Book struct {
Name string `json:"name"`
Author string `json:"author"`
}
var books = []Book{
{"Brave New World", "Aldous Huxley"},
{"Odyssey", "Homer"},
{"AngularJS: Up & Running", "Shyam Seshadri & Brad Green"},
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
})
http.HandleFunc("/api/book", bookHandler)
fmt.Println("Listening on localhost:3000...")
http.ListenAndServe(":3000", nil)
}
func bookHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.Encode(books)
} else if r.Method == "POST" {
var newBook Book
body, _ := ioutil.ReadAll(r.Body)
json.Unmarshal(body, &newBook)
books = append(books, newBook)
}
}