37 lines
807 B
Go
37 lines
807 B
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// Response helpers
|
|
|
|
func respondJSON(w http.ResponseWriter, status int, data interface{}) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
if data != nil {
|
|
json.NewEncoder(w).Encode(data)
|
|
}
|
|
}
|
|
|
|
func respondError(w http.ResponseWriter, status int, message string) {
|
|
respondJSON(w, status, map[string]string{"error": message})
|
|
}
|
|
|
|
func parseID(r *http.Request, prefix string) (int64, error) {
|
|
path := strings.TrimPrefix(r.URL.Path, prefix)
|
|
path = strings.TrimSuffix(path, "/")
|
|
parts := strings.Split(path, "/")
|
|
if len(parts) == 0 {
|
|
return 0, nil
|
|
}
|
|
return strconv.ParseInt(parts[0], 10, 64)
|
|
}
|
|
|
|
func decodeJSON(r *http.Request, v interface{}) error {
|
|
return json.NewDecoder(r.Body).Decode(v)
|
|
}
|