-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
101 lines (81 loc) · 2.5 KB
/
Copy pathmain.go
File metadata and controls
101 lines (81 loc) · 2.5 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"errors"
"fmt"
"io"
"net/http"
"os"
"sort"
)
func getRootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("New Root endpoint hit")
fmt.Fprintln(w, "New Root endpoint reached")
}
func getTestHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Test endpoint reached")
fmt.Fprintln(w, "Test endpoint reached")
// http.Post("http://run-as-user:8000/api/v1/jobs", "application/json", nil)
http.Post("http://cron-job:8080/api/v1/jobs", "application/json", nil)
}
func getHeadersHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Headers endpoint reached")
fmt.Fprintln(w, "Headers endpoint reached\n")
keys := make([]string, 0, len(r.Header))
for key := range r.Header {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Fprintf(w, "%s: %s\n", key, r.Header[key])
}
}
func getUserHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("User endpoint reached")
fmt.Fprintf(w, "UID: %d\n", os.Getuid())
fmt.Fprintf(w, "GID: %d\n", os.Getgid())
}
func getStartJobHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Start job endpoint reached")
fmt.Fprintln(w, "Job endpoint reached")
return
resp, err := http.Post("http://run-as-user:8000/api/v1/jobs", "application/json", nil)
if err != nil {
fmt.Fprintf(w, "Error: %s", err)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Fprintf(w, "Error: %s", err)
return
}
fmt.Fprintf(w, "Body:\n%s", string(body))
}
func redirectMiddleware(next http.Handler) http.Handler {
// return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// if r.Header.Get("X-Forwarded-Proto") != "https" || r.TLS != nil {
// target := "https://" + r.Host + r.URL.RequestURI()
// http.Redirect(w, r, target, http.StatusMovedPermanently)
// return
// }
// next.ServeHTTP(w, r)
// })
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", getRootHandler)
mux.HandleFunc("/test", getTestHandler)
mux.HandleFunc("/headers", getHeadersHandler)
mux.HandleFunc("/runasuser", getUserHandler)
mux.HandleFunc("/startjob", getStartJobHandler)
fmt.Println("Server starting on :1234")
err := http.ListenAndServe(":1234", redirectMiddleware(mux))
if errors.Is(err, http.ErrServerClosed) {
fmt.Println("Server was closed")
} else if err != nil {
fmt.Printf("Error starting server: %s\n", err)
}
}