分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

golang http proxy反向代理

发布时间:2023-09-06 02:30责任编辑:蔡小小关键词:反向代理http

本文介绍golang中如何进行反向代理。

下面例子中,
proxy server接收client 的 http request,转发给true server,并把 true server的返回结果再发送给client。

1.proxy server

proxyServer.go代码如下所示。

// proxyServer.gopackage mainimport ( ???"log" ???"net/http" ???"net/http/httputil" ???"net/url")//将request转发给 http://127.0.0.1:2003func helloHandler(w http.ResponseWriter, r *http.Request) { ???????trueServer := "http://127.0.0.1:2003" ???url, err := url.Parse(trueServer) ???if err != nil { ???????log.Println(err) ???????return ???} ???proxy := httputil.NewSingleHostReverseProxy(url) ???proxy.ServeHTTP(w, r)}func main() { ???http.HandleFunc("/hello", helloHandler) ???log.Fatal(http.ListenAndServe(":2002", nil))}

proxyServer监听端口2002,提供HTTP request "/hello" 的转发服务。

其中,

func NewSingleHostReverseProxy

func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy

NewSingleHostReverseProxy 返回一个新的 ReverseProxy, 将URLs 请求路由到targe的指定的scheme, host, base path 。

如果target的path是"/base" ,client请求的URL是 "/dir", 则target 最后转发的请求就是 /base/dir。

2.true server

trueServer.go代码如下所示。

// trueServer.gopackage mainimport ( ???"io" ???"net/http" ???"log")func helloHandler(w http.ResponseWriter, req *http.Request) { ???????io.WriteString(w, "hello, world!\n")}func main() { ???????http.HandleFunc("/hello", helloHandler) ???????log.Fatal(http.ListenAndServe(":2003", nil))}

trueServer 作为一个HTTP server,监听端口2003,提供"/hello"的实际处理。

3.client

client代码如下

$ curl http://127.0.0.1:2002/hellohello, world!

参考

ReverseProxy

golang http proxy反向代理

原文地址:https://www.cnblogs.com/lanyangsh/p/10293051.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved