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.

108 satır
2.2KB

  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "mime/multipart"
  9. "net/http"
  10. "net/http/httputil"
  11. "os"
  12. )
  13. //post a file to a url
  14. func postFileForm(filename string, targetURL string, formFieldName string) (strJSON string, err error) {
  15. bodyBuf := &bytes.Buffer{}
  16. bodyWriter := multipart.NewWriter(bodyBuf)
  17. // this step is very important
  18. fileWriter, err := bodyWriter.CreateFormFile(formFieldName, filename)
  19. if err != nil {
  20. fmt.Println(err)
  21. return "", err
  22. }
  23. // open file handle
  24. fh, err := os.Open(filename)
  25. if err != nil {
  26. fmt.Println(err)
  27. return "", err
  28. }
  29. //iocopy
  30. _, err = io.Copy(fileWriter, fh)
  31. if err != nil {
  32. return "", err
  33. }
  34. contentType := bodyWriter.FormDataContentType()
  35. bodyWriter.Close()
  36. resp, err := http.Post(targetURL, contentType, bodyBuf)
  37. if err != nil {
  38. return "", err
  39. }
  40. defer resp.Body.Close()
  41. r, err := ioutil.ReadAll(resp.Body)
  42. strJSON = string(r)
  43. if err != nil {
  44. return "", err
  45. }
  46. fmt.Println(resp.Status)
  47. fmt.Println(string(strJSON))
  48. return strJSON, nil
  49. }
  50. func postJSON(jsonB []byte, targetURL string) (resp string, err error) {
  51. headers := map[string]string{}
  52. headers["Content-Type"] = "application/json"
  53. return postRAW(jsonB, targetURL, headers)
  54. }
  55. func postRAW(data []byte, targetURL string, headers map[string]string) (resp string, err error) {
  56. return httpRaw("POST", targetURL, data, headers)
  57. }
  58. func putRAW(data []byte, targetURL string, headers map[string]string) (resp string, err error) {
  59. return httpRaw("PUT", targetURL, data, headers)
  60. }
  61. func httpRaw(httpMethod, targetURL string, data []byte, headers map[string]string) (resp string, err error) {
  62. requestBody := io.Reader(nil)
  63. if data != nil {
  64. requestBody = bytes.NewBuffer(data)
  65. }
  66. req, err := http.NewRequest(httpMethod, targetURL, requestBody)
  67. if err != nil {
  68. return
  69. }
  70. if headers != nil {
  71. for k, v := range headers {
  72. req.Header.Set(k, v)
  73. }
  74. }
  75. client := &http.Client{}
  76. r, err := client.Do(req)
  77. if err != nil {
  78. return
  79. }
  80. defer r.Body.Close()
  81. dump, err := httputil.DumpResponse(r, true)
  82. if err != nil {
  83. log.Fatal(err)
  84. }
  85. fmt.Printf("dump : %s", dump)
  86. b, _ := ioutil.ReadAll(r.Body)
  87. resp = string(b)
  88. log.Println(resp)
  89. return
  90. }