joplin-notes/joplin notion extension/Web Development/Go/routing.md
2026-11-04 00:33:23 +05:30

234 lines
No EOL
5.9 KiB
Markdown

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/](https://golang.org/dl/).
To verify the installation, run:
```bash
go version
```
You should see the installed Go version.
---
### Step 2: Create a Go Project
1. Create a new directory for your project:
```bash
mkdir go-rest-api
cd go-rest-api
```
2. Initialize a Go module:
```bash
go mod init go-rest-api
```
This creates a `go.mod` file, 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:
```go
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:
```bash
go get -u github.com/gorilla/mux
```
---
### Step 5: Run the API
To run the API, use the following command:
```bash
go run main.go
```
The server will start on `http://localhost:8080`.
---
### Step 6: Test the API
You can use tools like [Postman](https://www.postman.com/) or `curl` to test the API.
#### Endpoints:
1. **GET** `/items` - Get all items.
2. **GET** `/items/{id}` - Get a single item by ID.
3. **POST** `/items` - Create a new item.
4. **PUT** `/items/{id}` - Update an existing item.
5. **DELETE** `/items/{id}` - Delete an item.
#### Example Requests:
- **Get all items:**
```bash
curl http://localhost:8080/items
```
- **Get a single item:**
```bash
curl http://localhost:8080/items/1
```
- **Create a new item:**
```bash
curl -X POST -H "Content-Type: application/json" -d '{"name": "New Item"}' http://localhost:8080/items
```
- **Update an item:**
```bash
curl -X PUT -H "Content-Type: application/json" -d '{"name": "Updated Item"}' http://localhost:8080/items/1
```
- **Delete an item:**
```bash
curl -X DELETE http://localhost:8080/items/1
```
---
### Explanation of the Code
1. **`Item` Struct**: Represents a simple data structure with `ID` and `Name` fields.
2. **`items` Slice**: Acts as an in-memory database to store items.
3. **Routing**: The `gorilla/mux` package is used to define routes and handle HTTP methods.
4. **Handlers**: Functions like `getItems`, `getItem`, `createItem`, `updateItem`, and `deleteItem` handle the logic for each endpoint.
5. **JSON Encoding/Decoding**: The `encoding/json` package is used to convert Go structs to JSON and vice versa.
---
### Step 7: Learn More
- Go Documentation: [https://golang.org/doc/](https://golang.org/doc/)
- Gorilla Mux Documentation: [https://github.com/gorilla/mux](https://github.com/gorilla/mux)
Let me know if you have any questions! 😊