Last active
July 21, 2022 05:36
-
-
Save corvofeng/78a6afc994abf8b3a558bc89fb87b86c to your computer and use it in GitHub Desktop.
forward http request to unix socket
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" | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
) | |
// From: https://stackoverflow.com/a/26224019/5563477 | |
func fakeDial(proto, addr string) (conn net.Conn, err error) { | |
return net.Dial("unix", "/tmp/vscode.sock") | |
} | |
func main() { | |
tr := &http.Transport{ | |
Dial: fakeDial, | |
} | |
remote, err := url.Parse("http://localhost") | |
if err != nil { | |
log.Fatal(err) | |
} | |
proxy := httputil.NewSingleHostReverseProxy(remote) | |
proxy.Transport = tr | |
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) | |
} | |
} | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", handler(proxy)) | |
log.Println(http.ListenAndServe(":8090", mux)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment