67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
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
|
|
}
|
|
func CheckToken(r *http.Request) bool {
|
|
auth := r.Header.Get("Authorization")
|
|
if auth != cfg.JWTSecret {
|
|
return false
|
|
}
|
|
return true
|
|
}
|