-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
84 lines (72 loc) · 2.46 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
"github.com/michaelchristwin/taskmanager/db"
"github.com/michaelchristwin/taskmanager/handlers"
)
type CustomFileServer struct {
handler http.Handler
}
func (c *CustomFileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Set correct MIME type based on file extension
switch {
case strings.HasSuffix(r.URL.Path, ".js"):
w.Header().Set("Content-Type", "application/javascript")
case strings.HasSuffix(r.URL.Path, ".css"):
w.Header().Set("Content-Type", "text/css")
case strings.HasSuffix(r.URL.Path, ".html"):
w.Header().Set("Content-Type", "text/html")
case strings.HasSuffix(r.URL.Path, ".json"):
w.Header().Set("Content-Type", "application/json")
case strings.HasSuffix(r.URL.Path, ".png"):
w.Header().Set("Content-Type", "image/png")
case strings.HasSuffix(r.URL.Path, ".jpg"), strings.HasSuffix(r.URL.Path, ".jpeg"):
w.Header().Set("Content-Type", "image/jpeg")
case strings.HasSuffix(r.URL.Path, ".svg"):
w.Header().Set("Content-Type", "image/svg+xml")
}
c.handler.ServeHTTP(w, r)
}
func loadEnv() {
// Load .env file if it exists
if err := godotenv.Load(); err != nil {
log.Printf("No .env file found or error loading it: %v", err)
// Continue execution - we'll use os.Getenv which will check system environment variables
}
}
func main() {
loadEnv()
if err := db.Connect(); err != nil {
log.Fatalf("Failed to connect to the database: %v", err)
}
r := mux.NewRouter()
// Serve the frontend/dist directory directly
fs := http.FileServer(http.Dir("frontend/dist"))
customFs := &CustomFileServer{handler: fs}
// API routes
r.HandleFunc("/api/tasks", handlers.TaskHandler)
r.HandleFunc("/api/tasks/{id}", handlers.TaskHandler)
r.PathPrefix("/").Handler(customFs)
if os.Getenv("ENV") == "production" {
// In production, allow only the same origin
fmt.Println("Server running on http://localhost:8080")
if err := http.ListenAndServe(":8080", r); err != nil {
log.Fatalf("Server failed to start: %v", err)
}
} else {
// In development, allow localhost:3000
corsConfig := handlers.DefaultCORSConfig()
corsConfig.AllowedOrigins = []string{"http://localhost:3000"}
handlerWithCORS := handlers.CORSMiddleware(corsConfig)(r)
fmt.Println("Server running on http://localhost:8080")
if err := http.ListenAndServe(":8080", handlerWithCORS); err != nil {
log.Fatalf("Server failed to start: %v", err)
}
}
}