initial commit
This commit is contained in:
79
app/api.go
Normal file
79
app/api.go
Normal file
@@ -0,0 +1,79 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"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 io.ReadCloser) (T, error) {
|
||||
dst := new(T)
|
||||
data, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return *dst, err
|
||||
}
|
||||
err = json.Unmarshal(data, dst)
|
||||
return *dst, err
|
||||
}
|
||||
func ReadResponse[T any](r io.ReadCloser) (T, error) {
|
||||
var zero T
|
||||
resp, err := ReadBody[Response[T]](r)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
return resp.Data, nil
|
||||
}
|
||||
func CheckToken(r *http.Request) bool {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth != cfg.JWTSecret {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user