Server REST simplu în Go pentru gestionarea notițelor text cu operații CRUD, folosind net/http și stocare în memorie, ideal pentru prototipuri rapide.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
)
// Note reprezintă o singură notiță text
// cu ID unic, Titlu și Conținut.
type Note struct {
ID int `json:"id"`
Titolo string `json:"titolo"`
Contenuto string `json:"contenuto"`
}
// notes stochează toate notițele în memorie
// protejat de mutex pentru acces concurent.
var (
notes = make(map[int]Note)
mu sync.Mutex
idSeq = 1 // secvență pentru generarea ID-urilor unice
)
// loggingHandler este un middleware care loghează fiecare cerere HTTP.
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 returnează lista tuturor notițelor în 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 returnează o singură notiță după ID.
func getNoteHandler(w http.ResponseWriter, r *http.Request) {
id, err := estraiID(r.URL.Path)
if err != nil {
http.Error(w, "ID invalid", http.StatusBadRequest)
return
}
mu.Lock()
note, ok := notes[id]
mu.Unlock()
if !ok {
http.Error(w, "Notiță negăsită", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(note)
}
// createNoteHandler creează o notiță nouă din JSON trimis în corp.
func createNoteHandler(w http.ResponseWriter, r *http.Request) {
var n Note
err := json.NewDecoder(r.Body).Decode(&n)
if err != nil {
http.Error(w, "JSON invalid", 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 actualizează o notiță existentă după ID.
func updateNoteHandler(w http.ResponseWriter, r *http.Request) {
id, err := estraiID(r.URL.Path)
if err != nil {
http.Error(w, "ID invalid", http.StatusBadRequest)
return
}
var n Note
err = json.NewDecoder(r.Body).Decode(&n)
if err != nil {
http.Error(w, "JSON invalid", http.StatusBadRequest)
return
}
mu.Lock()
_, ok := notes[id]
if !ok {
mu.Unlock()
http.Error(w, "Notiță negăsită", http.StatusNotFound)
return
}
n.ID = id
notes[id] = n
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(n)
}
// deleteNoteHandler șterge o notiță după ID.
func deleteNoteHandler(w http.ResponseWriter, r *http.Request) {
id, err := estraiID(r.URL.Path)
if err != nil {
http.Error(w, "ID invalid", http.StatusBadRequest)
return
}
mu.Lock()
_, ok := notes[id]
if !ok {
mu.Unlock()
http.Error(w, "Notiță negăsită", http.StatusNotFound)
return
}
delete(notes, id)
mu.Unlock()
w.WriteHeader(http.StatusNoContent) // 204 No Content
}
// estraiID extrage ID-ul numeric din URL, așteptând /notes/{id}
func estraiID(path string) (int, error) {
parti := strings.Split(strings.Trim(path, "/"), "/")
if len(parti) < 2 {
return 0, fmt.Errorf("cale invalidă")
}
return strconv.Atoi(parti[1])
}
func main() {
mux := http.NewServeMux()
// Rute REST pentru notițe
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, "Metodă nesuportată", 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, "Metodă nesuportată", http.StatusMethodNotAllowed)
}
})
// Pornire server cu middleware de logging
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("Server pornit pe portul %s", port)
err := http.ListenAndServe(":"+port, loggingHandler(mux))
if err != nil {
log.Fatalf("Eroare la pornirea serverului: %v", err)
}
}Go 1.18+ instalat
Pachetul standard net/http pentru serverul HTTP
Pachetul encoding/json pentru serializarea JSON
Structură de date în memorie (map) pentru stocarea notițelor
Endpoint-uri REST: GET /notes, GET /notes/{id}, POST /notes, PUT /notes/{id}, DELETE /notes/{id}
Middleware simplu pentru logarea cererilor
Configurare: portul serverului configurabil prin variabila de mediu PORT (implicit 8080)
Fără dependențe externe, doar biblioteca standard Go
Nu este necesar Arduino sau hardware extern pentru acest exemplu