Created
March 10, 2020 03:59
-
-
Save jchiatt/e3d47e2a846ffaab9d39b2235ec804be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"log" | |
"net/http" | |
"github.com/gorilla/mux" | |
) | |
// Book Struct (Model) | |
type Book struct { | |
ID string `json:"id"` | |
Isbn string `json:"isbn"` | |
Title string `json:"title"` | |
Author *Author `json:"author"` | |
} | |
// Author Struct | |
type Author struct { | |
Firstname string `json:"firstname"` | |
Lastname string `json:"lastname"` | |
} | |
// Init books var as a slice Book struct | |
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 Single Book | |
func getBook(w http.ResponseWriter, r *http.Request) {} | |
// Create a New Book | |
func createBook(w http.ResponseWriter, r *http.Request) {} | |
// Update Book | |
func updateBook(w http.ResponseWriter, r *http.Request) {} | |
// Delete Book | |
func deleteBook(w http.ResponseWriter, r *http.Request) {} | |
func main() { | |
// Init Router | |
r := mux.NewRouter() | |
// Mock Data - @todo - implement DB | |
books = append(books, Book{ID: "1", Isbn: "234234", Title: "Book One", Author: &Author{Firstname: "John", Lastname: "Smith"}}) | |
books = append(books, Book{ID: "2", Isbn: "asd2134", Title: "Book Two", Author: &Author{Firstname: "Steve", Lastname: "Doe"}}) | |
// Route Handlers / Endpoints | |
r.HandleFunc("/api/books", getBooks).Methods("GET") | |
r.HandleFunc("/api/book/{id}", getBooks).Methods("GET") | |
r.HandleFunc("/api/books", createBook).Methods("POST") | |
r.HandleFunc("/api/books/{id}", updateBook).Methods("PUT") | |
r.HandleFunc("/api/books/{id}", deleteBook).Methods("DELETE") | |
log.Fatal(http.ListenAndServe(":8000", r)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment