This commit is contained in:
simonpetit 2024-12-20 17:06:42 +00:00
parent c35da8f016
commit e10bafbf76

38
main.go
View File

@ -5,25 +5,23 @@ import (
"net/http" "net/http"
"net/http/httputil" "net/http/httputil"
"net/url" "net/url"
"strings"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware" "github.com/go-chi/chi/v5/middleware"
) )
func main() { func main() {
apiURL := "https://catfact.ninja"
r := chi.NewRouter() r := chi.NewRouter()
r.Use(middleware.Logger) r.Use(middleware.Logger)
r.Use(middleware.Recoverer) r.Use(middleware.Recoverer)
// Parse the API URL // Parse the API URL
parsedURL, err := url.Parse(apiURL)
if err != nil {
log.Fatalf("Failed to parse API URL: %v", err)
}
r.Handle("/cats", reverseProxy(parsedURL, "/fact")) r.Handle("/cats/*", reverseProxy("https://catfact.ninja"))
r.Handle("/coins/*", reverseProxy("https://api.coindesk.com/v1/bpi"))
r.Get("/", func(w http.ResponseWriter, r *http.Request) { r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("root.")) w.Write([]byte("root."))
@ -34,21 +32,29 @@ func main() {
} }
// reverseProxy forwards requests to the target URL with path rewriting // reverseProxy forwards requests to the target URL with path rewriting
func reverseProxy(target *url.URL, targetPath string) http.Handler { func reverseProxy(target string, prefixToStrip string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Parse the target URL
parsedURL, err := url.Parse(target)
if err != nil {
log.Fatalf("Failed to parse target URL: %v", err)
}
// Create a reverse proxy // Create a reverse proxy
proxy := httputil.NewSingleHostReverseProxy(target) proxy := httputil.NewSingleHostReverseProxy(parsedURL)
// Update the request path to the target API path // Rewrite the request path by stripping the prefix
r.URL.Path = targetPath originalPath := r.URL.Path
r.URL.Host = target.Host strippedPath := strings.TrimPrefix(originalPath, prefixToStrip)
r.URL.Scheme = target.Scheme
// Set the Host header explicitly to match the target // Update the proxied request URL
r.Host = target.Host r.URL.Path = strippedPath // Use the stripped path in the proxy
r.URL.Scheme = parsedURL.Scheme
r.URL.Host = parsedURL.Host
r.Host = parsedURL.Host
// Debug: Log the final URL being proxied // Debug: Log the final proxied URL
log.Printf("Proxying request to: %s%s", target, targetPath) log.Printf("Proxying request to: %s%s", parsedURL, strippedPath)
// Serve the proxied request // Serve the proxied request
proxy.ServeHTTP(w, r) proxy.ServeHTTP(w, r)