golang NewsAPI客户端插件库newsapi-go的使用

golang NewsAPI客户端插件库newsapi-go的使用

安装

go get github.com/jellydator/newsapi-go

使用

我们使用NewClient函数创建一个客户端,默认只需要一个API密钥,但也可以通过可变选项函数设置其他参数。

client := newsapi.NewClient("apiKey", newsapi.WithHTTPClient(&http.Client{
	Timeout: 5 * time.Second,
}))

端点

Everything

Everything根据提供的参数检索所有文章。

articles, pageCount, err := client.Everything(context.Background(), newsapi.EverythingParams{
	Query: "cryptocurrency",
})
if err != nil {
	// 处理错误
}
// 成功

Top Headlines

TopHeadlines根据提供的参数检索头条新闻文章。

articles, pageCount, err := client.TopHeadlines(context.Background(), newsapi.TopHeadlinesParams{
	Query: "cryptocurrency",
})
if err != nil {
	// 处理错误
}
// 成功

Sources

Sources根据提供的参数检索可用的新闻来源。

sources, err := client.Sources(context.Background(), newsapi.SourceParams{
	Categories: []newsapi.Category{
		newsapi.CategoryBusiness,
		newsapi.CategoryScience,
	},
})
if err != nil {
	// 处理错误
}
// 成功

完整示例

下面是一个完整的示例代码,展示如何使用newsapi-go库:

package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/jellydator/newsapi-go"
)

func main() {
	// 创建客户端
	client := newsapi.NewClient("your-api-key", newsapi.WithHTTPClient(&http.Client{
		Timeout: 5 * time.Second,
	}))

	// 获取Everything文章
	everythingArticles, _, err := client.Everything(context.Background(), newsapi.EverythingParams{
		Query: "golang",
	})
	if err != nil {
		fmt.Printf("Error getting everything articles: %v\n", err)
	} else {
		fmt.Printf("Found %d everything articles\n", len(everythingArticles))
	}

	// 获取头条新闻
	topHeadlines, _, err := client.TopHeadlines(context.Background(), newsapi.TopHeadlinesParams{
		Query: "technology",
	})
	if err != nil {
		fmt.Printf("Error getting top headlines: %v\n", err)
	} else {
		fmt.Printf("Found %d top headlines\n", len(topHeadlines))
	}

	// 获取新闻来源
	sources, err := client.Sources(context.Background(), newsapi.SourceParams{
		Categories: []newsapi.Category{
			newsapi.CategoryTechnology,
		},
	})
	if err != nil {
		fmt.Printf("Error getting sources: %v\n", err)
	} else {
		fmt.Printf("Found %d sources\n", len(sources))
	}
}

这个示例展示了如何初始化客户端,并使用三种不同的端点获取新闻数据。记得将"your-api-key"替换为你实际的NewsAPI密钥。


更多关于golang NewsAPI客户端插件库newsapi-go的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang NewsAPI客户端插件库newsapi-go的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用newsapi-go构建Golang NewsAPI客户端

newsapi-go是一个用于访问NewsAPI的Golang客户端库,它简化了与NewsAPI的交互过程。下面我将介绍如何使用这个库来获取新闻数据。

安装

首先,你需要安装newsapi-go库:

go get github.com/jellydator/newsapi-go

基本用法

1. 初始化客户端

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/jellydator/newsapi-go"
)

func main() {
	// 从环境变量获取API密钥
	apiKey := os.Getenv("NEWS_API_KEY")
	if apiKey == "" {
		log.Fatal("NEWS_API_KEY environment variable not set")
	}

	// 创建NewsAPI客户端
	client := newsapi.NewClient(apiKey, nil)
	
	// 设置其他可选参数
	// client.SetHTTPClient(&http.Client{Timeout: 10 * time.Second})
}

2. 获取头条新闻

