-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
110 lines (89 loc) · 2.31 KB
/
main.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"sort"
"time"
"github.com/joho/godotenv"
)
type ResponseData struct {
Results []struct {
Properties struct {
Name struct {
Title []struct {
Text struct {
Content string `json:"content"`
} `json:"text"`
} `json:"title"`
} `json:"Name"`
} `json:"properties"`
} `json:"results"`
}
// .envファイルから環境変数を読み込む
func loadEnv() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
// NotionのAPIエンドポイント作成
func createAPIURL(baseURL, databaseID string) string {
return fmt.Sprintf("%s/databases/%s", baseURL, databaseID) // 指定したフォーマット(%sを後続の引数に置き換えて)文字列を生成
}
// HTTPリクエストを実行
func doRequest(req *http.Request) *http.Response {
client := &http.Client{Timeout: time.Second * 10}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
return resp
}
// レスポンスの加工処理
func processResponse(resp *http.Response) {
defer resp.Body.Close()
// 応答ボディを読み込み、コンソールに出力
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// JSONをGoのデータ構造に変換する
var data ResponseData
// var data interface{}
json.Unmarshal(body, &data)
contents := make([]string, 0, len(data.Results))
// サイズと容量をあらかじめ指定したスライスを作成
for _, result := range data.Results {
if len(result.Properties.Name.Title) > 0 {
content := result.Properties.Name.Title[0].Text.Content
contents = append(contents, content)
}
}
// 文字列のスライスソート
sort.Strings(contents)
for i, content := range contents {
fmt.Printf("Content %d: %s\n", i, content)
}
// Goのデータ構造を、整形したJSON文字列に変換する
// formatted, err := json.MarshalIndent(data, "", " ")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(string(formatted))
}
/*
* main関数
*/
func main() {
loadEnv()
notionAPIBase := "https://api.notion.com/v1"
databaseID := os.Getenv("DATABASE_ID")
apiURL := createAPIURL(notionAPIBase, databaseID)
req := CreatedRequestMultiFilteredItems(apiURL)
resp := doRequest(req)
processResponse(resp)
}