71 lines
1.7 KiB
Go
71 lines
1.7 KiB
Go
package utils
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"reflect"
|
|
"strings"
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
)
|
|
|
|
var Validate = validator.New()
|
|
|
|
func WriteJSON(w http.ResponseWriter, status int, v any) error {
|
|
w.Header().Add("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
resp := map[string]any{"status": "OK", "data": v}
|
|
return json.NewEncoder(w).Encode(resp)
|
|
}
|
|
|
|
func WriteJSONLogin(w http.ResponseWriter, status int, v any, t any, n any) error {
|
|
w.Header().Add("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
resp := map[string]any{"status": "OK", "user": v, "token": t, "type": n}
|
|
return json.NewEncoder(w).Encode(resp)
|
|
}
|
|
|
|
func WriteError(w http.ResponseWriter, status int, err error) {
|
|
w.Header().Add("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
resp := map[string]any{"status": "ERR", "message": err.Error()}
|
|
json.NewEncoder(w).Encode(resp)
|
|
}
|
|
|
|
func ParseJSON(r *http.Request, v any) error {
|
|
if r.Body == nil {
|
|
return fmt.Errorf("missing request body")
|
|
}
|
|
|
|
return json.NewDecoder(r.Body).Decode(v)
|
|
}
|
|
|
|
func GetTokenFromRequest(r *http.Request) string {
|
|
tokenAuth := r.Header.Get("Authorization")
|
|
if strings.HasPrefix(tokenAuth, "Bearer ") {
|
|
return strings.TrimPrefix(tokenAuth, "Bearer ")
|
|
}
|
|
|
|
tokenQuery := r.URL.Query().Get("token")
|
|
if tokenQuery != "" {
|
|
return tokenQuery
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func MatchStruct(src interface{}, dst interface{}) error {
|
|
srcVal := reflect.ValueOf(src)
|
|
dstVal := reflect.ValueOf(dst).Elem()
|
|
|
|
for i := 0; i < srcVal.NumField(); i++ {
|
|
srcField := srcVal.Type().Field(i)
|
|
dstField := dstVal.FieldByName(srcField.Name)
|
|
|
|
if dstField.IsValid() && dstField.CanSet() && srcField.Type == dstField.Type() {
|
|
dstField.Set(srcVal.Field(i))
|
|
}
|
|
}
|
|
return nil
|
|
}
|