I want to add a new value to the Post Form Before I Redirect it using the ReverseProxy

Viewed 231

I'm writing a ReverseProxy with special requirement using GOLANG The ReverseProxy works just fine. But I have a problem with the special requirement the users send Http Post Form contains user and email I want to add a new value to the Post Form For example url Before I Redirect it using the ReverseProxy

this is my proxy code

package main

import (
    "log"
    "net/http"
    "net/http/httputil"
    "net/url"
)

func main() {
    origin, _ := url.Parse("http://localhost:9000/")

    director := func(req *http.Request) {
        req.Header.Add("X-Forwarded-Host", req.Host)
        req.Header.Add("X-Origin-Host", origin.Host)
        req.URL.Scheme = "http"
        req.URL.Host = origin.Host
    }

    proxy := &httputil.ReverseProxy{Director: director}

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        proxy.ServeHTTP(w, r)
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

I tried R.Form.add and r.PostForm.add and r.Form.set r.PostForm.set It's not working.

1 Answers

You can try this.

func main() {
    origin, _ := url.Parse("http://localhost:9000/")

    director := func(req *http.Request) {
        req.Header.Add("X-Forwarded-Host", req.Host)
        req.Header.Add("X-Origin-Host", origin.Host)
        req.URL.Scheme = "http"
        req.URL.Host = origin.Host
    }

    proxy := &httputil.ReverseProxy{Director: director}

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        r.ParseForm()
        form := r.Form
        form.Add("hello", "world")
        body := form.Encode()
        r.Body = ioutil.NopCloser(strings.NewReader(body))
        r.ContentLength = int64(len(body))
        proxy.ServeHTTP(w, r)
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}
Related