LoginSignup
0
0

【Golang】echo + air でシンプルなREST APIをつくる

Posted at

ファイル構成

shell
# モジュール初期化
$ go mod init example.com/hello

# echo
$ go get github.com/labstack/echo/v4  
docker-compose.yml
version: '3'
services:
  app:
    build: .
    ports:
      - '3030:3000'  # ローカルの3030番ポートでコンテナの3000番ポートに接続
    volumes:
      - .:/app       # ローカルとコンテナのディレクトリをマウント(同期)
      - go_path:/go  # パッケージやバイナリファイルのインストール先($GOPATH)を永続化
volumes:
  go_path:
Dockerfile
FROM golang:1.18

# コンテナの作業ディレクトリにローカルのファイルをコピー
WORKDIR /app
COPY . /app

# 必要なパッケージをインストール
RUN go mod tidy

# インストール
RUN go install github.com/cosmtrek/air@v1.27.3
RUN go get -u github.com/go-delve/delve/cmd/dlv 
RUN go get github.com/labstack/echo/v4/middleware

# airコマンドでGoファイルを起動
CMD ["air"]
main.go
package main

import (
	"net/http"
	"github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
)

func rootHandler(c echo.Context) error {
	var records [3]string = [3]string{"1st", "2nd", "3rd"}
	return c.JSON(http.StatusOK, records)
}

func main() {
	// echo
	e := echo.New()
    e.Use(middleware.Recover())
	e.Use(middleware.Logger())

	// ルーティング
	e.GET("/", rootHandler) // ルートアクセスでrootHander実行

	// ポート:3000でサーバー起動
	e.Logger.Fatal(e.Start(":3000"))
}
0
0
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
0
0