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.

107 lines
2.3KB

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. //MediaID : json response for uploading media
  7. type MediaID struct {
  8. Type string `json:"type"`
  9. MediaID string `json:"media_id"`
  10. CreateAt int64 `json:"created_at"`
  11. ThumbMediaID string `json:"thumb_media_id"`
  12. }
  13. func uploadImage(filename string) (mediaid string) {
  14. url, _ := getPostImageURL()
  15. jstr, _ := postFileForm(filename, url, "media")
  16. //{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
  17. var m = MediaID{}
  18. json.Unmarshal([]byte(jstr), &m)
  19. mediaid = m.MediaID
  20. return
  21. }
  22. func uploadVideo(filename string) (mediaid string) {
  23. url, _ := getPostVideoURL()
  24. jstr, _ := postFileForm(filename, url, "media")
  25. //{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
  26. var m = MediaID{}
  27. json.Unmarshal([]byte(jstr), &m)
  28. mediaid = m.MediaID
  29. return
  30. }
  31. func uploadVoice(path string) (mediaID string) {
  32. url, _ := getPostVoiceURL()
  33. jstr, _ := postFileForm(path, url, "media")
  34. var m = MediaID{}
  35. json.Unmarshal([]byte(jstr), &m)
  36. mediaID = m.MediaID
  37. return
  38. }
  39. func uploadThumb(path string) (mediaID string) {
  40. url, _ := getPostThumbURL()
  41. jstr, _ := postFileForm(path, url, "media")
  42. var m = MediaID{}
  43. json.Unmarshal([]byte(jstr), &m)
  44. mediaID = m.ThumbMediaID
  45. return
  46. }
  47. func checkImageSanity() bool {
  48. //check file size should < 2M
  49. fmt.Println(" should check image file size")
  50. return true
  51. }
  52. func getPostImageURL() (url string, err error) {
  53. return getMediaPostURL("image")
  54. }
  55. func getPostVoiceURL() (url string, err error) {
  56. return getMediaPostURL("voice")
  57. }
  58. func getPostVideoURL() (url string, err error) {
  59. return getMediaPostURL("video")
  60. }
  61. func getPostThumbURL() (url string, err error) {
  62. return getMediaPostURL("thumb")
  63. }
  64. func getMediaPostURL(t string) (url string, err error) {
  65. atk, err := GetAccessToken()
  66. if err != nil {
  67. url = ""
  68. } else {
  69. url = fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s", atk, t)
  70. }
  71. return
  72. }
  73. func saveMedia2File(mediaID string) (filename string, err error) {
  74. url := mediaID2URL(mediaID)
  75. file, _, e := saveURL(url)
  76. if e != nil {
  77. return "", e
  78. }
  79. fmt.Println("save media to " + file)
  80. return file, nil
  81. }
  82. func mediaID2URL(mediaID string) (url string) {
  83. atk, _ := GetAccessToken()
  84. url = fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s", atk, mediaID)
  85. return
  86. }