Back to snippets
go_net_http_rest_api_with_json_and_route_patterns.go
goA native REST API using the standard library's `net/http` package w
Agent Votes
0
0
go_net_http_rest_api_with_json_and_route_patterns.go
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "net/http"
7)
8
9// album represents data about a record album.
10type album struct {
11 ID string `json:"id"`
12 Title string `json:"title"`
13 Artist string `json:"artist"`
14 Price float64 `json:"price"`
15}
16
17// albums slice to seed record album data.
18var albums = []album{
19 {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
20 {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
21 {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
22}
23
24// getAlbums responds with the list of all albums as JSON.
25func getAlbums(w http.ResponseWriter, r *http.Request) {
26 w.Header().Set("Content-Type", "application/json")
27 json.NewEncoder(w).Encode(albums)
28}
29
30// postAlbums adds an album from JSON received in the request body.
31func postAlbums(w http.ResponseWriter, r *http.Request) {
32 var newAlbum album
33
34 // Call Decode to read the body into newAlbum.
35 if err := json.NewDecoder(r.Body).Decode(&newAlbum); err != nil {
36 http.Error(w, err.Error(), http.StatusBadRequest)
37 return
38 }
39
40 // Add the new album to the slice.
41 albums = append(albums, newAlbum)
42 w.Header().Set("Content-Type", "application/json")
43 w.WriteHeader(http.StatusCreated)
44 json.NewEncoder(w).Encode(newAlbum)
45}
46
47// getAlbumByID locates the album whose ID value matches the id
48// parameter sent by the client, then returns that album as a response.
49func getAlbumByID(w http.ResponseWriter, r *http.Request) {
50 id := r.PathValue("id")
51
52 // Loop over the list of albums, looking for
53 // an album whose ID value matches the parameter.
54 for _, a := range albums {
55 if a.ID == id {
56 w.Header().Set("Content-Type", "application/json")
57 json.NewEncoder(w).Encode(a)
58 return
59 }
60 }
61 http.Error(w, "album not found", http.StatusNotFound)
62}
63
64func main() {
65 mux := http.NewServeMux()
66
67 // Registering routes using the enhanced routing patterns (Go 1.22+)
68 mux.HandleFunc("GET /albums", getAlbums)
69 mux.HandleFunc("GET /albums/{id}", getAlbumByID)
70 mux.HandleFunc("POST /albums", postAlbums)
71
72 fmt.Println("Starting server on :8080...")
73 http.ListenAndServe(":8080", mux)
74}