【问题标题】:Go simple API Gateway proxyGo 简单的 API 网关代理
【发布时间】:2015-06-11 03:58:44
【问题描述】:

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

【问题讨论】:

  • 使用 martini 的任何理由...您可以使用 net/http 包完成所有操作。
  • 我知道,但它还必须做一些静态文件服务和其他事情,网关只是应用程序的一部分

标签: go proxy martini


【解决方案1】:

标准库版本

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

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 2013-09-24
    • 2021-06-17
    • 1970-01-01
    • 2016-06-15
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多