Skip to content

Instantly share code, notes, and snippets.

@maggie44
Created December 15, 2024 18:06
Show Gist options
  • Save maggie44/189b2536e39f4660f12f3b92235ca3fc to your computer and use it in GitHub Desktop.
Save maggie44/189b2536e39f4660f12f3b92235ca3fc to your computer and use it in GitHub Desktop.
Nebula gVisor API Request Forwarder
func startHTTPReverseProxy(ctx context.Context, svc *service.Service) error {
mux := http.NewServeMux()
server := &http.Server{
Addr: ":3399",
Handler: mux,
}
// Create a custom transport with the custom dial context
transport := &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return svc.DialContext(ctx, network, addr)
},
}
mux.HandleFunc("/proxy/", func(w http.ResponseWriter, r *http.Request) {
// Extract the target from query parameters
target := r.URL.Query().Get("target")
if target == "" {
http.Error(w, "missing target parameter", http.StatusBadRequest)
return
}
// Parse the target URL
targetURL, err := url.Parse(target)
if err != nil {
http.Error(w, fmt.Sprintf("invalid target parameter: %s", err), http.StatusBadRequest)
return
}
// Create a reverse proxy
proxy := &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
// Use only the target's path and query parameters. SetURL sets the majority of the URL fields.
// Path and RawQuery replace the path to override the default which is to append the request
// path to the target.
r.SetURL(targetURL)
r.Out.URL.Path = targetURL.Path
r.Out.URL.RawQuery = targetURL.RawQuery
r.Out.URL.RawPath = targetURL.RawPath
},
Transport: transport,
}
proxy.ServeHTTP(w, r)
})
go func() {
<-ctx.Done()
log.Println("shutting down server")
_ = server.Shutdown(context.Background())
}()
log.Printf("starting server on %s", server.Addr)
return server.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment