使用 Mux, Go, PostgreSQL, GORM 构建 API
本文以不到百行代码,演示从表自动创建,mux路由分发,Gorm增删改查,httpie测试API全流程作业。
基本思路
Gorm通过数据库连接自动在postgres上建表mux负责注册Handler,分发,请求相关数据解析- 实现
curd操作,handler数据响应json格式,服务监听 httpie快速测试API接口
第三方包
mux类似nodejs中的director,小巧简单易用,非常适合api开发
github.com/gorilla/mux路由分发包,支持正则,分组,子路由,子域名等github.com/jinzhu/gorm面向接口编程的go语言orm库github.com/jinzhu/gorm/dialects/postgrespsql的gorm驱动版本github.com/lib/pqpsql对应的go语言数据类型映射库,用于结构体匹配建表
自动建表
homestead环境集成了postgres,其默认的数据库帐号(homestead)密码(secret)
用Gorm定义资源 模型
type Resource struct {
gorm.Model
Link string
Name string
Author string
Description string
Tags pq.StringArray `gorm:"type:varchar(64)[]"`
}
postgres 数据库连接,db.AutoMigrate 自动创建表结构
db, err = gorm.Open(
"postgres",
"host=127.0.0.1 user=homestead dbname=postgres sslmode=disable password=secret",
)
if err != nil {
panic(err)
}
defer db.Close()
db.AutoMigrate(&Resource{})
入库查看表相关信息如下

路由分发
mux 短小精悍,API该有的功能它都具备,除支持路径正则,命名路由外,还支持中间件等
router := mux.NewRouter()
router.HandleFunc("/resources", GetResources).Methods("GET")
router.HandleFunc("/resources/{id}", GetResource).Methods("GET")
router.HandleFunc("/resources", CreateResource).Methods("POST")
router.HandleFunc("/resources/{id}", DeleteResource).Methods("DELETE")
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), router))
实现Handler
用gorm操作数据库实现curd,使用标准库json包响应数据,用mux提取路径参数(iris中术语)
func GetResources(w http.ResponseWriter, r *http.Request) {
var resources []Resource
db.Find(&resources)
json.NewEncoder(w).Encode(&resources)
}
func GetResource(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var resource Resource
db.First(&resource, params["id"])
json.NewEncoder(w).Encode(&resource)
}
func CreateResource(w http.ResponseWriter, r *http.Request) {
var resource Resource
json.NewDecoder(r.Body).Decode(&resource)
db.Create(&resource)
json.NewEncoder(w).Encode(&resource)
}
func DeleteResource(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var resource Resource
db.First(&resource, params["id"])
db.Delete(&resource)
var resources []Resource
db.Find(&resources)
json.NewEncoder(w).Encode(&resources)
}
httpie测试
| HTTP谓词 | 请求路径 | 说明 |
|---|---|---|
POST |
/resources |
创建 |
GET |
/resources/{id} |
查看 |
PUT |
/resources/{id} |
修改 |
GET |
/resources |
查全部 |
DELET |
/resources/{id} |
删除 |
示例新增资源测试,shell开启服务进程,左侧窗口连接postgres查看库记录,右侧用 Hettpie 进行Post数据创建

数据库sql查询输出结果
postgres=# select link,name,author,tags from resources order by id desc limit 1;
link | name | author | tags
------------------+-----------+-----------+--------------------
www.pardon110.cn | pardon110 | pardon110 | {good,"very good"}
源码
完整源码,请参见API构建 https://gitee.com/pardon110/codes/aqrxkfiy...
本作品采用《CC 协议》,转载必须注明作者和本文链接
关于 LearnKu
推荐文章: