9

我一直在互联网上搜索如何做到这一点,但我一直无法找到它。我正在尝试使用 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工作得很好

4

1 回答 1

12

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.

于 2015-04-08T01:55:47.683 回答