Willkommen zu Teil 2 unserer Backend-Engineering für Full-Stack-Entwickler-Reihe! ? Heute befassen wir uns mit einem der grundlegendsten Themen: Erstellen von RESTful-APIs mit Go. Unabhängig davon, ob Sie ein internes Tool oder eine öffentliche API erstellen, ist es wichtig zu verstehen, wie RESTful-Endpunkte strukturiert und implementiert werden.
In diesem Beitrag behandeln wir Folgendes:
Am Ende haben Sie ein solides Verständnis dafür, wie Sie skalierbare RESTful-APIs in Go entwerfen und implementieren. Fangen wir an! ?
Bevor wir uns mit dem Code befassen, schauen wir uns kurz an, was eine API RESTful ausmacht. REST (Representational State Transfer) ist ein Architekturstil zum Erstellen von APIs, der diesen Prinzipien folgt:
Lassen Sie uns eine grundlegende CRUD-API für die Benutzerverwaltung mit Go und dem Gorilla Mux-Router erstellen. Unsere API wird die folgenden Endpunkte haben:
HTTP Method | Endpoint | Action |
---|---|---|
GET | /users | Retrieve all users |
GET | /users/{id} | Retrieve a specific user |
POST | /users | Create a new user |
PUT | /users/{id} | Update an existing user |
DELETE | /users/{id} | Delete a user |
First, install the Gorilla Mux router for routing:
go get -u github.com/gorilla/mux
Create a simple main.go file to get started:
package main import ( "log" "net/http" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() // Define routes here http.Handle("/", r) log.Println("Server started on :8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
Now, let’s define our API handlers. These will correspond to our CRUD actions. We’ll use a simple in-memory map to store user data for this example.
type User struct { ID string `json:"id"` Name string `json:"name"` Age int `json:"age"` } var users = make(map[string]User)
We’ll implement each CRUD operation: Create, Read, Update, and Delete users.
func getUsers(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var userList []User for _, user := range users { userList = append(userList, user) } json.NewEncoder(w).Encode(userList) }
func getUser(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) user, found := users[params["id"]] if !found { http.Error(w, "User not found", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(user) }
func createUser(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var user User _ = json.NewDecoder(r.Body).Decode(&user) users[user.ID] = user w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(user) }
func updateUser(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) user, found := users[params["id"]] if !found { http.Error(w, "User not found", http.StatusNotFound) return } _ = json.NewDecoder(r.Body).Decode(&user) user.ID = params["id"] // Ensure the ID stays the same users[params["id"]] = user w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(user) }
func deleteUser(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) _, found := users[params["id"]] if !found { http.Error(w, "User not found", http.StatusNotFound) return } delete(users, params["id"]) w.WriteHeader(http.StatusNoContent) }
Now that we’ve defined our handlers, let’s add the routes to our router in the main function:
func main() { r := mux.NewRouter() r.HandleFunc("/users", getUsers).Methods("GET") r.HandleFunc("/users/{id}", getUser).Methods("GET") r.HandleFunc("/users", createUser).Methods("POST") r.HandleFunc("/users/{id}", updateUser).Methods("PUT") r.HandleFunc("/users/{id}", deleteUser).Methods("DELETE") http.Handle("/", r) log.Println("Server started on :8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
You can test your API using Postman or curl commands. Here’s how you can create a new user and retrieve users:
curl -X POST http://localhost:8080/users \ -H "Content-Type: application/json" \ -d '{"id":"1", "name":"John Doe", "age":30}'
curl -X GET http://localhost:8080/users
curl -X GET http://localhost:8080/users/1
curl -X PUT http://localhost:8080/users/1 \ -H "Content-Type: application/json" \ -d '{"name":"John Smith", "age":31}'
curl -X DELETE http://localhost:8080/users/1
Now that we’ve built a basic RESTful API, it’s time to integrate database support so we can persist our data. In the next post, we’ll dive into using an ORM to connect our Go API to a database. Stay tuned for Part 3! ?
以上是使用 Go 构建 RESTful API的详细内容。更多信息请关注PHP中文网其他相关文章!