all repos — piggy @ main

Dead simple finance manager in Go, HTML and JS.

src/api/utils.go (view raw)

 1package api
 2
 3import (
 4	"encoding/json"
 5	"log"
 6	"net/http"
 7	"strconv"
 8)
 9
10type APIError struct {
11	Error string `json:"error"`
12}
13
14func jsonResponse(w http.ResponseWriter, v any) {
15	w.Header().Add("Content-Type", "application/json")
16	err := json.NewEncoder(w).Encode(v)
17	if err != nil {
18		log.Println("could not encode JSON response: " + err.Error())
19	}
20}
21
22func new500Error(w http.ResponseWriter, err error) {
23	http.Error(w, err.Error(), http.StatusInternalServerError)
24}
25
26func new400Error(w http.ResponseWriter, err error) {
27	http.Error(w, err.Error(), http.StatusBadRequest)
28}
29
30func getId(r *http.Request) (id uint, err error) {
31	v := r.PathValue("id")
32	id64, err := strconv.ParseUint(v, 10, 0)
33	if err != nil {
34		return
35	}
36	return uint(id64), nil
37}