Golang如何实现简单的API网关


当前第2页 返回上一页

NewSingleHostReverseProxy中源码已经对传入的URLs进行解析并且完成了Director的修改,我们只需要调用NewSingleHostReverseProxy函数并且传入目标服务器的URL即可,一个简单的反向代理就完成了啦。

代码

实例代码只涉及微服务中 userauth模块,可以根据实际需求自行修改部分

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

package mainimport (

    "fmt"

    "log"

    "net/http"

    "net/http/httputil"

    "net/url"

    "strings")type handle struct {

    host string

    port string}type Service struct {

    auth *handle

    user *handle}func (this *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    var remote *url.URL if strings.Contains(r.RequestURI, "api/auth") {

        remote, _ = url.Parse("http://" + this.auth.host + ":" + this.auth.port)

    } else if strings.Contains(r.RequestURI, "api/user") {

        remote, _ = url.Parse("http://" + this.user.host + ":" + this.user.port)

    } else {

        fmt.Fprintf(w, "404 Not Found")

        return

    }

    proxy := httputil.NewSingleHostReverseProxy(remote)

    proxy.ServeHTTP(w, r)}func startServer() {

    // 注册被代理的服务器 (host, port)

    service := &Service{

        auth: &handle{host: "127.0.0.1", port: "8081"},

        user: &handle{host: "127.0.0.1", port: "8082"},

    }

    err := http.ListenAndServe(":8888", service)

    if err != nil {

        log.Fatalln("ListenAndServe: ", err)

    }}func main() {

    startServer()}

以上就是Golang如何实现简单的API网关的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

手撸golang go与微服务 net.rpc

golang elasticsearch7的使用

golang中如何比较字符串是否相等

反射三定律

golang令牌桶实现 [go-rate] 速率限制器

go基础及语法(二)

golang

go基础及语法(一)

golang基础-内置数据结构

go struct,interface能否比较(tx面试题)

更多相关阅读请进入《golang》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...