title: Golang reverse proxy with multiple apps
body: <p>I want to serve two or more web applications running in a VM (different ports and some time in different directory under the same port) from the host machine and because I need the user to be logged before he can access those apps I can not use a static proxy like Nginx or Apache.</p>
  
  <p>So here is my situation :</p>
  
  <blockquote>
    <p>192.168.1.1 : is the host ip<br>
    192.168.1.2 : is the VM ip</p>
  </blockquote>
  
  <p>Inside the VM I have this :</p>
  
  <blockquote>
    <p>192.168.1.2/owncloud : owncloud address<br>
    192.168.1.2:8080 : an other app<br>
    192.168.1.2:8888 : 3rd app</p>
  </blockquote>
  
  <p>I want to have this :  </p>
  
  <blockquote>
    <p>192.168.1.1/app1 --> 192.168.1.2/owncloud<br>
    192.168.1.1/app2 --> 192.168.1.2:8080<br>
    192.168.1.1/app2 --> 192.168.1.2:8888</p>
  </blockquote>
  
  <p>I have tried to use golang httputil.ReverseProxy to achieve this routing but with no much success:
  my code is based on this work : <a href="https://gist.github.com/JalfResi/6287706" rel="noreferrer">gist</a></p>
  
  <pre><code>package main
  
  import(
      "log"
      "net/url"
      "net/http"
      "net/http/httputil"
  )
  
  func main() {
      remote, err := url.Parse("http://192.168.1.2:8080")
      if err != nil {
              panic(err)
      }
  
      proxy := httputil.NewSingleHostReverseProxy(remote)
      http.HandleFunc("/app2", handler(proxy))
      err = http.ListenAndServe(":80", 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)
          r.URL.Path = "/"                
              p.ServeHTTP(w, r)
      }
  }
  </code></pre>
  
  <p><strong>Edit :</strong><br>
  I have changed the vm ip address: 192.168.1.2 not 192.168.1.1</p>