Simple REST Server to Manage Text Notes in Go

Simple RESTful server in Go for managing text notes with CRUD operations, in-memory storage, JSON responses, and configurable port.

Brief Introduction

Simple REST Server to Manage Text Notes in Go (go)
DESCRIPTION:
A RESTful server written in Go that allows creating, reading, updating, and deleting text notes. It uses the standard net/http package and an in-memory data structure to manage notes.

ADDITIONAL NOTES:
The server keeps notes only in memory, so data is lost on restart. For real use, a database should be integrated. The code is ready to use and easily extendable.

EXPLANATIONS:
- The Note struct represents a single note with ID, Title, and Content.
- The notes map stores all notes in memory, indexed by ID.
- HTTP handlers manage REST requests and respond in JSON.
- The loggingHandler middleware prints each received request to the console.
- The main function configures the router, middleware, and starts the server on the configured port.

Example Code: go

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)
	}
}
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

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

Similar Topics

Word Counter in a Text File with Go
Go program that reads a text file and counts word occurrences case-insensitively with punctuation removal, displaying results alphabetically.
Simple Password Generator in Go (fixed length)
Simple Password Generator in Go creates fixed length random passwords using letters and numbers with no external dependencies for quick secure password creation
Simple Terminal Email Validator in Go
Simple Terminal Email Validator in Go uses regex to check email syntax from terminal input with no external dependencies or complex configuration required.
Simple HTTP File Downloader in Go
Simple HTTP file downloader in Go demonstrating how to download files via HTTP, handle errors, and save data locally using Go standard libraries.
CLI to Launch Simple System Commands in Go
A simple Go CLI tool to execute basic system commands with arguments and display output, ideal for automating terminal tasks using Go standard libraries.
Textual Notes Manager Saved in JSON File in Go
A Go CLI app to manage textual notes with CRUD operations saved in a local JSON file, ensuring data persistence and simple terminal interaction.
Simple Terminal Agenda with CSV Saving in Go
Simple Go CLI terminal agenda app to add, view, and save appointments in CSV with date-time validation and easy file handling.
CLI Tool to Compare Two Text Files (Simplified diff) in Go
A simple Go CLI tool to compare two text files line by line, showing differences with ’+’ and ’-’ prefixes for quick, readable file comparison.