small refactoring

pull/5/head
Yasuhiro Matsumoto 2017-04-14 12:30:13 +09:00
parent 0281f9c746
commit e8fd17094f
1 changed files with 34 additions and 35 deletions

View File

@ -34,24 +34,25 @@ func readFile(filename string) ([]byte, error) {
return ioutil.ReadFile(filename) return ioutil.ReadFile(filename)
} }
func extractText(node *html.Node, w *bytes.Buffer) {
if node.Type == html.TextNode {
data := strings.Trim(node.Data, "\r\n")
if data != "" {
w.WriteString(data + "\n")
}
}
for c := node.FirstChild; c != nil; c = c.NextSibling {
extractText(c, w)
}
}
func textContent(s string) string { func textContent(s string) string {
doc, err := html.Parse(strings.NewReader(s)) doc, err := html.Parse(strings.NewReader(s))
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
var buf bytes.Buffer var buf bytes.Buffer
var extractText func(node *html.Node, w *bytes.Buffer)
extractText = func(node *html.Node, w *bytes.Buffer) {
if node.Type == html.TextNode {
data := strings.Trim(node.Data, "\r\n")
if data != "" {
w.WriteString(data + "\n")
}
}
for c := node.FirstChild; c != nil; c = c.NextSibling {
extractText(c, w)
}
}
extractText(doc, &buf) extractText(doc, &buf)
return buf.String() return buf.String()
} }
@ -111,6 +112,25 @@ func getConfig() (string, *mastodon.Config, error) {
return file, config, nil return file, config, nil
} }
func authenticate(client *mastodon.Client, config *mastodon.Config, file string) {
email, password, err := prompt()
if err != nil {
log.Fatal(err)
}
err = client.Authenticate(email, password)
if err != nil {
log.Fatal(err)
}
b, err := json.MarshalIndent(config, "", " ")
if err != nil {
log.Fatal("failed to store file:", err)
}
err = ioutil.WriteFile(file, b, 0700)
if err != nil {
log.Fatal("failed to store file:", err)
}
}
func main() { func main() {
flag.Parse() flag.Parse()
@ -122,22 +142,7 @@ func main() {
client := mastodon.NewClient(config) client := mastodon.NewClient(config)
if config.AccessToken == "" { if config.AccessToken == "" {
email, password, err := prompt() authenticate(client, config, file)
if err != nil {
log.Fatal(err)
}
err = client.Authenticate(email, password)
if err != nil {
log.Fatal(err)
}
b, err := json.MarshalIndent(config, "", " ")
if err != nil {
log.Fatal("failed to store file:", err)
}
err = ioutil.WriteFile(file, b, 0700)
if err != nil {
log.Fatal("failed to store file:", err)
}
return return
} }
if *fromfile != "" { if *fromfile != "" {
@ -145,13 +150,7 @@ func main() {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
_, err = client.PostStatus(&mastodon.Toot{ *toot = string(text)
Status: string(text),
})
if err != nil {
log.Fatal(err)
}
return
} }
if *toot != "" { if *toot != "" {