initial commit

This commit is contained in:
2026-02-27 13:23:16 +03:00
commit 3701af1fd7
12 changed files with 512 additions and 0 deletions

59
app/api.go Normal file
View File

@@ -0,0 +1,59 @@
package app
import (
"encoding/json"
"log"
"net/http"
)
type Error struct {
Ok bool `json:"ok"`
Error string `json:"error"`
}
func WriteError(w http.ResponseWriter, err error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
e := json.NewEncoder(w).Encode(Error{
Ok: false,
Error: err.Error(),
})
if e != nil {
log.Println(e)
}
}
type Response[T any] struct {
Ok bool `json:"ok"`
Data T `json:"data"`
}
func WriteResponse[T any](w http.ResponseWriter, data T) {
WriteResponseCode(w, data, 200)
}
func WriteResponseCode[T any](w http.ResponseWriter, data T, code int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
e := enc.Encode(Response[T]{
Ok: true,
Data: data,
})
if e != nil {
log.Println(e)
}
}
func WriteResponseOrError[T any](w http.ResponseWriter, data T, err error) {
if err != nil {
WriteError(w, err)
} else {
WriteResponse(w, data)
}
}
func ReadBody[T any](r *http.Request) (T, error) {
dst := new(T)
err := json.NewDecoder(r.Body).Decode(dst)
return *dst, err
}