上一节已将将需要的数据从网站[](http://www.gratisography.com/)http://www.gratisography.com/ 抓取并存入数据库【使用crawldata.go
中的InsertData(&imageDatas)
函数】,现在需要将数据从数据库indiepic
的表gratisography
中取出并然会json
格式的数据。
项目文件夹结构如下:
1 2 3 4 5 6
| indiepic ├── README.md ├── crawldata │ ├── crawldata.go │ └── database.go └── indiepic.go
|
现在将获取数据的函数写在database.go
中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| 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() imgOut, err := db.Query("SELECT * FROM gratisography") if err != nil { fmt.Println(s.Join([]string{"获取数据失败", err.Error()}, "-->")) return nil, err } defer imgOut.Close() var ( id int img_url string type_name string title string width int height int create_time string ) for imgOut.Next() { 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。
在使用之前需要先获取:
1
| go get github.com/go-martini/martini
|
在indiepic.go
中引入martini
:
1 2 3
| import ( "github.com/go-martini/martini" )
|
定义一个结构体Results
用于表示输出结果的数据结构:
1 2 3 4 5
| type Results struct { Err int Msg string Datas crawldata.ImageDatas }
|
因为需要输出json
格式数据,所以需要用martini
的encoder
中间件资源,使用下面命令获取:
1
| go get github.com/martini-contrib/encoder
|
然后import
:
1 2 3
| import ( "github.com/martini-contrib/encoder" )
|
因为数据已经抓取完存入数据库了,所以在main
函数中,就不在需要调用crawldata.Crawl()
了,将其注释掉。然后编写如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| func main() { m := martini.New() route := martini.NewRouter() var ( results Results err error ) m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) { 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
部分:
1 2 3 4 5 6 7 8
| import ( "fmt" "github.com/go-martini/martini" "github.com/martini-contrib/encoder" "indiepic/crawldata" "net/http" s "strings" )
|
然后运行:
在浏览器中访问 http://127.0.0.1:3000/api 即可看到输出的json
数据。如果安装了postman
可以使用postman
访问地址,查看时选择json
。
到这里这个例子就结束了。源码见GitHub。