在 golang 中构建 restful api,部署到 docker:创建 golang 项目并定义数据结构。编写 api 处理程序,定义路由并启动 http 服务器。创建 dockerfile,构建 docker 镜像并运行 docker 容器。实战案例:使用 postman 或 curl 测试 api。

如何在 Golang 中构建 RESTful API 并部署到 Docker
go mod init my-api
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
)
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 服务器
fmt.Println("Listening on port 8080")
http.ListenAndServe(":8080", 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) {
// ...
}FROM golang:1.18-alpine WORKDIR /usr/src/app COPY . ./ RUN go build -o my-api CMD ["my-api"]
docker build -t my-api-image .
docker run -p 8080:8080 my-api-image
实战案例:
Android文档-开发者指南-第一部分:入门-中英文对照版 Android提供了丰富的应用程序框架,它允许您在Java语言环境中构建移动设备的创新应用程序和游戏。在左侧导航中列出的文档提供了有关如何使用Android的各种API来构建应用程序的详细信息。第一部分:Introduction(入门) 0、Introduction to Android(引进到Android) 1、Application Fundamentals(应用程序基础) 2、Device Compatibility(设备兼容性) 3、
11
可以将此 API 部署到 Docker 并使用 Postman 或 curl 进行测试。例如,创建一个名为 "test" 的用户:
立即学习“go语言免费学习笔记(深入)”;
curl -X POST http://localhost:8080/users -H "Content-Type: application/json" -d '{"name": "test", "email": "test@example.com", "age": 30}'以上就是如何使用 Golang 构建 RESTful API 并部署到 Docker?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号