Subcategory now accepts POST requests, so they can be added even after a category has been created.
This commit is contained in:
@@ -66,6 +66,8 @@ func category(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func subcategory(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
insertSubcategoryHandler(w, r)
|
||||
case "DELETE":
|
||||
deleteSubcategoryHandler(w, r)
|
||||
default:
|
||||
@@ -206,3 +208,44 @@ func insertCategoryHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(fmt.Sprintf("New Record: %d", id)))
|
||||
}
|
||||
|
||||
func insertSubcategoryHandler(w http.ResponseWriter, r *http.Request) {
|
||||
ct := r.Header.Get("content-type")
|
||||
|
||||
if ct != "application/json" {
|
||||
w.WriteHeader(http.StatusUnsupportedMediaType)
|
||||
w.Write([]byte(fmt.Sprintf("Unsupported media type '%s', expected application/json", ct)))
|
||||
return
|
||||
}
|
||||
|
||||
bodyBytes, err := ioutil.ReadAll(r.Body)
|
||||
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte("Failed to parse request body"))
|
||||
return
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
var subcategory Subcategory
|
||||
|
||||
err = json.Unmarshal(bodyBytes, &subcategory)
|
||||
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte("Failed to unmarshal JSON"))
|
||||
return
|
||||
}
|
||||
|
||||
id, ok := insertSubcategory(subcategory.Name, subcategory.CategoryId)
|
||||
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte("Failed to create the new subcategory."))
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(fmt.Sprintf("New Record: %d", id)))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user