nginxでgoを動かす
nginx上でgoを動かしてみたのでその手順をば。
nginxのインストール
今回の環境はローカルのmacで構築しています。
brew install nginx
でnginxを落とします
brewでダウンロードすると、/usr/local/etc/nginx にnginx.confが作成されます。
awsのubuntu環境でapt-getした場合は /etc/nginx/nginx.confでした。(/etc/nginx/が一般的にnginx.confが置かれるディレクトリだと思います)
nginx.confを触ります
http { server { listen 8080; server_name localhost; location / { proxy_pass http://127.0.0.1:9000; } } }
軽く説明すると、そのまんまですが:8080で受けた / へのリクエストを:9000にリダイレクトしてます。 go + nginxでググるとfastcgi_passを使っているのをよく見かけたのですが、シンプルにproxy_passを使えばよいかと思います。
nginx.confを修正したあとは
nginx -t
でnginx.confの記述が正しいかチェック
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
こんな感じで出力されればokです
go
main.go
func main() { mux := http.NewServeMux() mux.HandleFunc("/", handler) s := &http.Server{ Addr: ":9000", Handler: mux, } s.ListenAndServe() } func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World") }
シンプルに:9000にアクセスされればHello Worldを表示します。
動かす
// nginx 起動(:8080) nginx
nginxを打てばnginxが起動します
//go起動 (:9000) go run main.go
これで、localhost:8080にリクエスト投げると、 nginxが9000にリダイレクトしてHello, Worldが出力されます