Simple RESTful server in Go for managing text notes with CRUD operations, in-memory storage, JSON responses, and configurable port.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
)
// Note represents a single text note
// with unique ID, Title, and Content.
type Note struct {
ID int `json:"id"`
Titolo string `json:"titolo"`
Contenuto string `json:"contenuto"`
}
// notes stores all notes in memory
// protected by mutex for concurrent access.
var (
notes = make(map[int]Note)
mu sync.Mutex
idSeq = 1 // sequence to generate unique IDs
)
// loggingHandler is a middleware that logs every HTTP request.
func loggingHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
// getNotesHandler returns the list of all notes in JSON.
func getNotesHandler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
var lista []Note
for _, note := range notes {
lista = append(lista, note)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(lista)
}
// getNoteHandler returns a single note given the ID.
func getNoteHandler(w http.ResponseWriter, r *http.Request) {
id, err := estraiID(r.URL.Path)
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
mu.Lock()
note, ok := notes[id]
mu.Unlock()
if !ok {
http.Error(w, "Note not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(note)
}
// createNoteHandler creates a new note from JSON sent in the body.
func createNoteHandler(w http.ResponseWriter, r *http.Request) {
var n Note
err := json.NewDecoder(r.Body).Decode(&n)
if err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
mu.Lock()
n.ID = idSeq
idSeq++
notes[n.ID] = n
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(n)
}
// updateNoteHandler updates an existing note given the ID.
func updateNoteHandler(w http.ResponseWriter, r *http.Request) {
id, err := estraiID(r.URL.Path)
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
var n Note
err = json.NewDecoder(r.Body).Decode(&n)
if err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
mu.Lock()
_, ok := notes[id]
if !ok {
mu.Unlock()
http.Error(w, "Note not found", http.StatusNotFound)
return
}
n.ID = id
notes[id] = n
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(n)
}
// deleteNoteHandler deletes a note given the ID.
func deleteNoteHandler(w http.ResponseWriter, r *http.Request) {
id, err := estraiID(r.URL.Path)
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
mu.Lock()
_, ok := notes[id]
if !ok {
mu.Unlock()
http.Error(w, "Note not found", http.StatusNotFound)
return
}
delete(notes, id)
mu.Unlock()
w.WriteHeader(http.StatusNoContent) // 204 No Content
}
// estraiID extracts the numeric ID from the URL, expecting /notes/{id}
func estraiID(path string) (int, error) {
parti := strings.Split(strings.Trim(path, "/"), "/")
if len(parti) < 2 {
return 0, fmt.Errorf("invalid path")
}
return strconv.Atoi(parti[1])
}
func main() {
mux := http.NewServeMux()
// REST routes for notes
mux.HandleFunc("/notes", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
getNotesHandler(w, r)
case http.MethodPost:
createNoteHandler(w, r)
default:
http.Error(w, "Method not supported", http.StatusMethodNotAllowed)
}
})
mux.HandleFunc("/notes/", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
getNoteHandler(w, r)
case http.MethodPut:
updateNoteHandler(w, r)
case http.MethodDelete:
deleteNoteHandler(w, r)
default:
http.Error(w, "Method not supported", http.StatusMethodNotAllowed)
}
})
// Start server with logging middleware
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("Server started on port %s", port)
err := http.ListenAndServe(":"+port, loggingHandler(mux))
if err != nil {
log.Fatalf("Server start error: %v", err)
}
}Go 1.18+ installed
Standard net/http package for the HTTP server
encoding/json package for JSON serialization
In-memory data structure (map) to store notes
REST endpoints: GET /notes, GET /notes/{id}, POST /notes, PUT /notes/{id}, DELETE /notes/{id}
Simple middleware for request logging
Configuration: server port configurable via PORT environment variable (default 8080)
No external dependencies, only Go standard library
No Arduino or external hardware required for this example