在Golang中进行HTTP重定向

huangapple go评论92阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2015年2月11日 00:18:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/28436506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定