This commit is contained in:
parent
c33a997dc5
commit
57507756ec
14 changed files with 864 additions and 97 deletions
74
ia-wiki.go
Normal file
74
ia-wiki.go
Normal file
|
@ -0,0 +1,74 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Wikipedia API response structure
|
||||
type WikipediaResponse struct {
|
||||
Query struct {
|
||||
Pages map[string]struct {
|
||||
PageID int `json:"pageid"`
|
||||
Title string `json:"title"`
|
||||
Extract string `json:"extract"`
|
||||
} `json:"pages"`
|
||||
} `json:"query"`
|
||||
}
|
||||
|
||||
// Get Wikipedia summary
|
||||
func getWikipediaSummary(query string) (title, text, link string, ok bool) {
|
||||
// Clean and prepare query
|
||||
query = strings.TrimSpace(query)
|
||||
if query == "" {
|
||||
return "", "", "", false
|
||||
}
|
||||
|
||||
// API request
|
||||
apiURL := fmt.Sprintf(
|
||||
"https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&exintro&explaintext&redirects=1&titles=%s",
|
||||
url.QueryEscape(query),
|
||||
)
|
||||
|
||||
resp, err := http.Get(apiURL)
|
||||
if err != nil {
|
||||
return "", "", "", false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", "", "", false
|
||||
}
|
||||
|
||||
// Parse JSON response
|
||||
var result WikipediaResponse
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return "", "", "", false
|
||||
}
|
||||
|
||||
// Extract first valid page
|
||||
for _, page := range result.Query.Pages {
|
||||
if page.PageID == 0 || page.Extract == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Format text
|
||||
text = page.Extract
|
||||
if len(text) > 500 {
|
||||
text = text[:500] + "..."
|
||||
}
|
||||
|
||||
// Create link
|
||||
titleForURL := strings.ReplaceAll(page.Title, " ", "_")
|
||||
link = fmt.Sprintf("https://en.wikipedia.org/wiki/%s", url.PathEscape(titleForURL))
|
||||
|
||||
return page.Title, text, link, true
|
||||
}
|
||||
|
||||
return "", "", "", false
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue