Go simple API Gateway proxy

Dirk picture Dirk · Apr 6, 2015 · Viewed 8.5k times · Source

I've been searching all over the internet how to do this, but I haven't been able to find it. I'm trying to build a simple API gateway using Go and Martini for my system that has a few microservices with REST interfaces running. For example, I have my users service running on 192.168.2.8:8000, and I want to access it through /users

So my API gateway would look something like this:

package main

import (
    "github.com/codegangsta/martini"
    "net/http"
)

func main(){
    app := martini.Classic()
    app.Get("/users/:resource", func(req *http.Request, res http.ResponseWriter){
        //proxy to http://192.168.2.8:8000/:resource
    })
    app.Run()
}


edit


I've got something working, but all i see is [vhost v2] release 2.2.5:

package main

import(
    "net/url"
    "net/http"
    "net/http/httputil"
    "github.com/codegangsta/martini"
    "fmt"
)

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

    proxy := httputil.NewSingleHostReverseProxy(remote)
    app := martini.Classic()
    app.Get("/users/**", handler(proxy))
    app.RunOnAddr(":4000")
}

func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request, martini.Params) {
    return func(w http.ResponseWriter, r *http.Request, params martini.Params) {
        fmt.Println(params)
        r.URL.Path = "/authorize"
        p.ServeHTTP(w, r)
    }
}


edit 2


This only seems to be a problem when using it directly through the browser, XMLHttpRequest works just fine

Answer

freeformz picture freeformz · Apr 8, 2015

stdlib version

package main

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

func main() {
    target, err := url.Parse("http://192.168.2.8:8000")
    if err != nil {
        log.Fatal(err)
    }
    http.Handle("/users/", http.StripPrefix("/users/", httputil.NewSingleHostReverseProxy(target)))
    http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./Documents"))))
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Wrap http.StripPrefix with a function that logs before calling it if you need logging.