在 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
实战案例:
可以将此 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号