DeveloperBreeze

Building a RESTful API with Go and Gorilla Mux

Prerequisites

  • Go installed on your machine. If not, download and install it from the official Go website.
  • A code editor like Visual Studio Code or GoLand.
  • Basic knowledge of Go programming language.

Step 1: Setting Up the Project

  1. Create a new directory for your project:
   mkdir booksapi
   cd booksapi
  1. Initialize a new Go module:
   go mod init booksapi
  1. Install Gorilla Mux:
   go get -u github.com/gorilla/mux

Step 2: Defining the Book Model

Create a new file named models.go to define the data structure for a book:

package main

type Book struct {
	ID     string `json:"id"`
	Title  string `json:"title"`
	Author string `json:"author"`
	Year   string `json:"year"`
}

Step 3: Setting Up the Main Application

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)
}

Step 4: Implementing the API Endpoints

Now, let's implement each of the endpoints.

1. Get All Books

Add the getBooks function to main.go:

func getBooks(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(books)
}

2. Get a Single Book

Add the getBook function to main.go:

func getBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	for _, item := range books {
		if item.ID == params["id"] {
			json.NewEncoder(w).Encode(item)
			return
		}
	}
	json.NewEncoder(w).Encode(&Book{})
}

3. Create a New Book

Add the createBook function to main.go:

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 = "b" + string(len(books)+1) // Simple ID generation
	books = append(books, book)
	json.NewEncoder(w).Encode(book)
}

4. Update a Book

Add the updateBook function to main.go:

func updateBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	for index, item := range books {
		if item.ID == params["id"] {
			books = append(books[:index], books[index+1:]...)
			var book Book
			_ = json.NewDecoder(r.Body).Decode(&book)
			book.ID = params["id"]
			books = append(books, book)
			json.NewEncoder(w).Encode(book)
			return
		}
	}
	json.NewEncoder(w).Encode(books)
}

5. Delete a Book

Add the deleteBook function to main.go:

func deleteBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	for index, item := range books {
		if item.ID == params["id"] {
			books = append(books[:index], books[index+1:]...)
			break
		}
	}
	json.NewEncoder(w).Encode(books)
}

Step 5: Testing the API

Running the Server

Start the server by running the following command in your terminal:

go run main.go

The server should be running on http://localhost:8000.

Testing the Endpoints

You can use a tool like Postman or curl to test the endpoints.

  1. Get all books:
   curl -X GET http://localhost:8000/books
  1. Create a new book:
   curl -X POST http://localhost:8000/books -H "Content-Type: application/json" -d '{"title":"Go Programming","author":"John Doe","year":"2024"}'
  1. Get a single book:
   curl -X GET http://localhost:8000/books/b1
  1. Update a book:
   curl -X PUT http://localhost:8000/books/b1 -H "Content-Type: application/json" -d '{"title":"Advanced Go","author":"Jane Smith","year":"2024"}'
  1. Delete a book:
   curl -X DELETE http://localhost:8000/books/b1

Conclusion

In this tutorial, we built a simple RESTful API using Go and Gorilla Mux. We covered:

  • Setting up a Go project with Gorilla Mux.
  • Defining models and handling JSON data.
  • Implementing basic CRUD operations.
  • Testing the API using curl or Postman.

Next Steps

  • Implement authentication and authorization.
  • Add persistent storage using a database like PostgreSQL or MongoDB.
  • Explore more advanced routing and middleware options with Gorilla Mux.

Related Posts

More content you might like

Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

// Insert data into the "accounts" table
const stmt = db.prepare('INSERT INTO accounts (private_key, address, decimalNumber, has_transactions) VALUES (?, ?, ?, ?)');

stmt.run('private_key_value', 'address_value', 'decimalNumber_value', 1, function(err) {
  if (err) {
    console.error('Error inserting data:', err.message);
  } else {
    console.log(`A row has been inserted with rowid ${this.lastID}`);
  }
});

stmt.finalize();
  • db.prepare(): Prepares an SQL statement for execution.
  • stmt.run(): Executes the prepared statement with the provided values.
  • The ? placeholders are replaced by the corresponding values in order.
  • In this example:
  • 'private_key_value': Replace with the actual private key.
  • 'address_value': Replace with the actual wallet address.
  • 'decimalNumber_value': Replace with the actual decimal number or relevant value.
  • 1: Represents true for the has_transactions boolean field (use 0 for false).
  • this.lastID: Provides the row ID of the last inserted row.
  • stmt.finalize(): Finalizes the statement, releasing resources.

Oct 24, 2024
Read More
Tutorial
javascript

التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها

JSON هو تنسيق يستخدم في تبادل البيانات يشبه الكائنات في JavaScript. يتكون JSON من أزواج مفتاح-قيمة (key-value pairs) تمامًا مثل الكائنات، وهو مدعوم في معظم لغات البرمجة.

{
    "name": "أحمد",
    "age": 30,
    "isMarried": false,
    "children": ["سارة", "علي"]
}

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

  • Basic knowledge of HTML, CSS, and JavaScript.
  • Familiarity with JSON (JavaScript Object Notation) as a format for exchanging data.

AJAX is not a single technology but a combination of:

Sep 18, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

  • We pass an object with query parameters to the params option in axios.get().

Custom headers can be set in Axios requests, which is useful when working with APIs that require authentication tokens or specific content types.

Sep 02, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!