N
N
NubasLol2021-04-14 19:06:01
go
NubasLol, 2021-04-14 19:06:01

Is it possible to implement an analogue of proxy_pass nginx in golang?

Nginx is very cool at proxying requests and downloading files, but the problem is to authorize these requests and change urls dynamically.

But it’s enough to write

location /start {
            proxy_pass http://kinosotik.com/download/malenqkie-chudoviwa?original;
        }


And nginx will download a file from a remote site immediately after clicking on the link, it supports resume, etc.

Trying to write something similar in golang, but it gives a 404 error

func main() {
   http.HandleFunc("/", handlerProxy)
   if err := http.ListenAndServe(":4000", nil); err != nil {
       panic(err)
   }
}

func handlerProxy(w http.ResponseWriter, r *http.Request) {
   fmt.Println(r.URL.Host)

   url, _ := url.Parse(fmt.Sprintf("http://kinosotik.com/download/malenqkie-chudoviwa?original"))

    r.Host = url.Host
    r.URL.Scheme = "http"

   proxy := httputil.NewSingleHostReverseProxy(url)
   fmt.Println(r.URL.Host)

   proxy.ServeHTTP(w, r)
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2021-04-15
@NubasLol

to have no buffer, you need this piece

body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        http.Error(w, "error reading response body", http.StatusInternalServerError)
        return
    }

    // write status code and body from proxy request into the answer
    w.WriteHeader(resp.StatusCode)
    w.Write(body)

replace with this one:
w.WriteHeader(resp.StatusCode)
_, err := io.Copy(w, body)
if err != nil {
    http.Error(w, "error reading response body", http.StatusInternalServerError)
    return
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question