Go-TestAPI/libs/libs.go

49 lines
1.1 KiB
Go
Raw Normal View History

package libs
import (
2024-06-07 12:52:09 +00:00
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
2024-06-07 12:52:09 +00:00
"golang-test/types"
"net/http"
"strings"
)
2024-06-07 12:52:09 +00:00
type ValidationErrorsType struct {
Errors map[string]string `json:"errors"`
}
func GetValidationErrors(errs validator.ValidationErrors) ValidationErrorsType {
errors := make(map[string]string)
for _, err := range errs {
errors[err.Field()] = err.Error()
}
2024-06-07 12:52:09 +00:00
return ValidationErrorsType{Errors: errors}
}
func ToSnakeCase(str string) string {
var result []rune
for i, r := range str {
if i > 0 && 'A' <= r && r <= 'Z' {
result = append(result, '_')
}
result = append(result, r)
}
return strings.ToLower(string(result))
}
2024-06-07 12:52:09 +00:00
func GetTokenFromHeaders(c *gin.Context) (string, error) {
if c.Request.Header["Authorization"] == nil {
return "", errors.New("Authorization required")
}
if len(strings.Split(c.Request.Header["Authorization"][0], " ")) < 2 {
c.JSON(http.StatusUnauthorized, types.ErrorResponse{Message: "Invalid token. Please login"})
return "", errors.New("Authorization required")
}
token := strings.Split(c.Request.Header["Authorization"][0], " ")[1]
return token, nil
}