This repository has been archived by the owner on Dec 4, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.go
93 lines (73 loc) · 1.74 KB
/
utils.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Files with general processing such as URL generation
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"github.com/skratchdot/open-golang/open"
"github.com/tidwall/gjson"
"golang.org/x/term"
)
type result struct {
title string
content string
url string
}
type param struct {
Query string
Language string
SafeSearch int
}
func newURL(param param) string {
u := &url.URL{
Scheme: "https",
Host: "api.freasearch.org",
Path: "search",
}
q := u.Query()
q.Set("q", param.Query)
q.Set("language", "ja-JP")
u.RawQuery = q.Encode()
return u.String()
}
func getResp(param param) ([]result, error) {
req, err := http.NewRequest("GET", newURL(param), nil)
if err != nil {
return nil, fmt.Errorf("リクエストの作成に失敗しました: %w", err)
}
client := new(http.Client)
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("リクエストの取得に失敗しました: %w", err)
}
defer resp.Body.Close()
bArray, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("レスポンスボディの読み込みに失敗しました: %w", err)
}
results := gjson.Get(string(bArray), "results")
ctns := []result{}
for _, r := range results.Array() {
title := gjson.Get(r.String(), "title").String()
content := gjson.Get(r.String(), "content").String()
url := gjson.Get(r.String(), "url").String()
tmp := result{title: title, content: content, url: url}
ctns = append(ctns, tmp)
}
return ctns, nil
}
func setWidth() int {
fd := int(os.Stdout.Fd())
width, _, err := term.GetSize(fd)
if err != nil {
log.Fatal(err)
}
return (width / 2) - 7
}
func openBrowser(url string) {
fmt.Printf("Open the %s in your browser...", url)
open.Run(url)
}