首頁  >  文章  >  後端開發  >  如何使用 Golang 建置 RESTful API 並部署到 Docker?

如何使用 Golang 建置 RESTful API 並部署到 Docker?

WBOY
WBOY原創
2024-06-01 16:38:02614瀏覽

在 Golang 中建置 RESTful API,部署到 Docker:建立 Golang 專案並定義資料結構。編寫 API 處理程序,定義路由並啟動 HTTP 伺服器。建立 Dockerfile,建置 Docker 映像並執行 Docker 容器。實戰案例:使用 Postman 或 curl 測試 API。

如何使用 Golang 构建 RESTful API 并部署到 Docker?

如何在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