-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
70 lines (58 loc) · 1.64 KB
/
main.go
File metadata and controls
70 lines (58 loc) · 1.64 KB
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
package main
import (
"log"
"net/http"
"os"
"path/filepath"
"time"
)
// securityHeaders middleware adds basic security protections
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-XSS-Protection", "1; mode=block")
w.Header().Set("Content-Security-Policy", "default-src 'self'")
next.ServeHTTP(w, r)
})
}
// custom file server that prevents directory traversal
func safeFileServer(root http.Dir) http.Handler {
fs := http.FileServer(root)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Clean the path to prevent traversal
cleanPath := filepath.Clean(r.URL.Path)
// Force root to index.html
if cleanPath == "/" {
http.ServeFile(w, r, "static/index.html")
return
}
// Build full path
fullPath := filepath.Join(string(root), cleanPath)
// Check if file exists
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
w.WriteHeader(http.StatusNotFound)
http.ServeFile(w, r, "static/404.html")
return
}
fs.ServeHTTP(w, r)
})
}
func main() {
mux := http.NewServeMux()
// Serve static files securely
fileHandler := safeFileServer(http.Dir("./static"))
mux.Handle("/", securityHeaders(fileHandler))
server := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}
log.Println("Server running at http://localhost:8080")
err := server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}