2
4

More than 5 years have passed since last update.

Go言語の環境を作ってみた(GinでHTTPサーバー構築)

Last updated at Posted at 2019-05-20

最近、Go言語の話題をちょこちょこ見かけるので、環境を作ってみました。

環境

  • Windows+VirtualBOX+Vagrant
  • ゲストOS:CentOS7

環境構築

Windows側作業

  • 以下のVagrantfileを作成し、vagrant upを実行
Vagrant.configure("2") do |config|
  config.vm.box = "centos/7"
  config.vm.network "private_network", ip: "192.168.33.20"
end
  • 立ち上がったらvagrant sshでVMにSSH接続

ゲストOS(CentOS)側作業

※Vagrantfileでまとめればよかった。。。

  • yum update
  • sudo yum install git(後述のGinのインストールに必要)
  • Goのインストール(参考
$ curl -OL https://dl.google.com/go/go1.12.5.linux-amd64.tar.gz
$ sudo tar -C /usr/local -xzf go1.12.5.linux-amd64.tar.gz
$ export PATH=$PATH:/usr/local/go/bin
  • Hello Worldしてみる(参考)
$ mkdir hello-world
$ cd hello-world/
$ sudo vi main.go
$ go build
$ ./hello-world
main.go
package main

import "fmt"

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

↓↓↓結果
image.png

HTTPサーバーとして起動してみる

  • Ginのインストール
$ go get -u github.com/gin-gonic/gin 
main.go
package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}
  • 再ビルド
$ go build
$ ./hello-world

↓↓↓サーバー起動
image.png

image.png
→ちゃんとアクセスできてる

↓サーバーサイドのログ
image.png
ログがμ秒単位なのがいかにも処理速度に自信がある感じがして良いですね(笑)

2
4
1

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
2
4