Go - HTTP Server (net/http)

Beginner 10/10 Teacher 10/10 Architect 10/10
Tip: See the capstone Go - Sample REST API for a complete working example using net/http and JSON.

Minimal Server

package main
import (
  "encoding/json"
  "log"
  "net/http"
)

type Health struct{ Status string `json:"status"` }

func main(){
  http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(Health{Status: "ok"})
  })
  log.Println("listening on :8080")
  log.Fatal(http.ListenAndServe(":8080", nil))
}

Routing Options

  • http.ServeMux for simple routing.
  • Third-party routers exist, but stick to stdlib first.

JSON & Headers

Set Content-Type and use json.NewEncoder/Decoder.

Exercises

  1. Add a /time endpoint that returns current time in RFC3339.
  2. Return 404 for unknown routes.