Created
July 26, 2021 23:32
-
-
Save cauefcr/5395b557470b069c0465ed6eaf890087 to your computer and use it in GitHub Desktop.
reverse proxy i use at my raspberry pi
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/http" | |
"net/http/httputil" | |
"net/url" | |
) | |
func makeHandler(hostTarget map[string]string) func(w http.ResponseWriter, r *http.Request) { | |
hostProxy := map[string]*httputil.ReverseProxy{} | |
for k, v := range hostTarget { | |
remoteUrl, err := url.Parse(v) | |
if err != nil { | |
log.Println("target parse fail:", err) | |
return nil | |
} | |
proxy := httputil.NewSingleHostReverseProxy(remoteUrl) | |
hostProxy[k] = proxy | |
} | |
return func(w http.ResponseWriter, r *http.Request) { | |
host := r.Host | |
log.Println(host + ": " + ReadUserIP(r)) | |
if fn, ok := hostProxy[host]; ok { | |
fn.ServeHTTP(w, r) | |
return | |
} | |
w.Write([]byte("403: Host forbidden " + host)) | |
} | |
} | |
func ReadUserIP(r *http.Request) string { | |
IPAddress := r.Header.Get("X-Real-Ip") | |
if IPAddress == "" { | |
IPAddress = r.Header.Get("X-Forwarded-For") | |
} | |
if IPAddress == "" { | |
IPAddress = r.RemoteAddr | |
} | |
return IPAddress | |
} | |
func main() { | |
var ( | |
hostTarget = map[string]string{ | |
"caue.site": "http://localhost:8080", | |
"home.caue.site": "http://localhost:8081", | |
"torrent.caue.site": "http://localhost:8082", | |
"code.caue.site": "http://localhost:8083", | |
} | |
) | |
http.HandleFunc("/", makeHandler(hostTarget)) | |
log.Fatal(http.ListenAndServe(":80", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment