如何使用Go语言将不同域名的请求多路复用到不同的服务器上?

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

How to multiplex requests for different domains to different servers using Go?

问题

我想在同一台机器上托管多个域名,使用不同端口运行多个服务器。我正在尝试编写一个多路复用器,它将把对域名"A"的请求重定向到本地运行在"portA"上的服务器,将对域名"B"的请求重定向到运行在"portB"上的服务器。如何在保持对用户和搜索引擎机器人透明的同时路由这些请求?

目前,我使用类似以下的代码:

package main

import (
	"net/http"
	"log"
)

func main() {
	mux := http.NewServeMux()
	mux.Handle("mydomainA.com", http.RedirectHandler("http://localhost:1234", 302))
    mux.Handle("mydomainB.com", http.RedirectHandler("http://localhost:4567", 302))
	log.Fatal(http.ListenAndServe(":8080", mux))
}
英文:

I want to host multiple domains on the same machine, with multiple servers running on the same machine and different ports. I am trying to write a multiplexer which will redirect requests for domain "A" to the server running locally on "portA", and requests for domain "B" to the server running on "portB". How can I route those requests, while making this redirect transparent to the user and search-engine bots?

Currently, I use something like this:

package main

import (
	"net/http"
	"log"
)

func main() {
	mux := http.NewServeMux()
	mux.Handle("mydomainA.com", http.RedirectHandler("http://localhost:1234", 302))
    mux.Handle("mydomainB.com", http.RedirectHandler("http://localhost:4567", 302))
	log.Fatal(http.ListenAndServe(":8080", mux))
}

答案1

得分: 1

你想要使用 httputil.ReverseProxy 类型,它来自于 net/http/httputil 包。

英文:

(just posting @james-odoherty's comment as an answer since he hasn't)

You want to use the httputil.ReverseProxy type from the net/http/httputil package.

huangapple
  • 本文由 发表于 2014年1月9日 20:11:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/21019890.html
匿名

发表评论

匿名网友

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

确定