英文:
HTTP Redirect in Golang
问题
我有这个域名http://mynewurl.com/,它的框架转发到http://oldurl.com:8000,这是我运行博客的Go服务器。
我需要每篇文章的URL正确映射,例如:
目前在主页上访问链接会完全隐藏URL,因此任何分享(希望使用webmentions)都不会引用该文章的URL,而是主URL...
但我想知道是否可以让Golang更好地监听新的URL?
func main() {
http.HandleFunc("/", handlerequest)
http.ListenAndServe(":8000", nil)
}
英文:
I have this domain http://mynewurl.com/, Which frame forwards to -
http://oldurl.com:8000 a Go server I’m running for a blog.
I need to have URLs for each post map correctly aka
As at the moment visiting links on the main page masks the URL totally so any sharing (hopefully using webmentions) will not reference that post URL but the main URL…
But I was wondering if I can get Golang to play better and listen at the new URL?
func main() {
http.HandleFunc("/", handlerequest)
http.ListenAndServe(":8000", nil)
}
答案1
得分: 2
看一下httputil.ReverseProxy
。
我使用它来实现请求转发器,基本上就是你描述的那样 - 监听特定端口并转发到某个URL。
这是示例代码。具体情况可能有所不同,因为我只剥离了与代理实际工作相关的部分,只保留了进行路由的部分。但这可以作为一个起点。
func SetProxy(targetUrl string) (newUrl string, err error) {
var target *url.URL
target, err = url.Parse(targetUrl)
if err != nil {
return "", err
}
origHost := target.Host
origScheme := target.Scheme
d := func(req *http.Request) {
req.URL.Host = origHost
req.URL.Scheme = origScheme
}
p := &httputil.ReverseProxy{Director: d}
http.HandleFunc("/", p)
target.Host = "localhost:8000"
target.Scheme = "http"
newUrl = target.String()
go func() {
err = http.ListenAndServe(":"+localPort, nil)
if err != nil {
panic(err)
}
}()
return newUrl, nil
}
英文:
Look at httputil.ReverseProxy
I used it to implement request dumper that essentially does what you described - listen on specific port and forwards to some url.
This is example code. Mileage can vary as I just stripped out parts related to actual work that I am doing in proxy and left pieces that do routing.
But it could be a starting point.
func SetProxy(targetUrl string) (newUrl string, err error) {
var target *url.URL
target, err = url.Parse(targetUrl)
if err != nil {
return "", err
}
origHost := target.Host
origScheme := target.Scheme
d := func(req *http.Request) {
req.URL.Host = origHost
req.URL.Scheme = origScheme
}
p := &httputil.ReverseProxy{Director: d,}
http.HandleFunc("/", p)
target.Host = "localhost:8000"
target.Scheme = "http"
newUrl = target.String()
go func() {
err = http.ListenAndServe(":"+localPort, nil)
if err != nil {
panic(err)
}
}()
return newUrl, nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论