Files
anydb/rest/serve.go

88 lines
2.3 KiB
Go
Raw Normal View History

/*
2025-12-23 14:24:04 +01:00
Copyright © 2024-2025 Thomas von Dein
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package rest
import (
"encoding/json"
"net/http"
2025-11-03 09:15:27 +01:00
"codeberg.org/scip/anydb/cfg"
)
// used to return to the api client
type Result struct {
Success bool `json:"success"`
Message string `json:"message"`
Code int `json:"code"`
}
const apiprefix = `/anydb/v1/`
func Runserver(conf *cfg.Config, args []string) error {
// setup api server
mux := http.NewServeMux()
2025-12-23 14:24:04 +01:00
// just in case someone tries to access the non-api url
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
Home(w)
})
2025-12-23 14:24:04 +01:00
mux.HandleFunc("GET "+apiprefix+"{$}", func(w http.ResponseWriter, r *http.Request) {
RestList(w, r, conf)
})
2025-12-23 14:24:04 +01:00
mux.HandleFunc("POST "+apiprefix+"{$}", func(w http.ResponseWriter, r *http.Request) {
RestList(w, r, conf)
})
mux.HandleFunc("GET "+apiprefix+"{key}", func(w http.ResponseWriter, r *http.Request) {
key := r.PathValue("key")
RestGet(w, r, key, conf)
})
mux.HandleFunc("DELETE "+apiprefix+"{key}", func(w http.ResponseWriter, r *http.Request) {
key := r.PathValue("key")
RestDelete(w, r, key, conf)
})
mux.HandleFunc("PUT "+apiprefix, func(w http.ResponseWriter, r *http.Request) {
2025-12-23 14:24:04 +01:00
RestSet(w, r, conf)
})
logger := LogHandler()
return http.ListenAndServe(conf.Listen, logger(mux))
}
/*
Wrapper to respond with proper json status, message and code,
shall be prepared and called by the handlers directly.
*/
2025-12-23 14:30:37 +01:00
func JsonStatus(resp http.ResponseWriter, code int, msg string) {
success := code == http.StatusOK
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(code)
json.NewEncoder(resp).Encode(
Result{
Code: code,
Message: msg,
Success: success,
})
}