Files
ris-backend-go/utils/utils.go
2024-12-12 09:53:29 +07:00

76 lines
2.0 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 {
// fmt.Printf("Request: %v\n", r.)
var tokenAuth string
tokenAuth = r.Header.Get("Authorization")
// fmt.Printf("Token Auth: %v\n", tokenAuth)
tokenQuery := r.URL.Query().Get("token")
// fmt.Printf("Token Query: %v\n", tokenQuery)
if tokenQuery != "" {
tokenAuth = tokenQuery
}
tokenAuth = strings.TrimSpace(tokenAuth)
tokenAuth = strings.ReplaceAll(tokenAuth, "Bearer", "")
tokenAuth = strings.ReplaceAll(tokenAuth, "\"", "")
tokenAuth = strings.TrimSpace(tokenAuth)
return tokenAuth
}
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
}