英文:
How do I use nginx with Go for a subdomain?
问题
我有一个简单的Go程序,使用http.ListenAndServe来提供内容。我使用nginx在一个服务器上提供多个应用程序,并且我也想将其用于Go程序。我尝试查找相关信息,但我发现大多数人都使用FastCGI或node.js来使其工作。是否可能只使用纯Go和nginx来实现?我知道如何在子域名中使用nginx,但不知道如何在Go程序中使用。
英文:
I have a simple go program that uses http.ListenAndServe to serve content. I use nginx to serve multiple applications on one server, and I want to use it for the go program too. I've tried looking for information on it, but all I found people using FastCGI or node.js to get it to work. Is it possible to do it with just pure Go and nginx? I understand how to use nginx with a subdomain, but not a Go program.
答案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;
}
英文:
You can connect Nginx to your Go program directly via proxy_pass.
Given:
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)
}
You just need to add to your nginx configuration the proxy_pass:
location @go {
proxy_pass 127.0.0.1:8080;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论