使用 Mux, Go, PostgreSQL, GORM 构建 API

本文以不到百行代码,演示从表自动创建,mux路由分发,Gorm增删改查,httpie测试API全流程作业。

基本思路

  1. Gorm 通过数据库连接自动在postgres上建表
  2. mux 负责注册Handler,分发,请求相关数据解析
  3. 实现 curd 操作,handler 数据响应json格式,服务监听
  4. httpie 快速测试API接口

第三方包

mux 类似 nodejs 中的 director,小巧简单易用,非常适合 api 开发

  • github.com/gorilla/mux 路由分发包,支持正则,分组,子路由,子域名等
  • github.com/jinzhu/gorm 面向接口编程的go语言orm库
  • github.com/jinzhu/gorm/dialects/postgres psql的gorm驱动版本
  • github.com/lib/pq psql对应的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, Go, PostgreSQL, GORM 构建 API

路由分发

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数据创建

使用 Mux, Go, PostgreSQL, GORM 构建 API

数据库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 协议》,转载必须注明作者和本文链接
pardon110
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
开发者 @ 社科大
文章
134
粉丝
24
喜欢
101
收藏
55
排名:106
访问:8.9 万
私信
所有博文
社区赞助商