Added CORS middleware

This commit is contained in:
Steve White 2024-10-04 22:05:30 -05:00
parent 818cfcd818
commit 34580a4646
3 changed files with 16 additions and 4 deletions

1
go.mod
View File

@ -6,6 +6,7 @@ require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gorilla/mux v1.8.1
github.com/jinzhu/gorm v1.9.16
github.com/rs/cors v1.11.1
github.com/stretchr/testify v1.9.0
gopkg.in/yaml.v2 v2.4.0
)

2
go.sum
View File

@ -26,6 +26,8 @@ github.com/mattn/go-sqlite3 v1.14.0 h1:mLyGNKR8+Vv9CAU7PphKa2hkEqxxhn8i32J6FPj1/
github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=

17
main.go
View File

@ -7,6 +7,7 @@ import (
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
"github.com/rs/cors"
)
var (
@ -26,7 +27,7 @@ func main() {
log.Fatalf("Failed to load config: %v", err)
}
// Conne:ct to the database
// Connect to the database
db, err = ConnectDB(config.DatabasePath)
fmt.Println("DB Connection String:", db.DB().Ping())
if err != nil || db == nil {
@ -39,7 +40,7 @@ func main() {
// Create the router
router := mux.NewRouter()
// Apply JWT authentication middleware to protected endpoints
// Define your routes
router.Handle("/login", http.HandlerFunc(LoginHandler)).Methods("POST", "OPTIONS")
router.Handle("/boxes", AuthMiddleware(http.HandlerFunc(GetBoxesHandler))).Methods("GET", "OPTIONS")
router.Handle("/boxes", AuthMiddleware(http.HandlerFunc(CreateBoxHandler))).Methods("POST", "OPTIONS")
@ -51,7 +52,15 @@ func main() {
router.Handle("/items/{id}", AuthMiddleware(http.HandlerFunc(UpdateItemHandler))).Methods("PUT", "OPTIONS")
router.Handle("/items/{id}", AuthMiddleware(http.HandlerFunc(DeleteItemHandler))).Methods("DELETE", "OPTIONS")
// Start the server
// Apply CORS middleware
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000"}, // Change this to your frontend domain
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Authorization", "Content-Type"},
AllowCredentials: true,
})
// Start the server with CORS middleware
fmt.Printf("Server listening on port %d\n", config.ListeningPort)
http.ListenAndServe(fmt.Sprintf(":%d", config.ListeningPort), router)
http.ListenAndServe(fmt.Sprintf(":%d", config.ListeningPort), c.Handler(router))
}