-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
67 lines (55 loc) · 1.72 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
package main
import (
"flag"
"log"
"net/http"
"time"
"github.com/dogeorg/reflector/pkg/api"
"github.com/dogeorg/reflector/pkg/database"
reflectormiddleware "github.com/dogeorg/reflector/pkg/middleware"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func CORS() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "*")
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
func main() {
// Initialize database
db, err := database.NewDatabase()
if err != nil {
log.Fatalf("Failed to initialize database: %v", err)
}
defer db.Close()
// Create router
r := chi.NewRouter()
// Middleware
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Post("/", func(w http.ResponseWriter, r *http.Request) {
reflectormiddleware.RateLimiter(time.Minute, 1)(api.CreateEntry(db)).ServeHTTP(w, r)
})
r.With(CORS()).Get("/dbxcheck", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("{\"status\": \"ok\"}"))
})
r.With(CORS()).Options("/{token}", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
r.With(CORS()).Get("/{token}", func(w http.ResponseWriter, r *http.Request) {
api.GetIP(db).ServeHTTP(w, r)
})
bindAddr := flag.String("bind", ":8080", "Bind address and port for the server")
flag.Parse()
// Start server
log.Printf("Server starting on %s\n", *bindAddr)
log.Fatal(http.ListenAndServe(*bindAddr, r))
}