func getTopHeadlines(client *newsapi.Client) {
	// 设置查询参数
	opts := &newsapi.TopHeadlinesOptions{
		Country: "us",
		Category: "technology",
		PageSize: 5,
	}

	// 获取头条新闻
	results, err := client.GetTopHeadlines(opts)
	if err != nil {
		log.Fatalf("Error getting top headlines: %v", err)
	}

	// 打印结果
	fmt.Println("Total Results:", results.TotalResults)
	for _, article := range results.Articles {
		fmt.Println("---")
		fmt.Println("Title:", article.Title)
		fmt.Println("Source:", article.Source.Name)
		fmt.Println("URL:", article.URL)
		fmt.Println("PublishedAt:", article.PublishedAt)
	}
}

3. 获取所有新闻

func getAllNews(client *newsapi.Client) {
	// 设置查询参数
	opts := &newsapi.EverythingOptions{
		Q: "golang",
		Language: "en",
		SortBy: "publishedAt",
		PageSize: 3,
	}

	// 获取所有匹配新闻
	results, err := client.GetEverything(opts)
	if err != nil {
		log.Fatalf("Error getting all news: %v", err)
	}

	// 打印结果
	fmt.Println("Total Results:", results.TotalResults)
	for _, article := range results.Articles {
		fmt.Println("---")
		fmt.Println("Title:", article.Title)
		fmt.Println("Description:", article.Description)
		fmt.Println("URL:", article.URL)
	}
}

4. 获取可用新闻来源

func getSources(client *newsapi.Client) {
	// 设置查询参数
	opts := &newsapi.SourcesOptions{
		Category: "technology",
		Language: "en",
		Country: "us",
	}

	// 获取新闻来源
	results, err := client.GetSources(opts)
	if err != nil {
		log.Fatalf("Error getting sources: %v", err)
	}

	// 打印结果
	for _, source := range results.Sources {
		fmt.Println("---")
		fmt.Println("ID:", source.ID)
		fmt.Println("Name:", source.Name)
		fmt.Println("Description:", source.Description)
		fmt.Println("URL:", source.URL)
	}
}

高级用法

处理分页

func getPaginatedResults(client *newsapi.Client) {
	opts := &newsapi.EverythingOptions{
		Q: "artificial intelligence",
		PageSize: 20,
		Page: 2, // 获取第二页
	}

	results, err := client.GetEverything(opts)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Page %d of %d\n", opts.Page, results.TotalResults/opts.PageSize+1)
}

错误处理

func handleErrors(client *newsapi.Client) {
	_, err := client.GetTopHeadlines(&newsapi.TopHeadlinesOptions{
		Country: "xx", // 无效的国家代码
	})

	if err != nil {
		switch e := err.(type) {
		case *newsapi.ErrorResponse:
			// NewsAPI返回的错误
			fmt.Printf("API Error: %s (Code: %s)\n", e.Message, e.Code)
		default:
			// 其他错误
			fmt.Printf("Unexpected error: %v\n", err)
		}
		return
	}
}

完整示例

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/jellydator/newsapi-go"
)

func main() {
	apiKey := os.Getenv("NEWS_API_KEY")
	if apiKey == "" {
		log.Fatal("NEWS_API_KEY environment variable not set")
	}

	client := newsapi.NewClient(apiKey, nil)

	fmt.Println("=== Technology Headlines ===")
	getTopHeadlines(client)

	fmt.Println("\n=== Golang News ===")
	getAllNews(client)

	fmt.Println("\n=== Tech News Sources ===")
	getSources(client)
}

// 前面定义的函数放在这里...

注意事项

  1. 你需要从NewsAPI官网获取API密钥
  2. 免费计划有请求限制(500次/天)
  3. 某些高级功能可能需要付费计划
  4. 建议缓存结果以减少API调用
  5. 处理错误时区分API错误和网络错误

newsapi-go库提供了简洁的接口来访问NewsAPI的所有功能,通过合理的参数组合,你可以获取各种类型的新闻数据。

回到顶部