Go
Go開発
シンプル・高速・並行処理に強いモダン言語

概要

Go(Golang)は、静的型付けコンパイルガベージコレクションgoroutineによる並行処理を備えた言語です。単一バイナリ・クロスコンパイル・高速ビルドで配布と運用が容易

特徴

  • シンプルな文法、標準ライブラリが充実
  • goroutinechannel による並行処理
  • 静的バイナリでデプロイが容易(Dockerと好相性)
  • ツールチェーンが標準提供(go fmt / go test / go vet など)

よく使う用途

  • Web/API サーバ(標準 net/http や Echo/Fiber 等)
  • CLI ツール・自動化ユーティリティ
  • 分散処理・ネットワークサービス

基本

まずはプロジェクトの初期化と最小APIから。

Shell
# プロジェクト作成
mkdir hello && cd hello
go mod init example.com/hello

# 依存追加(例)
go get github.com/gofiber/fiber/v2

# 実行
go run .
main.go
package main

import (
  "fmt"
  "log"
  "net/http"
)

func main() {
  mux := http.NewServeMux()
  mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, Go!")
  })
  log.Println("listening on :8080")
  if err := http.ListenAndServe(":8080", mux); err != nil {
    log.Fatal(err)
  }
}
Tips: 実運用では ReadHeaderTimeout 等のタイムアウト設定や、構造化ログ出力を推奨。

基礎

型と構造体

Go
type User struct{ ID int64 `json:"id"` Name string `json:"name"` } func (u User) Greet() string { return "Hi, " + u.Name }

goroutine と channel

Go
func worker(id int, ch chan<- string){ ch <- fmt.Sprintf("done:%d", id) } func main(){ ch := make(chan string, 2) go worker(1, ch); go worker(2, ch) fmt.Println(<-ch, <-ch) }

応用

EchoでREST

Go (Echo)
import "github.com/labstack/echo/v4" type Todo struct{ ID int `json:"id"`; Title string `json:"title"` } func main(){ e := echo.New() e.GET("/todos/:id", func(c echo.Context) error{ id := c.Param("id") return c.JSON(200, map[string]string{"id": id, "title":"buy milk"}) }) e.Logger.Fatal(e.Start(":8080")) }

FiberでREST

Go (Fiber)
import "github.com/gofiber/fiber/v2" func main(){ app := fiber.New() app.Get("/health", func(c *fiber.Ctx) error { return c.JSON(fiber.Map{"status":"ok"}) }) app.Listen(":8080") }

発展

コンテキストとタイムアウト

Go
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() // 外部APIやDB呼び出しに ctx を渡す

テストとベンチ

Go test
func BenchmarkX(b *testing.B){ for i:=0;i<b.N;i++{ /* ... */ } }

最新情報

仕事の現場

運用ベストプラクティス

  • 構成: 逆プロキシ(nginx/Caddy)+ アプリ(:8080)
  • ヘルスチェック: /healthz / readiness / liveness
  • ロギング: JSON構造化 + ログレベル
  • コンフィグ: 環境変数(12factor)

ディレクトリ例

構成例
cmd/app/main.go internal/handler/... internal/service/... internal/repo/... pkg/...

Web開発

標準 net/http

Go
mux := http.NewServeMux() mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request){ json.NewEncoder(w).Encode(map[string]string{"message":"hello"}) })

ミドルウェア

  • リクエストID / 追跡ID
  • リカバリ / Panic保護
  • Auth / CORS / Rate Limit

アプリ開発

CLI(cobra)例

Go
import "github.com/spf13/cobra" var rootCmd = &cobra.Command{Use:"tool"} func main(){ rootCmd.Execute() }

知っておくといい

知識・技能

  • コンテキスト設計 / タイムアウト
  • エラーハンドリング指針(wrap/unwrap)
  • プロファイリング(pprof)/ レースディテクタ

用語

goroutine
軽量スレッドのような並行実行単位
channel
goroutine間の通信機構
module
Goの依存管理単位(go.mod)

シンプルJSON API

Go
type Resp struct{ Message string `json:"message"` } func hello(w http.ResponseWriter, r *http.Request){ w.Header().Set("Content-Type","application/json") json.NewEncoder(w).Encode(Resp{Message:"ok"}) }

より具体的に

Dockerfile(最小)

Dockerfile
# syntax=docker/dockerfile:1 FROM golang:1.23 AS build WORKDIR /src COPY . . RUN --mount=type=cache,target=/go/pkg/mod \ --mount=type=cache,target=/root/.cache/go-build \ CGO_ENABLED=0 go build -o /app FROM gcr.io/distroless/base-debian12 COPY --from=build /app /app EXPOSE 8080 USER nonroot:nonroot ENTRYPOINT ["/app"]