Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package main

import (
"bytes"
"context"
"crypto/tls"
"flag"
"fmt"
"io"
"net"
"net/http"
"os"
Expand Down Expand Up @@ -271,6 +273,12 @@ func serveHTTP(rw http.ResponseWriter, r *http.Request) {
respondWith(rw, err, http.StatusForbidden)
return
}

if r.URL.Query().Get(xRedirectQuery) == "1" {
redirect(proxy, rw, r)
return
}

proxy.ServeHTTP(rw, r)
default:
badRequest.Inc()
Expand All @@ -280,6 +288,39 @@ func serveHTTP(rw http.ResponseWriter, r *http.Request) {
}
}

func redirect(proxy *reverseProxy, rw http.ResponseWriter, r *http.Request) {
name, password := getAuth(r)
found, _, c, _ := proxy.getUser(name, password)
if !found {
rw.Header().Set("Connection", "close")
err := fmt.Errorf("invalid username or password for user %q", name)
respondWith(rw, err, http.StatusUnauthorized)
return
}

targetURL := *r.URL
targetURL.Host = c.getReplica().getHost().Host()
targetURL.User = *&r.URL.User

query := targetURL.Query()
query.Del(xRedirectQuery)
targetURL.RawQuery = query.Encode()

if r.Body != nil && r.Body != http.NoBody {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
respondWith(rw, fmt.Errorf("failed to read request body: %v", err), http.StatusInternalServerError)
return
}
r.Body.Close()
r.Body = io.NopCloser(bytes.NewReader(bodyBytes))
r.ContentLength = int64(len(bodyBytes))
}

rw.Header().Set("Location", targetURL.String())
rw.WriteHeader(http.StatusPermanentRedirect)
}

func loadConfig() (*config.Config, error) {
if *configFile == "" {
log.Fatalf("Missing -config flag")
Expand Down
2 changes: 2 additions & 0 deletions proxy_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const (
xForwardedForHeader = "X-Forwarded-For"
xRealIPHeader = "X-Real-Ip"
forwardedHeader = "Forwarded"

xRedirectQuery = "X-Redirect" //Query
)

type ProxyHandler struct {
Expand Down