forked from milhamrk/altaid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
43 lines (36 loc) · 962 Bytes
/
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
package main
import (
"encoding/json"
"net/http"
)
type Buku struct {
ID int `json:"id"`
Judul string `json:"judul"`
Pengarang string `json:"pengarang"`
}
var perpustakan []Buku
func GetBooks(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
json.NewEncoder(rw).Encode(perpustakan)
}
func CreateBooks(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
var params Buku
err := json.NewDecoder(r.Body).Decode(¶ms)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
return
}
perpustakan = append(perpustakan, params)
rw.WriteHeader(http.StatusCreated)
json.NewEncoder(rw).Encode(perpustakan)
}
func main() {
mux := http.NewServeMux()
perpustakan = []Buku{
{ID: 1, Judul: "Halo Book", Pengarang: "Siti"},
}
mux.HandleFunc("/books", GetBooks)
mux.HandleFunc("/create-books", CreateBooks)
http.ListenAndServe(":8000", mux)
}