Added /users/me route, and handling auth in frontend

This commit is contained in:
cdricms
2025-01-17 15:37:01 +01:00
parent 5405cc50d9
commit eb9883a1c3
20 changed files with 453 additions and 68 deletions

View File

@@ -17,6 +17,21 @@ import (
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<html><body><h1>Hello, World!</h1></body></html>")
}
func Cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Allow all origins (can restrict to specific origins)
w.Header().Set("Access-Control-Allow-Origin", "*")
// Allow certain HTTP methods (you can customize these as needed)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
// Allow certain headers (you can add more as needed)
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Handle OPTIONS pre-flight request
if r.Method == http.MethodOptions {
return
}
next.ServeHTTP(w, r)
})
}
func main() {
err := godotenv.Load()
@@ -52,10 +67,13 @@ func main() {
core.HandleRoutes(mux, map[string]core.Handler{
"/": {
Handler: handler,
Middlewares: []core.Middleware{api.Methods("post")}},
Middlewares: []core.Middleware{api.Methods("get")}},
"/users/login": {
Handler: api.HandleLogin,
Middlewares: []core.Middleware{api.Methods("POST")}},
"/users/me": {
Handler: api.HandleGetMe,
Middlewares: []core.Middleware{api.Methods("GET"), api.AuthJWT}},
"/users": {
Handler: api.HandleGetUsers,
Middlewares: []core.Middleware{api.Methods("GET"), api.AuthJWT}},
@@ -80,7 +98,7 @@ func main() {
})
fmt.Printf("Serving on port %s\n", port)
err = http.ListenAndServe(fmt.Sprintf(":%s", port), mux)
err = http.ListenAndServe(fmt.Sprintf(":%s", port), Cors(mux))
if err != nil {
fmt.Printf("Error starting server: %s\n", err)
}