From 15f78b2da38d074ad17e6cd52e2cc8f997b46286 Mon Sep 17 00:00:00 2001 From: Yasuhiro Matsumoto Date: Fri, 14 Apr 2017 12:33:12 +0900 Subject: [PATCH] small refactoring --- cmd/mstdn/main.go | 91 ++++++++++++++++++++++++++--------------------- 1 file changed, 51 insertions(+), 40 deletions(-) diff --git a/cmd/mstdn/main.go b/cmd/mstdn/main.go index 8a0de7f..9c96bf1 100644 --- a/cmd/mstdn/main.go +++ b/cmd/mstdn/main.go @@ -131,9 +131,55 @@ func authenticate(client *mastodon.Client, config *mastodon.Config, file string) } } -func main() { - flag.Parse() +func streaming(client *mastodon.Client) { + ctx, cancel := context.WithCancel(context.Background()) + sc := make(chan os.Signal, 1) + signal.Notify(sc, os.Interrupt) + q, err := client.StreamingPublic(ctx) + if err != nil { + log.Fatal(err) + } + go func() { + <-sc + cancel() + close(q) + }() + for e := range q { + switch t := e.(type) { + case *mastodon.UpdateEvent: + color.Set(color.FgHiRed) + fmt.Println(t.Status.Account.Username) + color.Set(color.Reset) + fmt.Println(textContent(t.Status.Content)) + case *mastodon.ErrorEvent: + color.Set(color.FgYellow) + fmt.Println(t.Error()) + color.Set(color.Reset) + } + } +} +func init() { + flag.Parse() + if *fromfile != "" { + text, err := readFile(*fromfile) + if err != nil { + log.Fatal(err) + } + *toot = string(text) + } +} + +func post(client *mastodon.Client, text string) { + _, err := client.PostStatus(&mastodon.Toot{ + Status: text, + }) + if err != nil { + log.Fatal(err) + } +} + +func main() { file, config, err := getConfig() if err != nil { log.Fatal(err) @@ -145,49 +191,14 @@ func main() { authenticate(client, config, file) return } - if *fromfile != "" { - text, err := readFile(*fromfile) - if err != nil { - log.Fatal(err) - } - *toot = string(text) - } if *toot != "" { - _, err = client.PostStatus(&mastodon.Toot{ - Status: *toot, - }) - if err != nil { - log.Fatal(err) - } + post(client, *toot) return } + if *stream { - ctx, cancel := context.WithCancel(context.Background()) - sc := make(chan os.Signal, 1) - signal.Notify(sc, os.Interrupt) - q, err := client.StreamingPublic(ctx) - if err != nil { - log.Fatal(err) - } - go func() { - <-sc - cancel() - close(q) - }() - for e := range q { - switch t := e.(type) { - case *mastodon.UpdateEvent: - color.Set(color.FgHiRed) - fmt.Println(t.Status.Account.Username) - color.Set(color.Reset) - fmt.Println(textContent(t.Status.Content)) - case *mastodon.ErrorEvent: - color.Set(color.FgYellow) - fmt.Println(t.Error()) - color.Set(color.Reset) - } - } + streaming(client) return }