Skip to content

Instantly share code, notes, and snippets.

@woodsaj
Created March 23, 2017 18:53
Show Gist options
  • Save woodsaj/674bc0a7688dd40561ff2bf3b19de179 to your computer and use it in GitHub Desktop.
Save woodsaj/674bc0a7688dd40561ff2bf3b19de179 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"io"
"io/ioutil"
"log"
"strings"
"github.com/go-macaron/binding"
"gopkg.in/macaron.v1"
"net/http"
"net/http/httputil"
)
type RenderRequest struct {
Targets []string `json:"target" form:"target"`
MaxDataPoints int `json:"maxDataPoints" form:"maxDataPoints"`
Format string `json:"format" form:"format"`
}
func ProxyHandeler(ctx *macaron.Context, request RenderRequest, body OriginalBody) {
needProxy := false
for _, target := range request.Targets {
// if target is wrapped in a function
if strings.HasSuffix(target, ")") {
needProxy = true
}
}
if !needProxy {
log.Printf("request can be handled locally.")
render(ctx, request)
return
}
log.Printf("request needs to be proxied.")
director := func(req *http.Request) {
req.URL.Scheme = "http"
req.URL.Host = "localhost:4000"
req.URL.Path = "/proxy" + req.URL.Path
req.Body = body.ReadCloser
}
proxy := httputil.ReverseProxy{Director: director}
proxy.ServeHTTP(ctx.Resp, ctx.Req.Request)
}
func render(ctx *macaron.Context, request RenderRequest) {
ctx.JSON(200, request)
}
func logProxy(ctx *macaron.Context, request RenderRequest) {
log.Printf("request being handled by proxy")
return
}
type OriginalBody struct {
ReadCloser io.ReadCloser
}
func captureBody(ctx *macaron.Context) {
buf, _ := ioutil.ReadAll(ctx.Req.Body().ReadCloser())
rdr1 := ioutil.NopCloser(bytes.NewBuffer(buf))
rdr2 := ioutil.NopCloser(bytes.NewBuffer(buf))
ctx.Req.Request.Body = rdr2
ctx.Map(OriginalBody{
ReadCloser: rdr1,
})
}
func main() {
bind := binding.Bind
m := macaron.Classic()
m.Use(macaron.Renderer())
m.Combo("/render", captureBody, bind(RenderRequest{})).Get(ProxyHandeler).Post(ProxyHandeler)
m.Combo("/proxy/render", bind(RenderRequest{}), logProxy).Get(render).Post(render)
m.Run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment