Skip to content

Commit

Permalink
Use httputil/NewSingleHostReverseProxy instead of our own implementat…
Browse files Browse the repository at this point in the history
…ion (#5)
  • Loading branch information
kotx authored Dec 7, 2024
1 parent 58400a7 commit 2c59c66
Showing 1 changed file with 3 additions and 39 deletions.
42 changes: 3 additions & 39 deletions cmd/proxy/main.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
package main

import (
"errors"
"flag"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"

"tailscale.com/client/tailscale"
"tailscale.com/tsnet"
Expand Down Expand Up @@ -45,15 +42,9 @@ func main() {
log.Fatalf("error creating tailscale local client: %v", err)
}

proxy := httputil.NewSingleHostReverseProxy(endpointUrl)
log.Printf("proxying requests to %s", endpointUrl)

httpClient := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: time.Minute,
}

log.Fatal(http.Serve(ln,
http.HandlerFunc(
func(writer http.ResponseWriter, req *http.Request) {
Expand All @@ -72,10 +63,6 @@ func main() {
slog.Debug("tailscale", "whois", who)

req.Host = endpointUrl.Host
req.URL.Host = endpointUrl.Host
req.URL.Scheme = endpointUrl.Scheme
req.RequestURI = ""

for key, value := range req.Header {
if strings.HasPrefix(http.CanonicalHeaderKey("X-Remote-"), key) {
slog.Info("removing spoofed header", "key", key, "value", value)
Expand All @@ -89,29 +76,6 @@ func main() {
req.Header.Set("X-Remote-User-Id", who.UserProfile.ID.String())
}

res, err := httpClient.Do(req)
if err != nil {
var urlError *url.Error
if errors.As(err, &urlError) && urlError.Timeout() {
writer.WriteHeader(http.StatusGatewayTimeout)
} else {
writer.WriteHeader(http.StatusBadGateway)
}

_, _ = fmt.Fprint(writer, err)
slog.Error("proxying request", "err", err)
return
}

for key, value := range res.Header {
writer.Header()[key] = value
}
writer.WriteHeader(res.StatusCode)

_, err = io.Copy(writer, res.Body)
defer res.Body.Close()
if err != nil {
slog.Error("reading response body", "err", err)
}
proxy.ServeHTTP(writer, req)
})))
}

0 comments on commit 2c59c66

Please sign in to comment.