Last active
October 25, 2024 15:41
-
-
Save JalfResi/6287706 to your computer and use it in GitHub Desktop.
Simple reverse proxy in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import( | |
"log" | |
"net/url" | |
"net/http" | |
"net/http/httputil" | |
) | |
func main() { | |
remote, err := url.Parse("http://google.com") | |
if err != nil { | |
panic(err) | |
} | |
handler := func(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) { | |
return func(w http.ResponseWriter, r *http.Request) { | |
log.Println(r.URL) | |
r.Host = remote.Host | |
w.Header().Set("X-Ben", "Rad") | |
p.ServeHTTP(w, r) | |
} | |
} | |
proxy := httputil.NewSingleHostReverseProxy(remote) | |
http.HandleFunc("/", handler(proxy)) | |
err = http.ListenAndServe(":8080", nil) | |
if err != nil { | |
panic(err) | |
} | |
} |
Great!
hi, after saved this file, how can i try?
go run main.go
then
curl localhost:8080
I think
Made some changes to add support for ssl. And cleanup handler.
`package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"crypto/tls"
)
func main() {
// Replace 'target' with the URL of the server you want to proxy to
target, err := url.Parse("https://example.com")
if err != nil {
panic(err)
}
// Create a new ReverseProxy instance
proxy := httputil.NewSingleHostReverseProxy(target)
// Configure the reverse proxy to use HTTPS
proxy.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
// Create a handler function that logs the URL and forwards the request to the proxy
handler := func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL)
r.Host = target.Host
//w.Header().Set("X-Ben", "radi")
proxy.ServeHTTP(w, r)
}
// Register the handler function with the HTTP server
http.HandleFunc("/", handler)
// Start the HTTP server
err = http.ListenAndServe(":3000", nil)
if err != nil {
panic(err)
}
}`
Modified it to use struct and ssl
https://gist.github.com/c0d3kid/862276a6291e4aeaf2638e5f7e93a954
Helpful, ta, used this to transparently adjust some query parameters for certain requests.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @lwzm!