Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "encoding/json"
- "fmt"
- "log"
- "math/rand"
- "net/http"
- "strconv"
- "github.com/gorilla/mux"
- )
- // Book Struct ( Class-like i guess ?) - Looks like ES6 classes or JAVA
- type Book struct {
- ID string `json:id`
- ISBN string `json:isbn`
- Title string `json:title`
- Author *Author `json:author`
- }
- // Author Struct, sub-struct to book
- type Author struct {
- Firstname string `json:firstname`
- Lastname string `json:lastname`
- }
- // Init books var as a slice (variable array)
- var books []Book
- // Get all books
- func getBooks(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(books)
- }
- // Get a single book by id
- func getBook(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- params := mux.Vars(r) // Get params
- // Find correct book with id r
- for _, item := range books {
- fmt.Println(item.ID, params["id"])
- fmt.Printf("%+v\n", books)
- if item.ID == params["id"] {
- json.NewEncoder(w).Encode(item)
- return
- }
- }
- json.NewEncoder(w).Encode(&Book{})
- }
- // Create a new book
- func createBook(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- fmt.Println(r.Body)
- var book Book
- _ = json.NewDecoder(r.Body).Decode(&book)
- book.ID = strconv.Itoa(rand.Intn(10000000)) // Mock ID - shitty duplicates
- books = append(books, book)
- json.NewEncoder(w).Encode(book)
- }
- // Updates an existing book
- func updateBook(w http.ResponseWriter, r *http.Request) {
- }
- // Deletes a book by id
- func deleteBook(w http.ResponseWriter, r *http.Request) {
- }
- func main() {
- // Initialize router
- r := mux.NewRouter()
- // Mock Data - @todo - implement DB
- books = append(books, Book{"1", "AS-465234", "The First Title", &Author{"Simon", "Borgmästars"}})
- books = append(books, Book{"2", "KL-34545", "The Second Title", &Author{"Simon2", "Borgmästars2"}})
- books = append(books, Book{"3", "OP-64545", "The Third Title", &Author{"Simon3", "Borgmästars3"}})
- books = append(books, Book{"4", "UI-90875", "The Fourth Title", &Author{"Simon4", "Borgmästars4"}})
- // Route Handlers
- r.HandleFunc("/api/books", getBooks).Methods("GET")
- r.HandleFunc("/api/books/{id}", getBook).Methods("GET")
- r.HandleFunc("/api/books", createBook).Methods("POST")
- r.HandleFunc("/api/books", updateBook).Methods("PUT")
- r.HandleFunc("/api/books/{id}", deleteBook).Methods("DELETE")
- // Running the server
- fmt.Println("Starting up the server...")
- log.Fatal(http.ListenAndServe(":3000", r))
- }
Advertisement
Add Comment
Please, Sign In to add comment