How do I use nginx with Go for a subdomain?

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

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;
}

huangapple
  • 本文由 发表于 2015年4月20日 01:32:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/29733371.html
匿名

发表评论

匿名网友

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

确定