Redirect to another directive/label, after reading post body


(Sebastian Faujour) #1

Hey together,
finally i write here because i can’t get my problem solved.

At first i want to say about the needed setup.

I’m using a custom caddy with this Plugin (https://github.com/lucaslorentz/caddy-docker-proxy)
which dynamically writes a caddyfile, with the current running docker swarm services.
In my Setup all services are suffixed with “.caddy-proxy”, so when i have a service named “whoami1”, it generates a directive “whoami1.caddy-proxy”. When i curl it with a Host-Header “whoami1.caddy-proxy” against http://localhost:2015 i get the response of the docker service.

That’s working fine, i have no problems here, now the more difficult part (maybe not but i don’t know how to solve that in the end).

What i want to do:
Dynamically requesting a docker service by reading post body, initially without given Host-Header,
which will be set after reading POST-Body.

e.g. Post Request:

curl -X POST \
http://localhost:2015/ \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
    -d "{
    "object":"page",
    "entry":[
    {
        "id":"whoami0",
        "time":1458692752478,
        "messaging":[]
   }
]
}"

I wrote a plugin which registers a directive “dyn_request” with 2 Parameters, the path that should be checked for a Post-Request and the domain suffix.
That you can follow here the current caddyfile as one:

localhost:2015 {
    dyn_request / caddy-proxy
}

whoami0.caddy-proxy {
    gzip
    proxy / whoami0:8000 {
        transparent
    }
    tls off
}

whoami1.caddy-proxy {
gzip
proxy / whoami1:8000 {
	    transparent
    }
    tls off
}

In my ServeHTTP, i check if it is the correct Path, and if the request method is a POST-Method. If all conditions match, (POST to correct Path with correct JSON-Body) i unmarshal the JSON-Body and get that what i need, the ID out of the first Entry-Object, in this case “whoami0”.

Now my Idea was just Setting the “Host”-Header with r.Header.Set(“Host”, fmt.Sprintf("%s.%s", req.Entries[0].Id, h.Domain)) // h.Domain == caddy-proxy

and then calling Next.ServeHTTP(w, r), but that seems not the correct way.

Also tried with Redirects/Rewrites and so on, maybe one of you can give me a hint how to solve that problem.

Many thanks