如何使用 Golang 建置 RESTful API 並部署到 Docker?
golang
在 Golang 中建置 RESTful API,部署到 Docker:建立 Golang 專案並定義資料結構。編寫 API 處理程序,定義路由並啟動 HTTP 伺服器。建立 Dockerfile,建置 Docker 映像並執行 Docker 容器。實戰案例:使用 Postman 或 curl 測試 API。
如何在Golang 中建置RESTful API 並部署到Docker
建置RESTful API
建立Golang 項目
go mod init my-api
登入後複製
定義資料結構
type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` Age int `json:"age"` }
登入後複製
編寫API 處理程序
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) { // ... }
登入後複製
部署到Docker
建立Dockerfile
FROM golang:1.18-alpine WORKDIR /usr/src/app COPY . ./ RUN go build -o my-api CMD ["my-api"]
登入後複製
#建置Docker 映像
docker build -t my-api-image .
登入後複製
執行Docker 容器
docker run -p 8080:8080 my-api-image
登入後複製
實戰案例:
#可以將此API 部署到Docker 並使用Postman 或curl 進行測試。例如,建立一個名為 "test" 的使用者:
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中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前
By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
R.E.P.O.保存文件位置:在哪里以及如何保護它?
3 週前
By DDD

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)