-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
72 lines (62 loc) · 1.56 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
// Fetch Headers attempts to fetch the headers of a service routed through Tailscale.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
)
var client = http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
},
}
func main() {
log.Print("starting server...")
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
http.HandleFunc("/", handler)
port := os.Getenv("PORT")
if port == "" {
port = "80"
log.Printf("defaulting to port %s", port)
}
log.Printf("listening on port %s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
endpoint := os.Getenv("TAILSCALE_ENDPOINT")
fmt.Fprintf(w, "fetching %s...\n\n", endpoint)
hdrFetch(ctx, w, endpoint)
if err := ctx.Err(); err != nil {
fmt.Fprintf(w, "context error: %v\n", err)
}
}
func hdrFetch(ctx context.Context, w http.ResponseWriter, addr string) {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, addr, nil)
if err != nil {
fmt.Fprintf(w, "unable to create new request: %v\n", err)
return
}
res, err := client.Do(req)
if err != nil {
fmt.Fprintf(w, "unable to issue http request: %v\n", err)
return
}
defer res.Body.Close()
var sb strings.Builder
for k, v := range res.Header {
fmt.Fprintf(&sb, "%s => %q\n", k, v)
}
fmt.Fprintln(w, sb.String())
}