Esempio n. 1
0
func optionsHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	table := vars["table"]
	route := table
	if _, ok := vars["id"]; ok {
		route += "/{id}"
	}

	apiHandlers := api.ApiHandlers()
	if tableHandlers, ok := apiHandlers[route]; !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	} else {
		setHeaders(w, tableHandlers.Methods())
		w.WriteHeader(http.StatusOK)
	}
}
Esempio n. 2
0
func addApiHandlers(router *mux.Router) {
	for route, funcs := range api.ApiHandlers() {
		wrapRouter := func(f api.ApiHandlerFunc) func(w http.ResponseWriter, r *http.Request) {
			return func(w http.ResponseWriter, r *http.Request) {
				setHeaders(w, funcs.Methods())
				body, err := ioutil.ReadAll(r.Body)
				response, err := f(mux.Vars(r), body)
				if err != nil {
					log.Println(err)
				}
				jresponse := output.MakeApiResponse(response, nil, err)
				w.Header().Set("Content-Type", "application/json")
				enc := json.NewEncoder(w)
				enc.Encode(jresponse)
			}
		}
		for method, f := range funcs {
			router.HandleFunc(apiPath+route, auth.Use(wrapRouter(f), auth.RequireLogin)).Methods(method.String())
		}
	}
}