-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
52 lines (43 loc) · 1.22 KB
/
server.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
package main
import (
"io"
"net/http"
"os"
"strings"
)
func startServer() {
http.HandleFunc("/generate-config", authMiddleware(handleNginxConfigRequest))
log.Infof("Server is running on port 8080...")
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
token = strings.TrimPrefix(token, "Bearer ")
if token != os.Getenv("API_KEY") {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
}
}
func handleNginxConfigRequest(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
return
}
log.Info("Received request")
jsonConfig, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusInternalServerError)
return
}
if err := setupNginxConfig(reloadNginxConfig, jsonConfig); err != nil {
http.Error(w, "Failed to setup Nginx config", http.StatusInternalServerError)
log.Errorw("Failed to setup Nginx config", "error", err)
return
}
w.WriteHeader(http.StatusOK)
}