上一节已将将须要的数据从网站http://www.gratisography.com/ 抓取并存入数据库【使用crawldata.go
中的InsertData(&imageDatas)
函数】,如今须要将数据从数据库indiepic
的表gratisography
中取出并然会json
格式的数据。git
项目文件夹结构以下:github
indiepic ├── README.md ├── crawldata │ ├── crawldata.go │ └── database.go └── indiepic.go
如今将获取数据的函数写在database.go
中:web
func GetAllImages() (imageDatas ImageDatas, err error) { // 链接数据库 db, err := OpenDatabase() if err != nil { fmt.Printf(s.Join([]string{"链接数据库失败", err.Error()}, "-->")) return nil, err } defer db.Close() // Prepare statement for inserting data imgOut, err := db.Query("SELECT * FROM gratisography") if err != nil { fmt.Println(s.Join([]string{"获取数据失败", err.Error()}, "-->")) return nil, err } defer imgOut.Close() // 定义扫描select到的数据库字段的变量 var ( id int img_url string type_name string title string width int height int create_time string ) for imgOut.Next() { // db.Query()中select几个字段就须要Scan多少个字段 err := imgOut.Scan(&id, &img_url, &type_name, &title, &width, &height, &create_time) if err != nil { fmt.Println(s.Join([]string{"查询数据失败", err.Error()}, "-->")) return nil, err } else { imageData := ImageData{img_url, type_name, title, width, height} imageDatas = append(imageDatas, imageData) } } return imageDatas, nil }
值得一提的是在SELECT
语句中拿到多少个字段就须要在Scan
的时候使用变量去获取多少个字段,否测会报错。因此建议不要像上面那样SELECT *
,而是指定须要的字段如SELECT id,img_url,title FROM tableName
。GetAllImages()
函数返回两个参数imageDatas ImageDatas
、err error
。数据库
虽然使用GO本身写一个HTTP请求很简单,但为了更好地处理路由和数据,这里使用一个web框架martini Classy web framework for Go。
在使用以前须要先获取:json
go get github.com/go-martini/martini
在indiepic.go
中引入martini
:api
import ( "github.com/go-martini/martini" )
定义一个结构体Results
用于表示输出结果的数据结构:浏览器
type Results struct { Err int // 错误码 Msg string // 错误信息 Datas crawldata.ImageDatas // 数据,无数据时为nil }
由于须要输出json
格式数据,因此须要用martini
的encoder
中间件资源,使用下面命令获取:数据结构
go get github.com/martini-contrib/encoder
而后import
:app
import ( "github.com/martini-contrib/encoder" )
由于数据已经抓取完存入数据库了,因此在main
函数中,就不在须要调用crawldata.Crawl()
了,将其注释掉。而后编写以下代码:框架
func main() { // 使用crawldata包里面的Crawl()抓取须要的数据存到数据库 // crawldata.Crawl() m := martini.New() route := martini.NewRouter() var ( results Results err error ) m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) { // 将encoder.JsonEncoder{}按照encoder.Encoder接口(注意大小写)类型注入到内部 c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil)) w.Header().Set("Content-Type", "application/json; charset=utf-8") }) route.Get("/", func(enc encoder.Encoder) (int, []byte) { result := Results{10001, "Not Found Data", nil} return http.StatusOK, encoder.Must(enc.Encode(result)) }) route.Get("/api", func(enc encoder.Encoder) (int, []byte) { results.Datas, err = crawldata.GetAllImages() if err != nil { fmt.Println(s.Join([]string{"获取数据失败", err.Error()}, "-->")) result := Results{10001, "Data Error", nil} return http.StatusOK, encoder.Must(enc.Encode(result)) } else { results.Err = 10001 results.Msg = "获取数据成功" return http.StatusOK, encoder.Must(enc.Encode(results)) } }) m.Action(route.Handle) m.Run() }
import
部分:
import ( "fmt" "github.com/go-martini/martini" "github.com/martini-contrib/encoder" "indiepic/crawldata" "net/http" s "strings" )
而后运行:
go run indiepic.go
在浏览器中访问 http://127.0.0.1:3000/api 便可看到输出的json
数据。若是安装了postman
能够使用postman
访问地址,查看时选择json
。
到这里这个例子就结束了。源码见GitHub。