
{{ $('Map tags to IDs').item.json.title }}
Building a REST API in Go
Building a REST API in Go is straightforward and efficient. Go’s powerful standard library makes it easy to create web servers and handle HTTP requests. This tutorial will walk you through the steps to set up a REST API using Go.
Prerequisites
- Go language installed on your machine.
- Basic understanding of Go programming.
- Familiarity with REST principles.
1. Setting Up Your Go Project
Create a new directory for your project:
mkdir my-go-api
cd my-go-api
Initialize a new Go module:
go mod init my-go-api
2. Creating the Main Application File
Create a file named main.go
:
touch main.go
Open main.go
in a text editor and add the following code:
package main
import (
"encoding/json"
"net/http"
)
var items []string
func getItems(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(items)
}
func createItem(w http.ResponseWriter, r *http.Request) {
var item string
json.NewDecoder(r.Body).Decode(&item)
items = append(items, item)
w.WriteHeader(http.StatusCreated)
}
func main() {
http.HandleFunc("/items", getItems)
http.HandleFunc("/items/create", createItem)
http.ListenAndServe(":8080", nil)
}
This code sets up basic routes for getting and creating items in your API.
3. Running Your API
To run your application, execute the following command in the terminal:
go run main.go
Your API will start running on http://localhost:8080
.
4. Testing Your API
You can test your API using tools like Postman or curl.
4.1. Testing GET Request
To retrieve the list of items, open a new terminal and run:
curl http://localhost:8080/items
4.2. Testing POST Request
To add a new item, use:
curl -X POST -H "Content-Type: application/json" -d '"New Item"' http://localhost:8080/items/create
Replace "New Item"
with your desired item name.
5. Conclusion
You have successfully built a simple REST API using Go! With this basic setup, you can expand your API to include more features, such as updating or deleting items and integrating a database for persistent storage. Explore the extensive capabilities of Go for developing robust web applications.