I have Products and Items in my application. Products is a collection of items. For example, T-Shirt is a product and it has attributes like size and color. Sizes are S, M, L, XL and colors are Red, Green and Blue.
I want to build REST services using http package only. (No Gorilla Mux, Goji, etc).
POST Api to add a product
http://localhost/product
For the above, I use
http.HandleFunc("/product", AddProduct)
func AddProduct(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
// My code
}
}
I want to know how to implement the following:
GET API to get list of items for a particular Product
http://localhost/product/23
POST API to add an item within a product
http://localhost/product/23/item
GET API to return Item details
http://localhost/product/23/item/4
Note: I've been searching stack overflow for more than 2 hours and not able to find relevant answer. If this is already asked, I'm really sorry... please provide the link in comments.
The following should give you a starting point to work from:
package main
import (
"log"
"strconv"
"net/http"
"strings"
)
func AddProduct(w http.ResponseWriter, r *http.Request) {
c := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
switch {
case len(c) == 2:
// GET product/{id}
if r.Method != "GET" && r.Method != "HEAD" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
id, err := strconv.Atoi(c[1])
if err != nil {
break
}
// implementation
return
case len(c) == 3 && c[2] == "item":
// POST product/{id}/item
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
id, err := strconv.Atoi(c[1])
if err != nil {
break
}
// implementation
return
case len(c) == 4 && c[2] == "item":
// GET product/{id}/item/{itemID}
if r.Method != "GET" && r.Method != "HEAD" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
id, err := strconv.Atoi(c[1])
if err != nil {
break
}
itemID, err := strconv.Atoi(c[3])
if err != nil {
break
}
// implementation
return
}
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
func main() {
http.HandleFunc("/product/", AddProduct)
log.Fatal(http.ListenAndServe(":8080", nil))
}