mirror of
https://github.com/twhite96/go-backend-api.git
synced 2025-01-31 06:59:15 +00:00
50 lines
1.4 KiB
Go
50 lines
1.4 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
func (s *Server) RegisterRoutes() http.Handler {
|
|
mux := http.NewServeMux()
|
|
|
|
// Register routes
|
|
mux.HandleFunc("/", s.HelloWorldHandler)
|
|
|
|
// Wrap the mux with CORS middleware
|
|
return s.corsMiddleware(mux)
|
|
}
|
|
|
|
func (s *Server) corsMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Set CORS headers
|
|
w.Header().Set("Access-Control-Allow-Origin", "*") // Replace "*" with specific origins if needed
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-CSRF-Token")
|
|
w.Header().Set("Access-Control-Allow-Credentials", "false") // Set to "true" if credentials are required
|
|
|
|
// Handle preflight OPTIONS requests
|
|
if r.Method == http.MethodOptions {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
|
|
// Proceed with the next handler
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func (s *Server) HelloWorldHandler(w http.ResponseWriter, r *http.Request) {
|
|
resp := map[string]string{"message": "Hello World"}
|
|
jsonResp, err := json.Marshal(resp)
|
|
if err != nil {
|
|
http.Error(w, "Failed to marshal response", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if _, err := w.Write(jsonResp); err != nil {
|
|
log.Printf("Failed to write response: %v", err)
|
|
}
|
|
}
|