-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
68 lines (53 loc) · 1.49 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"fmt"
"log"
"net/http"
"os"
"fastURL/handlers"
"fastURL/model"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
)
func withCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") // Permitir todos los orígenes (modificar según sea necesario)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Manejar preflight requests
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
// Load environment variables
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file: %v\n", err)
}
// DB setup
model.InitDB()
defer model.CloseDB()
// Endpoints setup
r := mux.NewRouter()
handlers.RegisterHandlers(r)
// Server setup
certfile := os.Getenv("CERTFILE")
keyfile := os.Getenv("KEYFILE")
// Start on HTTPS if certfile and keyfile are provided
if certfile != "" && keyfile != "" {
log.Println("Starting https server on :8088")
err := http.ListenAndServeTLS(":8088", certfile, keyfile, withCORS(r))
if err != nil {
log.Fatalf("Error starting https server:", err)
}
} else {
fmt.Println("Starting http server on :8088")
if err := http.ListenAndServe(":8088", withCORS(r)); err != nil {
log.Fatalf("Error starting http server:", err)
}
}
}