-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
77 lines (65 loc) · 2.12 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
package main
import (
"log"
"net/http"
"os"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/joho/godotenv"
"github.com/xqsit94/cypher/internal/handlers"
)
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
w.Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()")
next.ServeHTTP(w, r)
})
}
func main() {
// Load environment variables
if err := godotenv.Load(); err != nil {
log.Println("No .env file found, proceeding with environment variables")
}
// Initialize router
r := chi.NewRouter()
// Middleware
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.RealIP)
r.Use(securityHeaders)
r.Use(middleware.ThrottleBacklog(20, 10, time.Second*5))
// Get port from environment
port := os.Getenv("PORT")
if port == "" {
port = "8000"
}
// Get allowed origins from environment or use default based on port
allowedOrigins := []string{"http://localhost:" + port}
if origins := os.Getenv("ALLOWED_ORIGINS"); origins != "" {
allowedOrigins = []string{origins}
}
r.Use(cors.Handler(cors.Options{
AllowedOrigins: allowedOrigins,
AllowedMethods: []string{"GET", "POST", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
}))
// File server for static files
fileServer := http.FileServer(http.Dir("static"))
r.Handle("/static/*", http.StripPrefix("/static/", fileServer))
// Routes
r.Get("/", handlers.HomeHandler)
r.Post("/encrypt", handlers.EncryptHandler)
r.Post("/decrypt", handlers.DecryptHandler)
log.Printf("Server starting on port %s", port)
if err := http.ListenAndServe(":"+port, r); err != nil {
log.Fatal(err)
}
}