Simple Gateway API Proxy

I searched all over the Internet for how to do this, but I could not find it. I am trying to create a simple API gateway using Go and Martini for my system, which has several microservices running REST interfaces. For example, I have a users service running on 192.168.2.8:8000 and I want to access it through /users

So my API gateway will 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() } 


change

Something works for me, 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) } } 


change 2

It just seems like a problem when using it directly through the browser, XMLHttpRequest works just fine

+5
source share
1 answer

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 registers before it is called if you need to keep a log.

+5
source

All Articles