network.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. package etc
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "mime/multipart"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "path/filepath"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. time "time"
  18. )
  19. func GetHttpResponseSimplePost(method string, apiurl string, jsBytes []byte) (retbody []byte, retsta []byte, reterr error) {
  20. response, err := http.Post(apiurl, "application/json", bytes.NewBuffer(jsBytes))
  21. if err != nil {
  22. fmt.Printf("The HTTP request failed with error %s\n", err)
  23. } else {
  24. retbody, _ = ioutil.ReadAll(response.Body)
  25. }
  26. return retbody, []byte(strconv.Itoa(response.StatusCode)), nil
  27. }
  28. func GetHttpResponse(method string, apiurl string, jsBytes []byte) ([]byte, []byte, error) {
  29. reader := bytes.NewBuffer(jsBytes)
  30. req, err := http.NewRequest(method, apiurl, reader)
  31. if err != nil {
  32. return nil, []byte("909"), MyErr("WERZDSVADFZ-http.NewRequest", err, false)
  33. }
  34. req.Header.Add("Content-Type", "application/json")
  35. req.Header.Add("Accept", "application/json")
  36. req.Header.Add("Endpoint-Agent", "abango-rest-api-v1.0")
  37. req.Header.Add("Accept-Language", "en-US")
  38. req.Header.Add("User-Agent", runtime.GOOS+"-"+runtime.Version()) // for checking OS Type in Server
  39. // 들어가지 않으면 Request Reject 됨. //Go 에서는 SERVER_NAME 을 구할 방법이 없다. 아직까지는
  40. req.Header.Add("FrontendHost", "localhost:normal")
  41. req.Header.Add("RemoteIp", "localhost")
  42. req.Header.Add("Referer", "http://localhost")
  43. req.Header.Add("DeviceDesc", "API-Developer-Device")
  44. i := len(os.Args)
  45. if i != 1 { // 1일 경우는 go function call 의 경우 이므로 memory fault 가 난다.
  46. gateToken := os.Args[i-2]
  47. if len(gateToken) == 20 { // Argument 뒤에서 2번째 Arg가 20자리이면 GateToken 이라고 간주
  48. req.Header.Add("GateToken", gateToken)
  49. }
  50. }
  51. req.Body = ioutil.NopCloser(bytes.NewReader(jsBytes))
  52. // Client객체에서 Request 실행
  53. client := &http.Client{
  54. Timeout: time.Second * 3600, //Otherwirse, it can cause crash without this line. Must Must.
  55. // Timeout: time.Second * 20, //Otherwirse, it can cause crash without this line. Must Must.
  56. } // Normal is 10 but extend 20 on 1 Dec 2018
  57. // fmt.Println(reflect.TypeOf(respo))
  58. resp, err := client.Do(req)
  59. if err != nil {
  60. return nil, []byte("909"), MyErr("WERZDSVXBDCZSRE-client.Do "+apiurl, err, false)
  61. }
  62. defer resp.Body.Close()
  63. byteRtn, _ := ioutil.ReadAll(resp.Body)
  64. return byteRtn, []byte(strconv.Itoa(resp.StatusCode)), nil
  65. }
  66. func UploadFileResponse(method string, apiurl string, jsBytes []byte) ([]byte, []byte, error) {
  67. paramFile := "file"
  68. uploader := struct {
  69. FilePath string `json:"FilePath"`
  70. }{}
  71. var params map[string]interface{}
  72. if err := json.Unmarshal(jsBytes, &uploader); err == nil {
  73. params, _ = StructToMap(uploader, "json")
  74. }
  75. reqBd := &bytes.Buffer{}
  76. writer := multipart.NewWriter(reqBd)
  77. // 추가할 폼필드는 writer.WriteField("key", "Value") 이렇게 작업 한다.
  78. path := fmt.Sprint(params["FilePath"])
  79. file, err := os.Open(path)
  80. if err != nil {
  81. return nil, []byte("804"), errors.New("OLKMBVF-os.Open file, " + path + " " + err.Error())
  82. }
  83. defer file.Close()
  84. part, err := writer.CreateFormFile(paramFile, filepath.Base(path))
  85. if err != nil {
  86. return nil, []byte("804"), errors.New("WER%^TGCDS-CreateFormFile, " + path + err.Error())
  87. }
  88. _, err = io.Copy(part, file)
  89. if err = writer.Close(); err != nil {
  90. return nil, []byte("804"), errors.New("YUHGTYGHK-writer.Close" + err.Error())
  91. }
  92. req, err := http.NewRequest(method, apiurl, reqBd)
  93. // reader := bytes.NewBuffer(jsBytes)
  94. // req, err := http.NewRequest(method, apiurl, reader)
  95. if err != nil {
  96. return nil, []byte("804"), MyErr("WERZDSVADFZ-http.NewRequest", err, false)
  97. }
  98. req.Header.Add("Content-Type", "application/json")
  99. req.Header.Add("Accept", "application/json")
  100. req.Header.Add("Endpoint-Agent", "abango-rest-api-v1.0")
  101. req.Header.Add("Accept-Language", "en-US")
  102. req.Header.Add("User-Agent", runtime.GOOS+"-"+runtime.Version()) // for checking OS Type in Server
  103. // 들어가지 않으면 Request Reject 됨. //Go 에서는 SERVER_NAME 을 구할 방법이 없다. 아직까지는
  104. req.Header.Add("FrontendHost", "localhost:normal")
  105. req.Header.Add("RemoteIp", "localhost")
  106. req.Header.Add("Referer", "http://localhost")
  107. i := len(os.Args)
  108. if i != 1 { // 1일 경우는 go function call 의 경우 이므로 memory fault 가 난다.
  109. gateToken := os.Args[i-2]
  110. if len(gateToken) == 20 { // Argument 뒤에서 2번째 Arg가 20자리이면 GateToken 이라고 간주
  111. req.Header.Add("GateToken", gateToken)
  112. }
  113. }
  114. // fmt.Println(writer.FormDataContentType())
  115. req.Header.Set("Content-Type", writer.FormDataContentType())
  116. // req.Body = ioutil.NopCloser(bytes.NewReader(jsBytes))
  117. // Client객체에서 Request 실행
  118. client := &http.Client{
  119. Timeout: time.Second * 3600, //Otherwirse, it can cause crash without this line. Must Must.
  120. // Timeout: time.Second * 20, //Otherwirse, it can cause crash without this line. Must Must.
  121. } // Normal is 10 but extend 20 on 1 Dec 2018
  122. // fmt.Println(reflect.TypeOf(respo))
  123. resp, err := client.Do(req)
  124. if err != nil {
  125. return nil, []byte("804"), MyErr("ERTYUIJBVFBHK-client.Do "+apiurl, err, false)
  126. }
  127. defer resp.Body.Close()
  128. byteRtn, _ := ioutil.ReadAll(resp.Body)
  129. return byteRtn, []byte(strconv.Itoa(resp.StatusCode)), nil
  130. }
  131. func GetHttpResponseOLd(method string, apiurl string, jsBytes []byte) ([]byte, []byte, error) {
  132. // func GetHttpResponseOld(method string, apiurl string, jsBytes []byte) ([]byte, []byte, error) {
  133. form := url.Values{}
  134. // form.Add("postvalues", string(kkk))
  135. // Values.Encode() encodes the values into "URL encoded" form sorted by key.
  136. // eForm := v.Encode()
  137. // fmt.Printf("v.Encode(): %v\n", s)
  138. reader := strings.NewReader(form.Encode()) // This causes 411 error
  139. // req, err := http.NewRequest("GET", apiurl, reader)
  140. req, err := http.NewRequest(method, apiurl, reader)
  141. if err != nil {
  142. return nil, []byte("909"), MyErr("WERZDSVADFZ-http.NewRequest", err, true)
  143. }
  144. req.Header.Add("Content-Type", "application/json")
  145. req.Header.Add("Accept", "application/json")
  146. req.Header.Add("Endpoint-Agent", "abango-rest-api-v1.0")
  147. req.Header.Add("Accept-Language", "en-US")
  148. req.Header.Add("User-Agent", runtime.GOOS+"-"+runtime.Version()) // for checking OS Type in Server
  149. req.Body = ioutil.NopCloser(bytes.NewReader(jsBytes))
  150. // Client객체에서 Request 실행
  151. client := &http.Client{
  152. Timeout: time.Second * 3600, //Otherwirse, it can cause crash without this line. Must Must.
  153. // Timeout: time.Second * 20, //Otherwirse, it can cause crash without this line. Must Must.
  154. } // Normal is 10 but extend 20 on 1 Dec 2018
  155. // fmt.Println(reflect.TypeOf(respo))
  156. resp, err := client.Do(req)
  157. if err != nil {
  158. return nil, []byte("909"), MyErr("REWTAVDEQWFAF-client.Do "+apiurl, err, true)
  159. }
  160. defer resp.Body.Close()
  161. byteRtn, _ := ioutil.ReadAll(resp.Body)
  162. return byteRtn, []byte(strconv.Itoa(resp.StatusCode)), nil
  163. }