commit d22c8440305b833deea26886bdb2556363efc0b0 Author: Matt Baer Date: Tue Mar 10 22:39:59 2015 -0400 :rocket: Includes posting ability using the current API utilized by the Android app at i.write.as. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b72f9be --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*~ +*.swp diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..0ed9677 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,7 @@ +language: go + +notifications: + email: false + +go: + - 1.4 diff --git a/README.md b/README.md new file mode 100644 index 0000000..0df346a --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +writeas-cli +=========== +Command line interface for [Write.as](https://write.as). diff --git a/cli.go b/cli.go new file mode 100644 index 0000000..a6e8478 --- /dev/null +++ b/cli.go @@ -0,0 +1,93 @@ +package main + +import ( + "bufio" + "bytes" + "fmt" + "github.com/codegangsta/cli" + "io" + "io/ioutil" + "log" + "net/http" + "net/url" + "os" + "strconv" +) + +func main() { + app := cli.NewApp() + app.Name = "writeas" + app.Version = "1.0" + app.Usage = "Simple text pasting and publishing" + app.Authors = []cli.Author{ + { + Name: "Matt Baer", + Email: "mb@mattbaer.io", + }, + } + + app.Action = post + + app.Run(os.Args) +} + +func post(*cli.Context) { + numBytes, numChunks := int64(0), int64(0) + r := bufio.NewReader(os.Stdin) + fullPost := []byte{} + buf := make([]byte, 0, 1024) + for { + n, err := r.Read(buf[:cap(buf)]) + buf = buf[:n] + if n == 0 { + if err == nil { + continue + } + if err == io.EOF { + break + } + log.Fatal(err) + } + numChunks++ + numBytes += int64(len(buf)) + + fullPost = append(fullPost, buf...) + if err != nil && err != io.EOF { + log.Fatal(err) + } + } + + fmt.Println("Posting...") + + DoPost(fullPost) +} + +func DoPost(post []byte) { + apiUrl := "http://i.write.as" + + data := url.Values{} + data.Set("w", string(post)) + + u, _ := url.ParseRequestURI(apiUrl) + u.Path = "/" + urlStr := fmt.Sprintf("%v", u) + + client := &http.Client{} + r, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode())) + r.Header.Add("Content-Type", "application/x-www-form-urlencoded") + r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode()))) + + resp, _ := client.Do(r) + defer resp.Body.Close() + + if resp.StatusCode == http.StatusOK { + content, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Printf("%s\n", err) + os.Exit(1) + } + fmt.Printf("%s\n", string(content)) + } else { + fmt.Printf("Unable to post: %s\n", resp.Status) + } +}