Go ile sıfırdan REST API

net/http ile temiz bir API iskeleti, routing ve JSON yanıtları.

Framework şart değil. Standart kütüphane ile okunabilir bir REST API kurabilirsin.

Temel iskelet

go
package main

import (
    "encoding/json"
    "net/http"
    "sync"
)

type Item struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

var (
    mu    sync.Mutex
    items = []Item{{ID: 1, Name: "Go kitabı"}}
    seq   = 2
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/items", func(w http.ResponseWriter, r *http.Request) {
        switch r.Method {
        case http.MethodGet:
            w.Header().Set("Content-Type", "application/json")
            mu.Lock()
            defer mu.Unlock()
            json.NewEncoder(w).Encode(items)
        case http.MethodPost:
            var in Item
            if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
                http.Error(w, "bad json", 400)
                return
            }
            mu.Lock()
            in.ID = seq
            seq++
            items = append(items, in)
            mu.Unlock()
            w.Header().Set("Content-Type", "application/json")
            w.WriteHeader(201)
            json.NewEncoder(w).Encode(in)
        default:
            http.Error(w, "method not allowed", 405)
        }
    })
    http.ListenAndServe(":8080", mux)
}

Sonraki adımlar

  • Go 1.22+ method-aware routing
  • Middleware: request ID, log, recovery
  • Context ile timeout
  • Gerçek veritabanı (database/sql, pgx)

Dene

Önce 21. HTTP dersini bitir, sonra bu API’yi kendi makinenizde çalıştır.

← Tüm blog