package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
)

type Item struct {
	ID   int    `json:"id"`
	Nama string `json:"nama"`
}

// haloHandler memiliki signature handler: dua parameter w dan r.
func haloHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	fmt.Fprintln(w, "Halo dari handler")
}

func main() {
	mux := http.NewServeMux()

	// Fungsi biasa otomatis menjadi handler lewat mux.HandleFunc.
	mux.HandleFunc("/halo", haloHandler)

	// Handler anonim: atur header, status code, lalu tulis body JSON.
	mux.HandleFunc("/items", func(w http.ResponseWriter, r *http.Request) {
		items := []Item{{ID: 1, Nama: "Buku Go"}, {ID: 2, Nama: "Mouse"}}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(items)
	})

	// Uji handler tanpa membuka port: request tiruan + perekam response.
	uji(mux, http.MethodGet, "/halo")
	uji(mux, http.MethodGet, "/items")
}

func uji(h http.Handler, method, path string) {
	req := httptest.NewRequest(method, path, nil)
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	fmt.Printf("%s %s -> %d (%s)\n", method, path, rec.Code, rec.Header().Get("Content-Type"))
	fmt.Printf("  body: %s", rec.Body.String())
}
