This repository has been archived by the owner on Sep 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
76 lines (59 loc) · 1.49 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
68
69
70
71
72
73
74
75
76
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/antonosmond/host-mutator/pkg/mutator"
)
var addr = ":8443"
var baseDomain = os.Getenv("BASE_DOMAIN")
var certPath = os.Getenv("SSL_CERT_PATH")
var keyPath = os.Getenv("SSL_KEY_PATH")
func init() {
if baseDomain == "" {
log.Fatal("BASE_DOMAIN environment variable must not be empty")
}
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/health", handleHealth)
mux.HandleFunc("/mutate", handleMutate)
s := &http.Server{
Addr: addr,
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20, // 1048576
}
log.Printf("Server listening on %s\n", addr)
log.Fatal(s.ListenAndServeTLS(certPath, keyPath))
}
func handleHealth(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s\n", r.URL, r.RemoteAddr)
w.WriteHeader(200)
}
func handleMutate(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s\n", r.URL, r.RemoteAddr)
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer r.Body.Close()
mutated, err := mutator.Mutate(body, baseDomain)
if err != nil {
log.Println(err)
// check if the error is due to a bad request
if _, ok := err.(*mutator.BadRequest); ok {
w.WriteHeader(http.StatusBadRequest)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
return
}
w.WriteHeader(http.StatusOK)
w.Write(mutated)
}