Reverse Proxy Beispiel

This commit is contained in:
Marco Kittel 2025-06-28 09:50:35 +02:00
parent ee934e1baf
commit 075b9113bc
5 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,11 @@
#
Zum Test Proxy und zwei Webserver auf Port 8081 und 8082 aufrufen.
## Proxy aufrufen
go run cmd/shell/main.go
## Webserver aufrufen
go run cmd/websrv/main.go 8081
go run cmd/websrv/main.go 8082

24
cmd/shell/main.go Normal file
View File

@ -0,0 +1,24 @@
package main
import (
"fmt"
"log"
"net/http"
"gittea.kittel.dev/marco/proxy/proxy"
)
var (
PORT = 8080
)
func main() {
targets := []string{
"http://localhost:8081",
"http://localhost:8082",
}
p := proxy.NewProxy(targets)
log.Println("Reverse proxy started on %d", PORT)
portStr := fmt.Sprintf(":%d", PORT)
log.Fatal(http.ListenAndServe(portStr, p))
}

16
cmd/websrv/main.go Normal file
View File

@ -0,0 +1,16 @@
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
port := os.Args[1]
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from backend %s", port)
})
fmt.Println("Backend listening on port:", port)
http.ListenAndServe(":"+port, nil)
}

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module gittea.kittel.dev/marco/proxy
go 1.24.4

44
proxy/proxy.go Normal file
View File

@ -0,0 +1,44 @@
package proxy
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"sync/atomic"
)
type Proxy struct {
targets []*url.URL
counter uint64
}
func NewProxy(targets []string) *Proxy {
parsed := []*url.URL{}
for _, t := range targets {
u, err := url.Parse(t)
if err != nil {
log.Fatalf("")
}
parsed = append(parsed, u)
}
return &Proxy{targets: parsed}
}
func (p *Proxy) getNextTarget() *url.URL {
i := atomic.AddUint64(&p.counter, 1)
return p.targets[(int(i)-1)%len(p.targets)]
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
target := p.getNextTarget()
proxy := httputil.NewSingleHostReverseProxy(target)
r.Host = target.Host
log.Printf("Weiterleitung der Anfrage %s %s --> %s", r.Method, r.URL.Path, target)
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("!! Proxy error for %s: %v", r.URL.Path, err)
http.Error(w, "Reverse Proxy Error", http.StatusBadGateway)
}
proxy.ServeHTTP(w, r)
}