如何将 nginx 与 Go 一起用于子域?

How do I use nginx with Go for a subdomain?

我有一个简单的 go 程序,它使用 http.ListenAndServe 来提供内容。我使用 nginx 在一台服务器上为多个应用程序提供服务,我也想将它用于 go 程序。我曾尝试寻找有关它的信息,但我发现所有人都在使用 FastCGI 或 node.js 来让它工作。是否可以仅使用纯 Go 和 nginx 来做到这一点?我了解如何将 nginx 与子域一起使用,但不了解 Go 程序。

您可以通过proxy_pass直接将Nginx连接到您的Go程序。 给定:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

你只需要在你的 nginx 配置中添加 proxy_pass:

location @go {
    proxy_pass            127.0.0.1:8080;
}