Command line client for Write.as https://write.as/apps/cli
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
1.6 KiB

  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "github.com/codegangsta/cli"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "strconv"
  14. )
  15. func main() {
  16. app := cli.NewApp()
  17. app.Name = "writeas"
  18. app.Version = "1.0"
  19. app.Usage = "Simple text pasting and publishing"
  20. app.Authors = []cli.Author{
  21. {
  22. Name: "Matt Baer",
  23. Email: "mb@mattbaer.io",
  24. },
  25. }
  26. app.Action = post
  27. app.Run(os.Args)
  28. }
  29. func post(*cli.Context) {
  30. numBytes, numChunks := int64(0), int64(0)
  31. r := bufio.NewReader(os.Stdin)
  32. fullPost := []byte{}
  33. buf := make([]byte, 0, 1024)
  34. for {
  35. n, err := r.Read(buf[:cap(buf)])
  36. buf = buf[:n]
  37. if n == 0 {
  38. if err == nil {
  39. continue
  40. }
  41. if err == io.EOF {
  42. break
  43. }
  44. log.Fatal(err)
  45. }
  46. numChunks++
  47. numBytes += int64(len(buf))
  48. fullPost = append(fullPost, buf...)
  49. if err != nil && err != io.EOF {
  50. log.Fatal(err)
  51. }
  52. }
  53. fmt.Println("Posting...")
  54. DoPost(fullPost)
  55. }
  56. func DoPost(post []byte) {
  57. apiUrl := "http://i.write.as"
  58. data := url.Values{}
  59. data.Set("w", string(post))
  60. u, _ := url.ParseRequestURI(apiUrl)
  61. u.Path = "/"
  62. urlStr := fmt.Sprintf("%v", u)
  63. client := &http.Client{}
  64. r, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode()))
  65. r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  66. r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
  67. resp, _ := client.Do(r)
  68. defer resp.Body.Close()
  69. if resp.StatusCode == http.StatusOK {
  70. content, err := ioutil.ReadAll(resp.Body)
  71. if err != nil {
  72. fmt.Printf("%s\n", err)
  73. os.Exit(1)
  74. }
  75. fmt.Printf("%s\n", string(content))
  76. } else {
  77. fmt.Printf("Unable to post: %s\n", resp.Status)
  78. }
  79. }