Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

shinonomeinc
東京理科大学発ベンチャー。提携大学内にソフトウェア研究所を組織し、学生向けのTech教育を提供しています。
http://shinonome.io
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした