Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
package main import ( "encoding/json" "fmt" "log" "net/http" "strconv" ) type User struct { ID int `json:"id"` Name string `json:"name"` } var users = []User{ {1, "Alice"}, {2, "Bob"}, {3, "Carol"}, } func listUsers(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(users) } func getUser(w http.ResponseWriter, r *http.Request) { idStr := r.PathValue("id") // Go 1.22+ id, err := strconv.Atoi(idStr) if err != nil { http.Error(w, "invalid id", http.StatusBadRequest) return } for _, u := range users { if u.ID == id { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(u) return } } http.NotFound(w, r) } func main() { mux := http.NewServeMux() mux.HandleFunc("GET /users", listUsers) mux.HandleFunc("GET /users/{id}", getUser) mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, `{"status":"ok"}`) }) addr := ":8080" log.Printf("listening on %s ", addr) if err := http.ListenAndServe(addr, mux); err != nil { log.Fatal(err) } }
Result
Open