Added JSON ERROR

This commit is contained in:
cdricms
2025-01-15 15:28:14 +01:00
parent ca313299cf
commit 49005d7768
2 changed files with 35 additions and 17 deletions

View File

@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
"time"
@@ -27,21 +26,37 @@ type Claims struct {
func HandleLogin(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
log.Fatal("Not post method")
JSONError{
Status: Error,
Message: "Method is not allowed",
}.Respond(w, http.StatusMethodNotAllowed)
return
}
if r.Body == nil {
log.Fatal("No body")
JSONError{
Status: Error,
Message: "No body has been provided.",
}.Respond(w, http.StatusNoContent)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
JSONError{
Status: Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
var login LoginInformation
err = json.Unmarshal(body, &login)
if err != nil {
log.Fatal(err)
JSONError{
Status: Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
var user User
@@ -52,7 +67,11 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
Scan(context.Background())
if err != nil {
log.Fatal(err)
JSONError{
Status: Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
claims := Claims{
@@ -68,10 +87,18 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString([]byte("hello"))
if err != nil {
log.Fatal(err)
JSONError{
Status: Error,
Message: err.Error(),
}.Respond(w, http.StatusNoContent)
return
}
fmt.Println(signed)
JSONSuccess{
Status: Success,
Message: "JWT Created",
Data: map[string]string{"jwt": signed},
}.Respond(w, http.StatusCreated)
}
func AuthJWT(next http.Handler) http.Handler {