message.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package main
  2. import (
  3. "io"
  4. "log"
  5. "net/http"
  6. "net/url"
  7. "strconv"
  8. "strings"
  9. "time"
  10. )
  11. type message struct {
  12. account account
  13. content, visibility string
  14. feed feed
  15. }
  16. func (msg *message) post() error {
  17. if debug {
  18. log.Printf("msg:\n\n%v", msg)
  19. log.Printf("msg.feed:\n\n%v", msg.feed)
  20. }
  21. apiURL := msg.account.InstanceURL + "/api/v1/statuses"
  22. data := url.Values{}
  23. data.Set("status", msg.content)
  24. data.Set("visibility", msg.feed.Visibility)
  25. data.Set("sensitive", strconv.FormatBool(msg.feed.Sensitive))
  26. data.Set("spoiler_text", msg.feed.ContentWarning)
  27. if debug {
  28. log.Printf("Data:\n\n%v", data)
  29. }
  30. switch msg.feed.Format {
  31. case "markdown":
  32. data.Set("content_type", "text/markdown")
  33. case "html":
  34. data.Set("content_type", "text/html")
  35. case "plain":
  36. data.Set("content_type", "text/plain")
  37. case "bbcode":
  38. data.Set("content_type", "text/bbcode")
  39. }
  40. var req *http.Request
  41. var body io.Reader
  42. body = strings.NewReader(data.Encode())
  43. if debug {
  44. log.Printf("Message:\n\n%s", msg.content)
  45. }
  46. req, err := http.NewRequest("POST", apiURL, body)
  47. if err != nil {
  48. return err
  49. }
  50. if debug {
  51. log.Printf("Request:\n\n%v", body)
  52. }
  53. // Set Headers
  54. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  55. req.Header.Set("Authorization", "Bearer "+msg.account.AccessToken)
  56. req.Header.Set("User-Agent", conf.HttpConfig.UserAgent)
  57. c := &http.Client{Timeout: time.Second * 10}
  58. if !debugOrDryRun {
  59. var resp *http.Response
  60. resp, err = c.Do(req)
  61. if err != nil {
  62. return err
  63. }
  64. defer func(Body io.ReadCloser) {
  65. _ = Body.Close()
  66. }(resp.Body)
  67. log.Println("response Status: ", resp.Status)
  68. }
  69. return nil
  70. }