Advertisement
bimoprasetyoafif

Untitled

Feb 25th, 2020
576
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8.  
  9. "github.com/gorilla/mux"
  10. )
  11.  
  12. type Book struct {
  13. title string `json:"title"`
  14. content string `json:"content"`
  15. }
  16.  
  17. var books []Book
  18.  
  19. func createBook(w http.ResponseWriter, r *http.Request) {
  20. reqBody, _ := ioutil.ReadAll(r.Body)
  21.  
  22. var book Book
  23. json.Unmarshal(reqBody, &book)
  24. books = append(books, book)
  25. log.Print(&book)
  26. json.NewEncoder(w).Encode(book)
  27. }
  28.  
  29. func getBook(w http.ResponseWriter, r *http.Request) {
  30. json.NewEncoder(w).Encode(books)
  31. }
  32.  
  33. func main() {
  34.  
  35. router := mux.NewRouter().StrictSlash(true)
  36. router.HandleFunc("/", createBook).Methods("POST")
  37. router.HandleFunc("/", getBook).Methods("GET")
  38.  
  39. log.Fatal(http.ListenAndServe(":8081", router))
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement