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
|
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"slices"
"github.com/jackc/pgx/v5/pgxpool"
"git.huntm.net/wedding/server/admin"
"git.huntm.net/wedding/server/guest"
)
var (
user = "postgres"
password = os.Getenv("PASS")
host = "localhost"
port = "5432"
database = "wedding"
)
func main() {
databasePool, err := pgxpool.New(context.Background(),
fmt.Sprintf("postgres://%s:%s@%s:%s/%s", user, password, host, port, database))
if err != nil {
log.Fatal(err)
}
defer databasePool.Close()
guestStore := guest.NewStore(databasePool)
guestHandler := guest.NewGuestHandler(guestStore)
adminStore := admin.NewStore(databasePool)
adminHandler := admin.NewAdminHandler(adminStore, guestStore)
mux := http.NewServeMux()
mux.Handle("/api/guests/", guestHandler)
mux.Handle("/api/admin/", adminHandler)
log.Fatal(http.ListenAndServe(":8080", serveHTTP(mux)))
}
func serveHTTP(handler http.Handler) http.Handler {
return http.HandlerFunc(func(responseWriter http.ResponseWriter,
request *http.Request) {
writeMethods(responseWriter, request)
writeOrigins(responseWriter, request)
writeHeaders(responseWriter)
handler.ServeHTTP(responseWriter, request)
})
}
func writeMethods(responseWriter http.ResponseWriter, request *http.Request) {
allowedMethods := []string{"OPTIONS", "POST", "PUT"}
method := request.Header.Get("Access-Control-Request-Method")
if isPreflight(request) && slices.Contains(allowedMethods, method) {
responseWriter.Header().Add("Access-Control-Allow-Methods", method)
}
}
func writeOrigins(responseWriter http.ResponseWriter, request *http.Request) {
allowedOrigins := []string{"http://localhost:5173", "http://192.168.1.11:5173"}
origin := request.Header.Get("Origin")
if slices.Contains(allowedOrigins, origin) {
responseWriter.Header().Add("Access-Control-Allow-Origin", origin)
}
}
func writeHeaders(responseWriter http.ResponseWriter) {
responseWriter.Header().Add("Access-Control-Allow-Headers", "*")
}
func isPreflight(request *http.Request) bool {
return request.Method == "OPTIONS" &&
request.Header.Get("Origin") != "" &&
request.Header.Get("Access-Control-Request-Method") != ""
}
|