Build a RESTful API in Golang and deploy to Docker: Create a Golang project and define the data structure. Write API handlers, define routes and start HTTP servers. Create a Dockerfile, build a Docker image and run a Docker container. Practical case: testing API using Postman or curl.
How to build a RESTful API in Golang and deploy to 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
Practical case:
You can deploy this API to Docker and use Postman or curl for testing. For example, create a user named "test":
curl -X POST http://localhost:8080/users -H "Content-Type: application/json" -d '{"name": "test", "email": "test@example.com", "age": 30}'
The above is the detailed content of How to build a RESTful API using Golang and deploy to Docker?. For more information, please follow other related articles on the PHP Chinese website!