LoginSignup
12
11

More than 5 years have passed since last update.

はじめてのGo言語 - インストール〜nginx導入まで -  

Last updated at Posted at 2016-01-16

Go言語が気になって気になってしようがないので、触ってみました。
最終的には、会社のHPをGoで実装したいと思います。(問い合わせ機能とかあるんで)
まずは、導入編です。

Goのインストール

インストール

簡単にインストールできます。(今回はLinuxにインストールしました。)

cd /usr/local/src
wget https://storage.googleapis.com/golang/go1.5.2.linux-amd64.tar.gz

※バージョンは2016/01/11現在の最新版です。

解凍しますっ

tar -C /usr/local -xzf go1.5.2.linux-amd64.tar.gz

パスを通す

export PATH=$PATH:/usr/local/go/bin

テストコード

hello.go
package main

import "fmt"

func main() {
    fmt.Printf("hello, world\n")
}

実行してみる

go run hello.go

ひとまずGoが動きました。

nginxをインストール

Goはパッケージが豊富なので、net/httpというパッケージで簡単にhttpサーバーの利用が開始できるそうなんですが、サービスレベルまで作りこむときにはきっとnginxの方がいいのかなーと思い・・・。

リポジトリファイル作成します。

touch /etc/yum.repos.d/nginx.repo
vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

インストールします。

yum install nginx

設定ファイルの書き換え。

 cd /etc/nginx/conf.d/*.conf
 vi xxxx.conf → 新しくファイルを作って下さい。(default.confがあるのでコピーしてもOK)
xxxx.conf
server {
    listen       80;
    server_name  example.com;

    location / {
        fastcgi_pass  127.0.0.1:9000;
        include       fastcgi_params;
    }
}

設定のチェックと反映

/etc/init.d/nginx configtest
/etc/init.d/nginx reload

index.goを作成する

index.go
package main

import (
    "fmt"
    "net"
    "net/http"
    "net/http/fcgi"
)

func handler(res http.ResponseWriter, req *http.Request) {
    fmt.Fprint(res, "Hello World!")
}

func main() {
    l, err := net.Listen("tcp", "127.0.0.1:9000") // TCP 9000 番ポートで Listen
    if err != nil {
        return
    }
    http.HandleFunc("/", handler)
    fcgi.Serve(l, nil)
}

実行します。

go run index.go

ブラウザからURLを叩いてみます。

スクリーンショット 2016-01-16 20.59.32.png
と表示されました。

テンプレートを別けてみる

index.go
package main

import (
    "net"
    // ↓追加
    "html/template"
    "net/http"
    "net/http/fcgi"
)

func handler(res http.ResponseWriter, req *http.Request) {
    // ここを書き換えます。
    // 同階層に置いたindex.htmlを読み込めます。
    t, _ := template.ParseFiles("index.html")
    t.Execute(res, nil)
}

func main() {
    l, err := net.Listen("tcp", "127.0.0.1:9000") // TCP 9000 番ポートで Listen
    if err != nil {
        return
    }

    http.HandleFunc("/", handler)
    fcgi.Serve(l, nil)
}

現時点の問題

  • css,js,imageなど静的ファイルの読み込みのやり方がわからない。
  • Go言語の基礎をまだ把握していない。\(^o^)/

MVCを自分で実装したいのですが、まだ慣れていないので
次回は、フレームワークを使ってみたいと思います。
あと、Goの基礎も。

12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11