This is simple RESTful API for managing a list of notes. We'll use the gorilla/mux
package to handle routing and create endpoints for creating, retrieving, updating, and deleting notes. And, yes it does work!
- Setting Up Your Project:
Create a new directory for the project and navigate to it:
mkdir note-api
cd note-api
- Initialize Go Module:
Initialize a Go module:
go mod init note-api
- Install Dependencies:
Install the gorilla/mux
package for routing:
go get -u github.com/gorilla/[email protected]
- Create Main Go File:
Create a file named main.go
with the following content:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
)
type Note struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
CreatedAt time.Time `json:"createdAt"`
}
var notes []Note
var currentID int
func createNoteHandler(w http.ResponseWriter, r *http.Request) {
var note Note
if err := json.NewDecoder(r.Body).Decode(¬e); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
note.ID = currentID
note.CreatedAt = time.Now()
notes = append(notes, note)
currentID++
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(note)
}
func getNotesHandler(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(notes)
}
func getNoteByIDHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
noteID, err := strconv.Atoi(vars["id"])
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
for _, note := range notes {
if note.ID == noteID {
json.NewEncoder(w).Encode(note)
return
}
}
http.NotFound(w, r)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/notes", createNoteHandler).Methods("POST")
r.HandleFunc("/notes", getNotesHandler).Methods("GET")
r.HandleFunc("/notes/{id:[0-9]+}", getNoteByIDHandler).Methods("GET")
fmt.Println("Note API listening on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", r))
}
- Build and Run:
Build and run the project:
go build
Now you can use the tool to start the note API:
./note-api
You can interact with the API using tools like curl
, Postman, or any other API client. Here are some example requests:
To create a new note:
curl -X POST -H "Content-Type: application/json" -d '{"title":"My Note","content":"This is my first note."}' http://localhost:8080/notes
To retrieve all notes:
curl http://localhost:8080/notes
To retrieve a note by ID (replace 1
with the actual note ID):
curl http://localhost:8080/notes/1
Please note that this example provides a basic implementation of a note API for educational purposes. In a production environment, you'd need to handle authentication, data persistence (such as using a database), and proper error handling.