概要
Go(Golang)は、静的型付け・コンパイル・ガベージコレクション・goroutineによる並行処理を備えた言語です。単一バイナリ・クロスコンパイル・高速ビルドで配布と運用が容易。
特徴
- シンプルな文法、標準ライブラリが充実
goroutineとchannelによる並行処理- 静的バイナリでデプロイが容易(Dockerと好相性)
- ツールチェーンが標準提供(
go fmt/go test/go vetなど)
よく使う用途
- Web/API サーバ(標準
net/httpや Echo/Fiber 等) - CLI ツール・自動化ユーティリティ
- 分散処理・ネットワークサービス
基本
まずはプロジェクトの初期化と最小APIから。
# プロジェクト作成
mkdir hello && cd hello
go mod init example.com/hello
# 依存追加(例)
go get github.com/gofiber/fiber/v2
# 実行
go run .
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 等のタイムアウト設定や、構造化ログ出力を推奨。基礎
型と構造体
type User struct{
ID int64 `json:"id"`
Name string `json:"name"`
}
func (u User) Greet() string { return "Hi, " + u.Name }
goroutine と channel
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
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
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")
}
発展
コンテキストとタイムアウト
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// 外部APIやDB呼び出しに ctx を渡す
テストとベンチ
func BenchmarkX(b *testing.B){
for i:=0;i<b.N;i++{ /* ... */ }
}
最新情報
2025-08-01
Go 1.23 リリース
2025-07-10
標準ライブラリアップデートまとめ
仕事の現場
運用ベストプラクティス
- 構成: 逆プロキシ(nginx/Caddy)+ アプリ(:8080)
- ヘルスチェック:
/healthz/ readiness / liveness - ロギング: JSON構造化 + ログレベル
- コンフィグ: 環境変数(12factor)
ディレクトリ例
cmd/app/main.go
internal/handler/...
internal/service/...
internal/repo/...
pkg/...
Web開発
標準 net/http
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)例
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
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(最小)
# 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"]