Files
Lumberjack-Go-Backend/handler_devicetype.go
2017-09-27 18:09:53 -05:00

111 lines
2.6 KiB
Go

package main
import (
"database/sql"
"encoding/json"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
func (a *App) getDeviceType(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid config ID")
return
}
c := DeviceType{ID: id}
if err := c.getDeviceType(a.DB); err != nil {
switch err {
case sql.ErrNoRows:
respondWithError(w, http.StatusNotFound, "DeviceType not found")
default:
respondWithError(w, http.StatusInternalServerError, err.Error())
}
return
}
respondWithJSON(w, http.StatusOK, c)
}
func (a *App) getDeviceTypes(w http.ResponseWriter, r *http.Request) {
count, _ := strconv.Atoi(r.FormValue("count"))
start, _ := strconv.Atoi(r.FormValue("start"))
if count > 10 || count < 1 {
count = 10
}
if start < 0 {
start = 0
}
configs, err := getDeviceTypes(a.DB, start, count)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, configs)
}
func (a *App) createDeviceType(w http.ResponseWriter, r *http.Request) {
var c DeviceType
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&c); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
defer r.Body.Close()
if err := c.createDeviceType(a.DB); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusCreated, c)
}
func (a *App) updateDeviceType(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid config ID")
return
}
var c DeviceType
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&c); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
defer r.Body.Close()
c.ID = id
if err := c.updateDeviceType(a.DB); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, c)
}
func (a *App) deleteDeviceType(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid DeviceType ID")
return
}
c := DeviceType{ID: id}
if err := c.deleteDeviceType(a.DB); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"})
}