首先用SQL创建一个包含id、name属性的users表
sql
create table users
(
id int auto_increment
primary key,
name varchar(255) null
);
查询所有用户信息:
Go
func queryData(db *sql.DB, w http.ResponseWriter) {
rows, err := db.Query("SELECT * FROM users")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
var users []struct {
ID int `json:"id"`
Name string `json:"name"`
}
for rows.Next() {
var id int
var name string
err := rows.Scan(&id, &name)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
users = append(users, struct {
ID int `json:"id"`
Name string `json:"name"`
}{id, name})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
根据姓名插入一个用户信息
sql
func insertData(db *sql.DB, name string, w http.ResponseWriter) {
stmt, err := db.Prepare("INSERT INTO users(name) VALUES(?)")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer stmt.Close()
res, err := stmt.Exec(name)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
id, _ := res.LastInsertId()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]int64{"id": id})
}
根据id删除一个用户信息
Go
func deleteData(db *sql.DB, id int, w http.ResponseWriter) {
stmt, err := db.Prepare("DELETE FROM users WHERE id=?")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer stmt.Close()
res, err := stmt.Exec(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
affected, _ := res.RowsAffected()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]int64{"deleted": affected})
}
三个方法整合一起放到main.go文件里
Go
package main
import (
"database/sql"
"encoding/json"
"log"
"net/http"
"strconv"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
)
func main() {
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test_go")
if err != nil {
log.Fatal(err)
}
defer db.Close()
r := mux.NewRouter()
r.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
queryData(db, w)
case http.MethodPost:
var user struct{ Name string }
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
insertData(db, user.Name, w)
}
}).Methods("GET", "POST")
r.HandleFunc("/insert", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var user struct{ Name string }
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
insertData(db, user.Name, w)
}).Methods("POST")
r.HandleFunc("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
idStr := vars["id"]
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
deleteData(db, id, w)
}).Methods("DELETE")
log.Println("Server running at http://localhost:8083")
log.Fatal(http.ListenAndServe(":8083", r))
}
func queryData(db *sql.DB, w http.ResponseWriter) {
rows, err := db.Query("SELECT * FROM users")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
var users []struct {
ID int `json:"id"`
Name string `json:"name"`
}
for rows.Next() {
var id int
var name string
err := rows.Scan(&id, &name)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
users = append(users, struct {
ID int `json:"id"`
Name string `json:"name"`
}{id, name})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
func insertData(db *sql.DB, name string, w http.ResponseWriter) {
stmt, err := db.Prepare("INSERT INTO users(name) VALUES(?)")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer stmt.Close()
res, err := stmt.Exec(name)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
id, _ := res.LastInsertId()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]int64{"id": id})
}
func deleteData(db *sql.DB, id int, w http.ResponseWriter) {
stmt, err := db.Prepare("DELETE FROM users WHERE id=?")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer stmt.Close()
res, err := stmt.Exec(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
affected, _ := res.RowsAffected()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]int64{"deleted": affected})
}
- 添加mysql的依赖
bash
go get -u github.com/go-sql-driver/mysql
- 添加gin的依赖
bash
go get -u github.com/gin-gonic/gin
- 添加对gorm的依赖
bash
go get -u gorm.io/gorm
go.mod文件
Go
module go-backend
go 1.24.0
require (
github.com/go-sql-driver/mysql v1.9.2
github.com/gorilla/mux v1.8.1
)
require filippo.io/edwards25519 v1.1.0 // indirect
然后启动
Go
go run main.go

获取用户数据

插入用户数据

删除用户数据
