去简单的API网关代理

时间:2015-04-06 17:50:58

标签: go proxy martini

我一直在网上搜索如何做到这一点,但我一直无法找到它。我正在尝试使用Go和Martini为我的系统构建一个简单的API网关,该系统有一些运行REST接口的微服务。例如,我在users上运行了192.168.2.8:8000服务,我想通过/users

访问它

所以我的API网关看起来像这样:

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()
}

<小时/> 的修改


我有一些工作,但我看到的只是[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)
    }
}

<小时/> 编辑2


直接通过浏览器使用时,这似乎只是一个问题,XMLHttpRequest工作得很好

1 个答案:

答案 0 :(得分:6)

stdlib版本

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))
}

如果您需要记录,请在调用之前使用记录功能的http.StripPrefix换行。