|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + _"encoding/json" |
| 7 | + "log" |
| 8 | + "math/rand" |
| 9 | + "net/http" |
| 10 | + _"math/rand" |
| 11 | + "strconv" |
| 12 | + _"strconv" |
| 13 | + "github.com/gorilla/mux" |
| 14 | +) |
| 15 | + |
| 16 | +type Book struct { |
| 17 | + Id string `json:"id"` |
| 18 | + Title string `json:"title"` |
| 19 | + Company *Company `json:"company"` |
| 20 | +} |
| 21 | + |
| 22 | +type Company struct { |
| 23 | + Name string `json:"name"` |
| 24 | + Age int `json:"age"` |
| 25 | +} |
| 26 | + |
| 27 | +var books []Book |
| 28 | +var book Book |
| 29 | + |
| 30 | +func getBooks(res http.ResponseWriter, req *http.Request) { |
| 31 | + res.Header().Set("Content-Type", "application/json") |
| 32 | + json.NewEncoder(res).Encode(books) |
| 33 | +} |
| 34 | + |
| 35 | +func getBook(res http.ResponseWriter, req *http.Request ) { |
| 36 | + res.Header().Set("Content-Type", "application/json") |
| 37 | + params := mux.Vars(req) |
| 38 | + fmt.Println(books) |
| 39 | + for _, book := range books { |
| 40 | + if book.Id == params["id"] { |
| 41 | + json.NewEncoder(res).Encode(book) |
| 42 | + return |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + json.NewEncoder(res).Encode(&Book{}) |
| 47 | +} |
| 48 | + |
| 49 | +func createBook(res http.ResponseWriter, req *http.Request) { |
| 50 | + res.Header().Set("Content-Type", "application/json") |
| 51 | + _ = json.NewDecoder(req.Body).Decode(&book) |
| 52 | + book.Id = strconv.Itoa(rand.Intn(12000000)) |
| 53 | + books = append(books, book) |
| 54 | + json.NewEncoder(res).Encode(book) |
| 55 | +} |
| 56 | + |
| 57 | + |
| 58 | +func main(){ |
| 59 | + fmt.Println("Hello world") |
| 60 | + |
| 61 | + router := mux.NewRouter() |
| 62 | + books = append(books, Book{ Id: "isbn231jks", Title: "Mugerwa", Company: &Company{ Name: "Mugerwa", Age: 21 } }) |
| 63 | + router.HandleFunc("/api/books", getBooks).Methods("GET") |
| 64 | + router.HandleFunc("/api/books/{id}", getBook).Methods("GET") |
| 65 | + router.HandleFunc("/api/books", createBook).Methods("POST") |
| 66 | + |
| 67 | + log.Fatal(http.ListenAndServe(":9000", router)) |
| 68 | +} |
| 69 | + |
| 70 | + |
0 commit comments