mirror of
https://github.com/netbirdio/netbird.git
synced 2026-07-31 09:58:38 -04:00
65 lines
2.2 KiB
Go
65 lines
2.2 KiB
Go
package proxy
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"sync"
|
|
|
|
"github.com/netbirdio/netbird/proxy/internal/roundtrip"
|
|
"github.com/netbirdio/netbird/proxy/web"
|
|
)
|
|
|
|
type ReverseProxy struct {
|
|
transport http.RoundTripper
|
|
mappingsMux sync.RWMutex
|
|
mappings map[string]Mapping
|
|
}
|
|
|
|
// NewReverseProxy configures a new NetBird ReverseProxy.
|
|
// This is a wrapper around an httputil.ReverseProxy set
|
|
// to dynamically route requests based on internal mapping
|
|
// between requested URLs and targets.
|
|
// The internal mappings can be modified using the AddMapping
|
|
// and RemoveMapping functions.
|
|
func NewReverseProxy(transport http.RoundTripper) *ReverseProxy {
|
|
return &ReverseProxy{
|
|
transport: transport,
|
|
mappings: make(map[string]Mapping),
|
|
}
|
|
}
|
|
|
|
func (p *ReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
target, serviceId, accountID, exists := p.findTargetForRequest(r)
|
|
if !exists {
|
|
web.ServeHTTP(w, r, map[string]any{
|
|
"page": "error",
|
|
"error": map[string]any{
|
|
"code": 404,
|
|
"title": "Service Not Found",
|
|
"message": "The requested service could not be found. Please check the URL, try refreshing, or check if the peer is running. If that doesn't work, see our documentation for help.",
|
|
},
|
|
}, http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
// Set the serviceId in the context for later retrieval.
|
|
ctx := withServiceId(r.Context(), serviceId)
|
|
// Set the accountId in the context for later retrieval (for middleware).
|
|
ctx = withAccountId(ctx, accountID)
|
|
// Set the accountId in the context for the roundtripper to use.
|
|
ctx = roundtrip.WithAccountID(ctx, accountID)
|
|
|
|
// Also populate captured data if it exists (allows middleware to read after handler completes).
|
|
// This solves the problem of passing data UP the middleware chain: we put a mutable struct
|
|
// pointer in the context, and mutate the struct here so outer middleware can read it.
|
|
if capturedData := CapturedDataFromContext(ctx); capturedData != nil {
|
|
capturedData.SetServiceId(serviceId)
|
|
capturedData.SetAccountId(accountID)
|
|
}
|
|
|
|
// Set up a reverse proxy using the transport and then use it to serve the request.
|
|
proxy := httputil.NewSingleHostReverseProxy(target)
|
|
proxy.Transport = p.transport
|
|
proxy.ServeHTTP(w, r.WithContext(ctx))
|
|
}
|