DeveloperBreeze

Tutorials Programming Tutorials, Guides & Best Practices

Explore 149+ expertly crafted tutorials tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Building a RESTful API with Go and Gorilla Mux

Tutorial August 12, 2024
go

Create a new file named main.go and set up the basic structure of the application:

package main

import (
	"encoding/json"
	"net/http"
	"github.com/gorilla/mux"
)

var books []Book

func main() {
	router := mux.NewRouter()

	// Define routes
	router.HandleFunc("/books", getBooks).Methods("GET")
	router.HandleFunc("/books/{id}", getBook).Methods("GET")
	router.HandleFunc("/books", createBook).Methods("POST")
	router.HandleFunc("/books/{id}", updateBook).Methods("PUT")
	router.HandleFunc("/books/{id}", deleteBook).Methods("DELETE")

	// Start the server
	http.ListenAndServe(":8000", router)
}