How do I build a REST API with net/http?

This tutorial demonstrates how to build a simple REST API using Go's net/http package. It covers creating HTTP handlers and returning JSON responses.

Go, REST API, net/http, JSON, HTTP handlers

package main

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

// Struct to represent a simple item
type Item struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

// Handler to get item
func getItem(w http.ResponseWriter, r *http.Request) {
    item := Item{ID: "1", Name: "Sample Item"}
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(item)
}

func main() {
    http.HandleFunc("/item", getItem)
    http.ListenAndServe(":8080", nil)
}
    

Go REST API net/http JSON HTTP handlers