http - 在一个 IP 上托管多个 Golang 站点并根据域请求提供服务?

标签 http nginx go port

我正在运行一个安装了 Ubuntu 的 VPS。如何在不指定端口(xxx.xxx.xxx.xxx:8084)的情况下使用同一个VPS(同一个IP)服务多个Golang网站?

例如,Golang 应用程序 1 正在监听端口 8084Golang 应用程序 2 正在监听端口 8060。我希望当有人从域 example1.com 请求时提供 Golang 应用程序 1,当有人从域 example2.com 请求时提供 Golang 应用程序 2。

我相信你可以用 Nginx 做到这一点,但我一直无法弄清楚如何。

最佳答案

Nginx 免费解决方案。

首先你可以重定向connections on port 80 as a normal user

sudo apt-get install iptables-persistent
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000
sudo netfilter-persistent save
sudo netfilter-persistent reload

然后使用gorilla/mux或类似地为每个主机创建一个路由,甚至从中获得一个“子路由器”

r := mux.NewRouter()
s := r.Host("www.example.com").Subrouter()

所以完整的解决方案是

package main

import (
    "net/http"
    "github.com/gorilla/mux"
    "fmt"
)

func Example1IndexHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello www.example1.com!") // send data to client side
}

func Example2IndexHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello www.example2.com!") // send data to client side
}

func main() {
    r := mux.NewRouter()
    s1 := r.Host("www.example1.com").Subrouter()
    s2 := r.Host("www.example2.com").Subrouter()

    s1.HandleFunc("/", Example1IndexHandler)
    s2.HandleFunc("/", Example2IndexHandler)

    http.ListenAndServe(":8000", nil)
}

关于http - 在一个 IP 上托管多个 Golang 站点并根据域请求提供服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39894171/

相关文章:

go - 在 Go 中读取 cookie

http - 404 错误 header 的描述文本 - 更改 'Not Found'

linux - Nginx url重写错误: [emerg] unexpected "}"

node.js - Nginx + Node JS + Express JS 产生 502 错误

nginx - 在单个主机中高效使用多个 docker 容器

go - 如何在 Go 中对字节进行 SHA1 RSA 签名?

Go 对 ARM 寄存器 R10 和 R11 的限制

用于访问损坏/无效资源的 REST 响应代码

java - 将 AsyncTasks 的结果放在一起

wget 中的 HTTP 500 错误