-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
71 lines (57 loc) · 1.66 KB
/
main.go
File metadata and controls
71 lines (57 loc) · 1.66 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
71
package main
import (
"fmt"
"net/http"
"strings"
"os"
"github.com/jackwrfuller/temp-handler/internal/controllers"
)
func main() {
c := controllers.NewBaseHandler()
router := http.NewServeMux()
router.HandleFunc("/", c.HandleRequests)
s := &http.Server{
Addr: ":3000",
Handler: corsMiddleware(authMiddleware(router)),
}
fmt.Println("Starting server...")
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err)
}
}
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/v1/status" {
next.ServeHTTP(w, r)
return
}
expectedToken := os.Getenv("ENDPOINT_TOKEN")
if expectedToken == "" {
http.Error(w, "Server not configured with ENDPOINT_TOKEN", http.StatusInternalServerError)
return
}
authHeader := r.Header.Get("Authorization")
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
token := strings.TrimPrefix(authHeader, "Bearer ")
if token != expectedToken {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(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", "Content-Type")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}