5.9 KiB
routing
from llm
Sure! Let's create a simple REST API in Go (Golang) and I'll explain everything step by step. By the end of this, you'll have a basic understanding of how to create and run a Go REST API.
What is a REST API?
A REST API (Representational State Transfer Application Programming Interface) is a way for two systems to communicate over HTTP. It uses standard HTTP methods like GET, POST, PUT, and DELETE to perform operations on resources (like data).
Step 1: Install Go
Before we start, make sure you have Go installed on your machine. You can download it from the official website: https://golang.org/dl/.
To verify the installation, run:
go version
You should see the installed Go version.
Step 2: Create a Go Project
-
Create a new directory for your project:
mkdir go-rest-api cd go-rest-api -
Initialize a Go module:
go mod init go-rest-apiThis creates a
go.modfile, which manages dependencies.
Step 3: Write the REST API Code
Create a file named main.go in your project directory and add the following code:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
// Item represents a simple data structure
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
}
// In-memory "database" to store items
var items []Item
// Get all items
func getItems(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(items)
}
// Get a single item by ID
func getItem(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r) // Get route parameters
id, _ := strconv.Atoi(params["id"])
// Find the item with the matching ID
for _, item := range items {
if item.ID == id {
json.NewEncoder(w).Encode(item)
return
}
}
// If not found, return a 404
http.NotFound(w, r)
}
// Create a new item
func createItem(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var item Item
_ = json.NewDecoder(r.Body).Decode(&item) // Decode the request body into the item
// Assign a new ID and add to the list
item.ID = len(items) + 1
items = append(items, item)
json.NewEncoder(w).Encode(item)
}
// Update an existing item
func updateItem(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
id, _ := strconv.Atoi(params["id"])
// Find the item and update it
for index, item := range items {
if item.ID == id {
var updatedItem Item
_ = json.NewDecoder(r.Body).Decode(&updatedItem)
updatedItem.ID = id
items[index] = updatedItem
json.NewEncoder(w).Encode(updatedItem)
return
}
}
// If not found, return a 404
http.NotFound(w, r)
}
// Delete an item
func deleteItem(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
id, _ := strconv.Atoi(params["id"])
// Find the item and remove it
for index, item := range items {
if item.ID == id {
items = append(items[:index], items[index+1:]...)
w.WriteHeader(http.StatusNoContent)
return
}
}
// If not found, return a 404
http.NotFound(w, r)
}
func main() {
// Initialize the router
router := mux.NewRouter()
// Add some initial data
items = append(items, Item{ID: 1, Name: "Item 1"})
items = append(items, Item{ID: 2, Name: "Item 2"})
// Define routes
router.HandleFunc("/items", getItems).Methods("GET")
router.HandleFunc("/items/{id}", getItem).Methods("GET")
router.HandleFunc("/items", createItem).Methods("POST")
router.HandleFunc("/items/{id}", updateItem).Methods("PUT")
router.HandleFunc("/items/{id}", deleteItem).Methods("DELETE")
// Start the server
fmt.Println("Server is running on port 8080...")
log.Fatal(http.ListenAndServe(":8080", router))
}
Step 4: Install Dependencies
The code uses the gorilla/mux package for routing. Install it by running:
go get -u github.com/gorilla/mux
Step 5: Run the API
To run the API, use the following command:
go run main.go
The server will start on http://localhost:8080.
Step 6: Test the API
You can use tools like Postman or curl to test the API.
Endpoints:
- GET
/items- Get all items. - GET
/items/{id}- Get a single item by ID. - POST
/items- Create a new item. - PUT
/items/{id}- Update an existing item. - DELETE
/items/{id}- Delete an item.
Example Requests:
-
Get all items:
curl http://localhost:8080/items -
Get a single item:
curl http://localhost:8080/items/1 -
Create a new item:
curl -X POST -H "Content-Type: application/json" -d '{"name": "New Item"}' http://localhost:8080/items -
Update an item:
curl -X PUT -H "Content-Type: application/json" -d '{"name": "Updated Item"}' http://localhost:8080/items/1 -
Delete an item:
curl -X DELETE http://localhost:8080/items/1
Explanation of the Code
ItemStruct: Represents a simple data structure withIDandNamefields.itemsSlice: Acts as an in-memory database to store items.- Routing: The
gorilla/muxpackage is used to define routes and handle HTTP methods. - Handlers: Functions like
getItems,getItem,createItem,updateItem, anddeleteItemhandle the logic for each endpoint. - JSON Encoding/Decoding: The
encoding/jsonpackage is used to convert Go structs to JSON and vice versa.
Step 7: Learn More
- Go Documentation: https://golang.org/doc/
- Gorilla Mux Documentation: https://github.com/gorilla/mux
Let me know if you have any questions! 😊