Creating a RESTful API in Go involves designing routes and handlers that adhere to the principles of Representational State Transfer (REST). In this tutorial, I'll guide you through creating a simple RESTful API using the built-in 'net/http' package.
Defining the API Routes:
We'll create a basic CRUD (Create, Read, Update, Delete) API for managing a list of books.
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
type Book struct {
ID int `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
}
var books []Book
var nextID int
func main() {
r := mux.NewRouter()
r.HandleFunc("/books", getBooks).Methods("GET")
r.HandleFunc("/books/{id:[0-9]+}", getBook).Methods("GET")
r.HandleFunc("/books", createBook).Methods("POST")
r.HandleFunc("/books/{id:[0-9]+}", updateBook).Methods("PUT")
r.HandleFunc("/books/{id:[0-9]+}", deleteBook).Methods("DELETE")
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
// Handlers...
In this example, we've set up routes for listing all books, getting a single book, creating a book, updating a book, and deleting a book. We use the "github.com/gorilla/mux" package for advanced routing.
Handler Functions:
Now let's implement the actual handler functions for each route.
func getBooks(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(books)
}
func getBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
id, _ := strconv.Atoi(params["id"])
for _, book := range books {
if book.ID == id {
json.NewEncoder(w).Encode(book)
return
}
}
http.NotFound(w, r)
}
func createBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var book Book
_ = json.NewDecoder(r.Body).Decode(&book)
book.ID = nextID
nextID++
books = append(books, book)
json.NewEncoder(w).Encode(book)
}
func updateBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
id, _ := strconv.Atoi(params["id"])
var updatedBook Book
_ = json.NewDecoder(r.Body).Decode(&updatedBook)
for i, book := range books {
if book.ID == id {
books[i] = updatedBook
json.NewEncoder(w).Encode(updatedBook)
return
}
}
http.NotFound(w, r)
}
func deleteBook(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id, _ := strconv.Atoi(params["id"])
for i, book := range books {
if book.ID == id {
books = append(books[:i], books[i+1:]...)
w.WriteHeader(http.StatusNoContent)
return
}
}
http.NotFound(w, r)
}
In the handlers, we're interacting with a slice called 'books' that holds book data. The functions follow RESTful conventions for handling requests and generating appropriate responses.
Testing the API:
You can test the API using tools like 'curl'or Postman. For example:
To get all books: 'GET http://localhost:8080/books'
To get a specific book: 'GET http://localhost:8080/books/1'
To create a book: 'POST http://localhost:8080/books' with JSON payload
To update a book: 'PUT http://localhost:8080/books/1' with JSON payload
To delete a book: 'DELETE http://localhost:8080/books/1'
Summary:
Creating a RESTful API in Go involves defining routes and handlers.
The "github.com/gorilla/mux" package enhances routing capabilities.
Handlers implement CRUD operations according to REST principles.
JSON encoding/decoding is used to handle data.
RESTful APIs allow you to create backend services that can be consumed by various clients.
Building a RESTful API in Go enables you to create robust and scalable backend services that interact with frontend applications, mobile apps, and more. Remember to handle errors, validation, and authentication to create a production-ready API.