使用golang完成一个http中转服务
下面是一个使用Golang实现的简单HTTP中转服务的示例代码:
package main
import (
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
)
func handler(w http.ResponseWriter, r *http.Request) {
// 将请求转发到目标URL
targetURL, _ := url.Parse("http://example.com")
proxy := httputil.NewSingleHostReverseProxy(targetURL)
proxy.ServeHTTP(w, r)
}
func main() {
// 创建一个HTTP服务器
http.HandleFunc("/", handler)
// 启动服务器并监听端口
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
在上面的示例中,我们创建了一个HTTP中转服务,将所有收到的请求转发到http://example.com。你可以根据自己的需求修改targetURL的值。然后,我们使用http.HandleFunc函数将请求处理函数handler注册到HTTP服务器上。最后,我们使用http.ListenAndServe函数启动服务器并监听端口8080。
当你运行这个程序后,你可以将你的请求发送到http://localhost:8080,然后该服务将会将请求转发到目标URL,并将响应返回给你。
原文地址: https://www.cveoy.top/t/topic/hKBV 著作权归作者所有。请勿转载和采集!