下級エンジニアの綴

新しく発見したことを綴っていこうと思っています。夢はでっかく上級エンジニアになることです。

dockerを使ってgoの環境を立ち上げる流れを作ってみたのでそのメモ

お久しぶりです。久々の更新ですみません。 今回はgo作業する時、dockerを使って開発したいなーと思って作成したそのメモになります。

自分は docker fo mac を使用しています。

フォルダ構成

|- docker
|  |- go
|    |- Dockerfile
|- docker-compose.yml
|- main.go
|- templates
  |- chat.html
Dockerfile
ROM golang:latest

RUN apt-get update -qq && apt-get install vim -y

WORKDIR /go
ADD . /go

EXPOSE 8080

CMD ["go", "run", "main.go"]
docker-compose.yml
version: '3'
services:
  app:
    build:
      context: .
      dockerfile: docker/go/Dockerfile
    environment:
      TZ: Asia/Tokyo
    volumes:
      - ./:/go
    ports:
      - "8080:8080"
    tty: true
    stdin_open: true
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)
  }
}
chat.html
<div> test test test </div>

実行結果

↑ファイル構成で docker-compose up -d を実行すると f:id:yanterakun:20180803184852p:plain

こんな感じで表示されます。 今回はただ表示して動かしただけなので、次はホットリロードに対応した構成にしたい。

参考URL

qiita.com