search
LoginSignup
78
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

Docker上でgolangの開発環境を整える

Docker上で簡単なgoの開発環境を整える

環境

MacOS High Sierra 10.13.1 Beta
docker version 17.09.0-ce
go version 1.8.3

ファイル構造

-app
 |-docker-compose.yml
 |-Dockerfile
 |-main.go
 |-templates
      |
      |-chat.html

docker-composeをセットアップ

docker-compose.yml
version: '3'
services:
  app:
    build: .
    ports:
      - "8080:8080"

Dockerfile

Dockerfile
FROM golang:latest

WORKDIR /go
ADD . /go

CMD ["go", "run", "main.go"]

docker上のGOPATHはデフォルトで/goとなる。

main.goを追加

サンプルアプリケーションを書きます

main.go
package main

import(
  "log"
  "net/http"
  "path/filepath"
  "sync"
  "text/template"
)

type templateHandler struct {
  once sync.Once
  filename string
  templ *template.Template
}

func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  t.once.Do(func() {
    t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
  })
  t.templ.Execute(w, nil)
}

func main() {
  http.Handle("/", &templateHandler{filename: "chat.html"})

  if err := http.ListenAndServe(":8080", nil); err != nil {
    log.Fatal("ListenAndServe", err)
  }
}

これで準備は完了です
実際に動かしてみてください

$ docker-compose up
$ docker-compose up
WARNING: The Docker Engine you're using is running in swarm mode.

Compose does not use swarm mode to deploy services to multiple nodes in a swarm. All containers will be scheduled
on the current node.

To deploy your application across the swarm, use `docker stack deploy`.

Starting goapp_app_1 ...
Starting goapp_app_1 ... done
Attaching to goapp_app_1

こうなったら成功です

localhost:8080

に接続してchat.htmlの内容が表示されたらOK

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
What you can do with signing up
78
Help us understand the problem. What are the problem?