如何在子域名上使用nginx和Go?

3

我有一个简单的Go程序,使用http.ListenAndServe来提供内容。 我使用nginx在一个服务器上为多个应用程序提供服务,我也想将其用于Go程序。 我尝试寻找有关此信息的资料,但我发现人们都使用FastCGI或node.js来使其工作。 是否可能仅使用纯Go和nginx来实现它? 我知道如何使用子域使用nginx,但不知道如何使用Go程序。

1个回答

5
您可以通过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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接