Files
webp/api/search.go
2024-12-16 13:56:34 +08:00

72 lines
1.8 KiB
Go

package api
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"github.com/graphql-go/graphql"
)
type Search struct {
Name string `json:"text"`
Count int `json:"count"`
}
var SearchItem = graphql.NewObject(graphql.ObjectConfig{
Name: "Search",
Description: "搜索",
Fields: graphql.Fields{
"name": &graphql.Field{Type: graphql.String, Description: "搜索词"},
},
})
var SearchItems = &graphql.Field{
Name: "Searchs",
Description: "搜索词列表",
Type: graphql.NewObject(graphql.ObjectConfig{
Name: "SearchConnection",
Description: "搜索词列表",
Fields: graphql.Fields{
"list": &graphql.Field{Type: graphql.NewList(SearchItem), Description: "搜索词列表"},
},
}),
Args: graphql.FieldConfigArgument{
"name": &graphql.ArgumentConfig{Type: graphql.String, Description: "按指定字符筛选"},
"first": &graphql.ArgumentConfig{Type: graphql.Int, Description: "翻页参数(傳回清單中的前n個元素)", DefaultValue: 10},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var searchs []Search
// 发送 GET 请求
resp, err := http.Get(fmt.Sprintf("http://localhost:6005/api/get_search/hot?page=%d", p.Args["first"]))
if err != nil {
log.Fatalf("Failed to fetch data: %v", err)
}
defer resp.Body.Close()
// 读取响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Println("Failed to read response body: %v", err)
}
// 检查 HTTP 状态码
if resp.StatusCode != http.StatusOK {
log.Println("HTTP request failed with status code: %d", resp.StatusCode)
}
// 解码 JSON 数据
err = json.Unmarshal(body, &searchs)
if err != nil {
log.Println("Failed to parse JSON: %v", err)
}
return map[string]interface{}{
"list": searchs,
}, err
},
}