GolangでAPIを作成する方法
Go言語でAPIを作成する手順:
- 「go mod init」コマンドを使用して新しい Go モジュールを作成します。例: go mod init example.com/api
- APIのルーティングとハンドラー関数を定義:ゴリラ/muxまたはその他のHTTPルーターライブラリーを使用して、APIのルーティングとハンドラー関数を定義します。例:
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
// 创建一个新的路由
r := mux.NewRouter()
// 定义路由和处理函数
r.HandleFunc("/api/users", getUsers).Methods("GET")
r.HandleFunc("/api/users/{id}", getUser).Methods("GET")
r.HandleFunc("/api/users", createUser).Methods("POST")
r.HandleFunc("/api/users/{id}", updateUser).Methods("PUT")
r.HandleFunc("/api/users/{id}", deleteUser).Methods("DELETE")
// 启动HTTP服务器并监听端口
fmt.Println("Server started on port 8000")
http.ListenAndServe(":8000", r)
}
func getUsers(w http.ResponseWriter, r *http.Request) {
// 处理获取用户列表的请求
}
func getUser(w http.ResponseWriter, r *http.Request) {
// 处理获取单个用户的请求
}
func createUser(w http.ResponseWriter, r *http.Request) {
// 处理创建用户的请求
}
func updateUser(w http.ResponseWriter, r *http.Request) {
// 处理更新用户的请求
}
func deleteUser(w http.ResponseWriter, r *http.Request) {
// 处理删除用户的请求
}
- API処理ロジックの実装:APIの要求に応じて各処理関数のロジックを実装する。
- コマンド「go run」でAPIサーバをコンパイルして実行します。例:go run main.go
現在、あなたは Go言語で基本的なAPIを作成しました。Postman または他のHTTPクライアントを使用して、APIのさまざまなエンドポイントと機能をテストできます。