I was asked to do a simple RESTful service using Go, that has to retrieve all the data about a particular book using its ID value.
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"`
}
//variables
//slice-> variable link to array
var books []Book
// Get single book
func getBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r) // Gets params
// Loop through books and find one with the id from the params
for _, item := range books {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Book{})
}
func main() {
// r := mux.NewRouter()
fmt.Println("hello api")
//initialize mux router
r := mux.NewRouter()
//mock data
books=append(books,Book{ID:"1",Isbn:"32123",Title:"Book one",Author:&Author{Firstname:"J.K.", Lastname:"Rowling"}})
books=append(books,Book{ID:"2",Isbn:"45434",Title:"Book two", Author:&Author{Firstname:"P.K.",Lastname:"Rowling"}})
//router handler
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/{id}",updateBook).Methods("PUT")
r.HandleFunc("/api/books/{id}",deleteBook).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8080",r))
}
expected output if i enter -> http://localhost:8080/api/books/1 this has to return me
{
"id": "1",
"isbn": "32123",
"title": "Book one",
"author": {
"firstname": "J.K.",
"lastname": "Rowling"
}
}
instead, I'm getting nothing in my browser
I just format the code as below and it works fine (pay attention to WriteHeader
function).
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
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"`
}
//variables
//slice-> variable link to array
var books []Book
// Get single book
func getBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r) // Gets params
// Loop through books and find one with the id from the params
for _, item := range books {
if item.ID == params["id"] {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(item)
return
}
}
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(&Book{})
}
func main() {
fmt.Println("Listening on :8080")
// initialize mux router
r := mux.NewRouter()
// mock data
books = append(books, Book{ID: "1", Isbn: "32123", Title: "Book one", Author: &Author{Firstname: "J.K.", Lastname: "Rowling"}})
books = append(books, Book{ID: "2", Isbn: "45434", Title: "Book two", Author: &Author{Firstname: "P.K.", Lastname: "Rowling"}})
// router handler
r.HandleFunc("/api/books/{id}", getBook).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", r))
}
After running the above program. The following command on the console:
curl 127.0.0.1:8080/api/books/1
returns:
{"id":"1","isbn":"32123","title":"Book one","author":{"firstname":"J.K.","lastname":"Rowling"}}
Finally, as a recommendation for implementing the ReST API with Golang, you can check here.