golang Unsplash API客户端插件库go-unsplash的使用
Golang Unsplash API客户端插件库go-unsplash的使用
安装
go get github.com/hbagdi/go-unsplash/unsplash
依赖
这个库有一个依赖项是Google的go-querystring。
API指南
使用Unsplash API时,需要确保遵守他们的API指南和API条款。
注册
在Unsplash.com上注册并注册为开发者。然后可以创建新应用并使用AppID和Secret进行身份验证。
使用示例
导入库
import "github.com/hbagdi/go-unsplash/unsplash"
认证
认证不由go-unsplash直接处理,而是传递一个可以处理认证的http.Client
。
ts := oauth2.StaticTokenSource(
// 注意访问令牌前的Client-ID
&oauth2.Token{AccessToken: "Client-ID Your-access-token"},
)
client := oauth2.NewClient(oauth2.NoContext, ts)
// 使用http.Client实例化unsplash
unsplash := unsplash.New(client)
// 现在可以向API发出请求
randomPhoto, _ , err := unsplash.RandomPhoto(nil)
获取随机照片
photos, resp, err := unsplash.Photos.Random(nil)
assert.Nil(err)
assert.NotNil(photos)
assert.NotNil(resp)
assert.Equal(1, len(*photos))
var opt RandomPhotoOpt
opt.Count = 3
photos, resp, err = unsplash.Photos.Random(&opt)
assert.Nil(err)
assert.NotNil(photos)
assert.NotNil(resp)
assert.Equal(3, len(*photos))
获取所有照片
opt := new(unsplash.ListOpt)
opt.Page = 1
opt.PerPage = 10
if !opt.Valid() {
fmt.Println("error with opt")
return
}
count := 0
for {
photos, resp, err := un.Photos.All(opt)
if err != nil {
fmt.Println("error")
return
}
// 处理照片
for _, c := range *photos {
fmt.Printf("%d : %d\n", count, *c.ID)
count += 1
}
// 获取下一页
if !resp.HasNextPage {
return
}
opt.Page = resp.NextPage
}
获取特定照片详情
photo, resp, err := unsplash.Photos.Photo("9BoqXzEeQqM", nil)
assert.NotNil(photo)
assert.NotNil(resp)
assert.Nil(err)
fmt.Println(photo)
// photo是*Unsplash.Photo类型
// 也可以指定PhotoOpt获取自定义大小或裁剪的照片
var opt PhotoOpt
opt.Height = 400
opt.Width = 600
photo, resp, err = unsplash.Photos.Photo("9BoqXzEeQqM", &opt)
assert.NotNil(photo)
assert.NotNil(resp)
assert.Nil(err)
log.Println(photo)
// photo.Urls.Custom会有裁剪后的照片
搜索照片
var opt SearchOpt
opt.Query = "Nature"
// 搜索标记为"Nature"的照片
photos, _, err = unsplash.Search.Photos(&opt)
log.Println(len(*photos.Results))
assert.NotNil(photos)
assert.Nil(err)
获取用户详情
profileImageOpt := &ProfileImageOpt{Height: 120, Width: 400}
// 或者传递nil作为第二个参数
user, err := unsplash.Users.User("lukechesser", profileImageOpt)
assert.Nil(err)
assert.NotNil(user)
// 或者,获取当前认证用户
user, resp, err := unsplash.CurrentUser()
assert.Nil(user)
assert.Nil(resp)
assert.NotNil(err)
错误处理
所有API调用都会返回一个error
作为第二个或第三个返回对象。所有成功的调用都会在这个返回位置返回nil。
randomPhoto, _ , err := unsplash.RandomPhoto(nil)
if err != nil {
// 处理错误
}
分页
分页目前通过在ListOpt中提供页码来支持。Response中的NextPage
字段可用于获取下一页的页码。
searchOpt := &SearchOpt{Query : "Batman"}
photos, resp, err := unsplash.Search.Photos(searchOpt)
if err != nil {
return
}
// 处理照片
for _,photo := range *photos {
fmt.Println(*photo.ID)
}
// 获取下一页
if !resp.HasNextPage {
return
}
searchOpt.Page = resp.NextPage
photos, resp ,err = unsplash.Search.Photos(searchOpt)
// photos现在有搜索结果的下一页
许可证
Copyright © 2017 Hardik Bagdi hbagdi1@binghamton.edu
MIT License
完整许可证内容请参考原始文档。
更多关于golang Unsplash API客户端插件库go-unsplash的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于golang Unsplash API客户端插件库go-unsplash的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
使用go-unsplash访问Unsplash API
go-unsplash是一个非官方的Golang客户端库,用于与Unsplash API进行交互。下面我将介绍如何使用这个库来访问Unsplash的各种功能。
安装
首先安装go-unsplash库:
go get github.com/hbagdi/go-unsplash
初始化客户端
要使用Unsplash API,你需要先注册开发者账号并获取访问密钥。
package main
import (
"context"
"fmt"
"os"
"github.com/hbagdi/go-unsplash/unsplash"
"golang.org/x/oauth2"
)
func main() {
// 从环境变量获取访问令牌
accessToken := os.Getenv("UNSPLASH_ACCESS_KEY")
if accessToken == "" {
panic("请设置UNSPLASH_ACCESS_KEY环境变量")
}
// 创建OAuth2配置
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: accessToken},
)
tc := oauth2.NewClient(context.Background(), ts)
// 创建Unsplash客户端
client := unsplash.New(tc)
}
常用功能示例
1. 搜索照片
func searchPhotos(client *unsplash.Unsplash, query string) {
// 设置搜索选项
opts := &unsplash.SearchPhotosOpts{
Query: query,
Page: 1,
PerPage: 10,
}
// 执行搜索
results, resp, err := client.Search.Photos(context.Background(), opts)
if err != nil {
panic(err)
}
fmt.Printf("找到 %d 张照片:\n", results.Total)
for _, photo := range results.Results {
fmt.Printf("- ID: %s, 描述: %s, URL: %s\n",
*photo.ID,
*photo.Description,
*photo.URLs.Raw)
}
}
2. 获取随机照片
func getRandomPhoto(client *unsplash.Unsplash) {
opts := &unsplash.RandomPhotoOpts{
Count: 1,
}
photos, resp, err := client.Photos.Random(context.Background(), opts)
if err != nil {
panic(err)
}
if len(photos) > 0 {
photo := photos[0]
fmt.Printf("随机照片: %s (%s)\n", *photo.ID, *photo.URLs.Full)
}
}
3. 下载照片
func downloadPhoto(client *unsplash.Unsplash, photoID string) {
// 获取照片详情
photo, resp, err := client.Photos.Get(context.Background(), photoID, nil)
if err != nil {
panic(err)
}
// 触发下载统计(Unsplash要求)
_, _, err = client.Photos.Download(context.Background(), photoID)
if err != nil {
panic(err)
}
fmt.Printf("照片下载链接: %s\n", *photo.Links.Download)
}
4. 获取用户信息
func getUserProfile(client *unsplash.Unsplash, username string) {
user, resp, err := client.Users.Get(context.Background(), username)
if err != nil {
panic(err)
}
fmt.Printf("用户: %s\n", *user.Name)
fmt.Printf("个人简介: %s\n", *user.Bio)
fmt.Printf("照片数: %d\n", *user.TotalPhotos)
}
完整示例
package main
import (
"context"
"fmt"
"os"
"github.com/hbagdi/go-unsplash/unsplash"
"golang.org/x/oauth2"
)
func main() {
accessToken := os.Getenv("UNSPLASH_ACCESS_KEY")
if accessToken == "" {
panic("请设置UNSPLASH_ACCESS_KEY环境变量")
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken})
tc := oauth2.NewClient(context.Background(), ts)
client := unsplash.New(tc)
// 搜索照片
searchPhotos(client, "nature")
// 获取随机照片
getRandomPhoto(client)
// 获取用户信息
getUserProfile(client, "adam")
}
// 上面定义的函数放在这里...
注意事项
- 使用Unsplash API需要遵守他们的API指南
- 免费层API有调用限制(50次/小时)
- 使用照片时需要按照要求进行署名
- 下载照片前必须触发下载统计端点
这个库提供了对Unsplash API的完整覆盖,你可以根据需要探索更多功能,如管理收藏、搜索用户、获取统计数据等。