func lampsHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { w.Header().Set("Content-Type", "application/json; charset=utf-8") //fetch array of lamps from db. lamps, err := db.FetchLamps() if err != nil { w.WriteHeader(http.StatusInternalServerError) json.NewEncoder(w).Encode("Database error") return } w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(lamps) }
func allLampActionHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { w.Header().Set("Content-Type", "application/json; charset=utf-8") //decide on the action.. //check if action is okay. action := ps.ByName("action") _, ok := actions[action] if !ok { w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode("Action not accepted. Use on or off.") return } if lamps, err := db.FetchLamps(); err == nil { for _, aLamp := range lamps { doAction(action, aLamp, w) } } w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode("All lamps is now " + action) }