go-sql-rest-driver 是一个简单的rest 包装,我们可以使用sql driver 的模式查询rest api
(注意此驱动很简单,没有实现类似sql 的复杂处理,功能很弱,而且代码也很少)
项目准备
- go rest server
package main
?
import "net/http"
?
func main() {
?
http.HandleFunc("/query/v1", func(res http.ResponseWriter, req *http.Request) {
var userinfo = `{"name":"dalong","age":333}`
res.Header().Add("Content-Type", "application/json")
res.Write([]byte(userinfo))
})
http.ListenAndServe(":8090", nil)
}
- 使用go-sql-rest-driver
go.mod
module demoapp
?
go 1.15
?
require github.com/adaptant-labs/go-sql-rest-driver v0.0.0-20190106101033-ca81a23dec0c
使用代码
package main
?
import (
"database/sql"
"log"
?
_ "github.com/adaptant-labs/go-sql-rest-driver"
)
?
func main() {
db, err := sql.Open("restsql", "http://localhost:8090/query/v1")
if err != nil {
log.Fatalln("some wrong:", err.Error())
}
rows, err := db.Query("")
for rows.Next() {
var info map[string]interface{}
rows.Scan(&info)
log.Println(info)
}
}
- 运行
启动rest api
go run server/main.go
运行查询
go run main.go
效果
说明
go-sql-rest-driver 代码量很少,但是是一个学习golang db driver 开发的一个不错例子,我以前有写过一个简单的db driver
可以参考
参考资料
https://github.com/adaptant-labs/go-sql-rest-driver
https://github.com/xwb1989/sqlparser
https://github.com/rongfengliang/go-sql-rest-driver-learning
https://www.cnblogs.com/rongfengliang/p/13985952.html