Explain how reverse proxy work

Hi everyone, I’m little lost of using golang reverse proxy.
It would be nice if someone here can explain how it works, if possible in screencast video

I’ve been try to write some code but still no luck

 package main

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

func main() {
        remote, err := url.Parse("http://httpbin.org/")
        if err != nil {
                panic(err)
        }

        proxy := httputil.NewSingleHostReverseProxy(remote)
        http.HandleFunc("/", handler(proxy))
        err = http.ListenAndServe(":8080", nil)
        if err != nil {
                panic(err)
        }
}

func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
        return func(w http.ResponseWriter, r *http.Request) {
                log.Println(r.URL)
                w.Header().Set("X-Ben", "Rad")
                p.ServeHTTP(w, r)
        }
}

when access the path the server show heroku not found page :confused:

Thanks a lot

A simple functional example is here. Pay attention to the readme file to see how it works.

Thanks for replying, is that already tested with https? For example https://httpbin.org ?

Because I’m getting struggle with proxy to https for example httpbin.

No, is just for http.

so is there any good resource how to go with https?

Hey @drafdev,

There are a few answers I’ve found that you can read into to do this if you’d like:


or

But in the meantime, you can get your reverse proxy working with https with as little code as this, but I would actually read those posted answers if I was you :slight_smile:

package main

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

type Transport struct{}

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
	req.Host = req.URL.Host
	return http.DefaultTransport.RoundTrip(req)
}

func main() {
	rp := httputil.NewSingleHostReverseProxy(&url.URL{
		Scheme: "https",
		Host:   "httpbin.org",
	})
	rp.Transport = &Transport{}

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

I have read your posted link before end I’m just getting more confiusing :frowning: but with your code I know that “Host” at

NewSingleHostReverseProxy

is actually the target upstream
and also
I know that I need to learn read answer from stackoverflow carefully :sweat_smile:
thank you very much :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.