This is the go application that I run
package main
import (
âfmtâ
âgithub.com/openziti/sdk-golang/zitiâ
âgithub.com/openziti/sdk-golang/ziti/configâ
âbytesâ
âencoding/jsonâ
âio/ioutilâ
âlogâ
ânetâ
âtimeâ
ânet/httpâ
ânet/http/httputilâ
ânet/urlâ
âosâ
)
type requestPayloadStruct struct {
ProxyCondition string json:"proxy_condition"
}
/*
Logging
*/
// Log the typeform payload and redirect url
func logRequestPayload(requestionPayload requestPayloadStruct, proxyUrl string) {
log.Printf(âproxy_condition: %s, proxy_url: %s\nâ, requestionPayload.ProxyCondition, proxyUrl)
}
/*
Reverse Proxy Logic
*/
// Serve a reverse proxy for a given url
func serveReverseProxy(target string, res http.ResponseWriter, req *http.Request) {
// parse the url
url, _ := url.Parse(target)
// create the reverse proxy
proxy := httputil.NewSingleHostReverseProxy(url)
// Update the headers to allow for SSL redirection
req.URL.Host = url.Host
req.URL.Scheme = url.Scheme
req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
req.Host = url.Host
// Note that ServeHttp is non blocking and uses a go routine under the hood
proxy.ServeHTTP(res, req)
}
// Get a json decoder for a given requests body
func requestBodyDecoder(request *http.Request) *json.Decoder {
// Read body to buffer
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Printf(âError reading body: %vâ, err)
panic(err)
}
request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
return json.NewDecoder(ioutil.NopCloser(bytes.NewBuffer(body)))
}
// Parse the requests body
func parseRequestBody(request *http.Request) requestPayloadStruct {
decoder := requestBodyDecoder(request)
var requestPayload requestPayloadStruct
err := decoder.Decode(&requestPayload)
if err != nil {
panic(err)
}
return requestPayload
}
// Given a request send it to the appropriate url
func handleRequestAndRedirect(res http.ResponseWriter, req *http.Request) {
requestPayload := parseRequestBody(req)
//url := getProxyUrl(requestPayload.ProxyCondition)
url := "https://www.theage.com.au:443"
logRequestPayload(requestPayload, url)
serveReverseProxy(url, res, req)
}
// setup the ZitiListener
func createZitiListener() net.Listener {
cfg, err := config.NewFromFile(os.Args[1])
if err != nil {
panic(err)
}
options := ziti.ListenOptions{
ConnectTimeout: 5 * time.Minute,
}
listener, err := ziti.NewContextWithConfig(cfg).ListenWithOptions(os.Args[2], &options)
if err != nil {
fmt.Printf(âError binding service %+v\nâ, err)
panic(err)
}
return listener
}
/*
Entry
*/
func main() {
// Log setup values
//logSetup()
// start server
http.HandleFunc("/", handleRequestAndRedirect)
if err := http.Serve(createZitiListener(), nil); err != nil {
panic(err)
}
//if err := http.ListenAndServe(getListenAddress(), nil); err != nil {
// panic(err)
//}
}