nginx下Go如何配置成fastCGI工作模式

最初是因为笔者的服务器上已经有了nginx + php(fastcgi)的项目,所以在引入Go的项目时,自然的就想到了通过nginx的虚拟主机+fastCGI的方式支持Go的项目。其实很简单,以下就是简单的示例,照此方法就可以让Go以FastCGI的方式Hello word了 !

1. Nginx 需要做的配置

server { 
  listen 80; 
  server_name  www.xxxxxxx.xxx; #这里可以配置域名,如果需要支持多个网站的话 #如果需要可以配置访问日志 
  #access_log  /var/log/nginx/log/host.access.log  main; 
  #以下是对静态资源访问的配置, 例如 css img 神马的 
  location ~ ^/css|img|js|tpl/ { 
    root   /data/www/xxxxx/; #expires 4d; #如果需要也可以配置缓存过期时间 
  }
  location / { 
    root   /data/www/xxxxxx/;
    index  index.html index.htm;
    fastcgi_pass   127.0.0.1:9001; #需要分配一个端口号给go-fastcgi 
    fastcgi_index  index; #这是Go的入口
    client_max_body_size    10m;
  }

  error_page   500 502 503 504  /50x.html;
  location = /50x.html { 
    root   /usr/share/nginx/html; 
  } 
}

2. Go fastCGI 代码示例

package main import ( 
  "fmt" 
  "net" 
  "net/http"
  "net/http/fcgi"
  "log"
)

type Hello struct{} func Handler ( 
  w http.ResponseWriter, r *http.Request
) {
  fmt.Fprint(w, "Hello!")
} 

func main() {
  l, err := net.Listen("tcp", ":9001") //这里是fastCGI监听的端口号 
  if err != nil { 
    panic(err) 
  } 
  serveMux := http.NewServeMux() 
  serveMux.HandleFunc("/", Handler) 
  err = fcgi.Serve(l, serveMux)
  if err != nil { 
    log.Println("fcgi error", err) 
  }
}