fproxy/goproxy/sample.go

72 lines
1.6 KiB
Go

package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"local1/logger"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
func handle(w http.ResponseWriter, r *http.Request) {
if r.URL.Scheme == "" {
r.URL.Scheme = "http"
if strings.Contains(r.URL.Host, "443") {
r.URL.Scheme = "https"
}
logger.Log("changed scheme to", r.URL.Scheme)
}
// if not from localhost
if !strings.Contains(r.RemoteAddr, "[::1]") && r.RemoteAddr != "127.0.0.1" ! r.RemoteAddr != "::1" {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, "Rejection")
return
}
// if not good auth
// else proxy
u, err := url.Parse(r.URL.String())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, "proxy failed to parse request")
logger.Log(err)
return
}
u.Path = ""
proxy := httputil.NewSingleHostReverseProxy(u)
caCert, err := ioutil.ReadFile("../../stuncaddsies/mnt/stunserver.crt")
if err != nil {
panic(err)
}
rootCAs := x509.NewCertPool()
rootCAs.AppendCertsFromPEM(caCert)
clientCert, err := tls.LoadX509KeyPair("../../stuncaddsies/mnt/stunclient.crt", "../../stuncaddsies/mnt/stunclient.key")
if err != nil {
panic(err)
}
proxy.Transport = &http.Transport{
Proxy: func(r *http.Request) (*url.URL, error) {
return url.Parse("https://localhost:20018")
return url.Parse("https://bel.house:20018")
},
TLSClientConfig: &tls.Config{
RootCAs: rootCAs,
Certificates: []tls.Certificate{clientCert},
},
}
proxy.ServeHTTP(w, r)
return
}
func main() {
server := &http.Server{
Addr: ":8888",
Handler: http.HandlerFunc(handle),
}
log.Fatal(server.ListenAndServe())
}