123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327 |
- package tools
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "io/ioutil"
- "mime/multipart"
- "net"
- "net/http"
- "net/url"
- "os"
- "strconv"
- "strings"
- "time"
- )
- func Get(url string, authinfo ...string) (interface{}, error) {
- timeout := time.Duration(5 * time.Second)
- client := &http.Client{Timeout: timeout}
- req, reqerr := http.NewRequest("GET", url, nil)
- if reqerr != nil {
- fmt.Println(url)
- return nil, reqerr
- }
- if len(authinfo) > 0 && authinfo[0] != "" {
- req.Header.Set("Authorization", authinfo[0])
- }
- result, httperr := client.Do(req)
- //defer result.Body.Close()
- if httperr != nil {
- fmt.Println(url)
- return nil, httperr
- }
- body, err := ioutil.ReadAll(result.Body)
- if err != nil {
- return nil, err
- }
- result.Close = true
- return returnBody(body)
- }
- func Post(url string, data interface{}, authinfo ...string) (interface{}, error) {
- timeout := time.Duration(5 * time.Second)
- client := &http.Client{Timeout: timeout}
- req, reqerr := http.NewRequest("POST", url, strings.NewReader(data.(string)))
- if reqerr != nil {
- return nil, reqerr
- }
- if len(authinfo) > 0 && authinfo[0] != "" {
- req.Header.Set("Authorization", authinfo[0])
- //req.Header.Set("Content-Type", "application/json;charset=utf-8")
- }
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
- result, httperr := client.Do(req)
- //defer result.Body.Close()
- if httperr != nil {
- fmt.Println(url)
- fmt.Println(data)
- return nil, httperr
- }
- body, err := ioutil.ReadAll(result.Body)
- if err != nil {
- return nil, err
- }
- result.Close = true
- return returnBody(body)
- }
- func PostJson(url string, data interface{}, authinfo ...string) (interface{}, error) {
- timeout := time.Duration(5 * time.Second)
- client := &http.Client{Timeout: timeout}
- req, reqerr := http.NewRequest("POST", url, strings.NewReader(data.(string)))
- if reqerr != nil {
- fmt.Println(url)
- fmt.Println(data)
- return nil, reqerr
- }
- if len(authinfo) > 0 && authinfo[0] != "" {
- req.Header.Set("Authorization", authinfo[0])
- //
- }
- req.Header.Set("Content-Type", "application/json;charset=utf-8")
- result, httperr := client.Do(req)
- //defer result.Body.Close()
- if httperr != nil {
- fmt.Println(url)
- fmt.Println(data)
- return nil, httperr
- }
- body, err := ioutil.ReadAll(result.Body)
- if err != nil {
- return nil, err
- }
- result.Close = true
- return returnBody(body)
- }
- func PostRaw(url string, data interface{}) (interface{}, error) {
- result, httperr := http.Post(url, "text/plain;charset=utf-8", strings.NewReader(data.(string)))
- if httperr != nil {
- fmt.Println(url)
- fmt.Println(data)
- return nil, httperr
- }
- body, err := ioutil.ReadAll(result.Body)
- if err != nil {
- return nil, err
- }
- result.Close = true
- return returnBody(body)
- }
- func PostForm(url string, data url.Values, authinfo ...string) (interface{}, error) {
- timeout := time.Duration(5 * time.Second)
- client := &http.Client{Timeout: timeout}
- req, reqerr := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
- if reqerr != nil {
- fmt.Println(url)
- fmt.Println(data)
- return nil, reqerr
- }
- if len(authinfo) > 0 && authinfo[0] != "" {
- req.Header.Set("Authorization", authinfo[0])
- }
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
- result, httperr := client.Do(req)
- //defer result.Body.Close()
- if httperr != nil {
- fmt.Println(url)
- fmt.Println(data)
- return nil, httperr
- }
- body, err := ioutil.ReadAll(result.Body)
- if err != nil {
- return nil, err
- }
- result.Close = true
- return returnBody(body)
- }
- func PostRawBasicAuth(url string, data interface{}, user string, pwd string) (interface{}, error) {
- client := http.Client{
- Transport: &http.Transport{
- Dial: func(netw, addr string) (net.Conn, error) {
- c, err := net.DialTimeout(netw, addr, time.Second*5)
- if err != nil {
- fmt.Println("dail timeout", err)
- return nil, err
- }
- return c, nil
- },
- MaxIdleConnsPerHost: 10,
- ResponseHeaderTimeout: time.Second * 5,
- },
- }
- req, _ := http.NewRequest("POST", url, strings.NewReader(data.(string)))
- req.SetBasicAuth(user, pwd)
- req.Header.Set("Content-Type", "text/plain;charset=utf-8")
- result, httperr := client.Do(req)
- //result, httperr := http.Post(url, "text/plain;charset=utf-8", strings.NewReader(data.(string)))
- if httperr != nil {
- fmt.Println(url)
- fmt.Println(data)
- return nil, httperr
- }
- body, err := ioutil.ReadAll(result.Body)
- if err != nil {
- return nil, err
- }
- result.Close = true
- return returnBody(body)
- }
- func Put(url string, data interface{}) (interface{}, error) {
- req, httperr := http.NewRequest("PUT", url, strings.NewReader(data.(string)))
- if httperr != nil {
- return nil, httperr
- }
- res, httperr := http.DefaultClient.Do(req)
- if httperr != nil {
- return nil, httperr
- }
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- return nil, err
- }
- res.Close = true
- return returnBody(body)
- }
- func Delete(url string) (interface{}, error) {
- req, httperr := http.NewRequest("DELETE", url, nil)
- //req.Header.Add("Authorization", "5F6MJ3N2Tk9ruL_6XQpx-uxkkg:o56-nIwtgTzUX80YCNpbcjUL8iM=:eyJyZXNvdXJjZSI6IF9mbG93RGF0YVNvdXJjZTEiLCJleHBpcmVzIjoxNTM2NzU4ODE2LCJjb250ZW50TUQ1IjoiIiwiY29udGVudFR5cGUiOiIiLCJoZWFkZXJzIjoiIiwibWV0aG9kIjoiREVMRVRFIn0=")
- if httperr != nil {
- return nil, httperr
- }
- res, httperr := http.DefaultClient.Do(req)
- if httperr != nil {
- return nil, httperr
- }
- body, httperr := ioutil.ReadAll(res.Body)
- if httperr != nil {
- return nil, httperr
- }
- res.Close = true
- return returnBody(body)
- }
- func PostFile(targetUrl string, filename string, filed string) (interface{}, error) {
- bodyBuf := &bytes.Buffer{}
- bodyWriter := multipart.NewWriter(bodyBuf)
- //关键的一步操作
- fileWriter, err := bodyWriter.CreateFormFile(filed, filename)
- if err != nil {
- fmt.Println("error writing to buffer")
- return nil, err
- }
- //打开文件句柄操作
- fh, err := os.Open(filename)
- if err != nil {
- fmt.Println("error opening file")
- return nil, err
- }
- defer fh.Close()
- //iocopy
- _, err = io.Copy(fileWriter, fh)
- if err != nil {
- return nil, err
- }
- contentType := bodyWriter.FormDataContentType()
- bodyWriter.Close()
- resp, err := http.Post(targetUrl, contentType, bodyBuf)
- if err != nil {
- return nil, err
- }
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
- resp.Close = true
- return returnBody(body)
- }
- func Soap11(url string, databody string) (interface{}, error) {
- reqBody := `<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
- <soap:Body>` + databody + `</soap:Body>
- </soap:Envelope>`
- res, err := http.Post(url, "text/xml; charset=UTF-8", strings.NewReader(reqBody))
- if nil != err {
- fmt.Println("http post err:", err)
- return nil, err
- }
- defer res.Body.Close()
- // return status
- if http.StatusOK != res.StatusCode {
- fmt.Println("WebService soap1.1 request fail, status: %s\n", res.StatusCode)
- return strconv.Itoa(http.StatusOK), nil
- }
- data, err := ioutil.ReadAll(res.Body)
- if nil != err {
- fmt.Println("ioutil ReadAll err:", err)
- return nil, err
- }
- return string(data), nil
- }
- func Soap12(url string, databody string) (interface{}, error) {
- reqBody := `<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
- <soap12:Body>` + databody + `</soap12:Body>
- </soap12:Envelope>`
- res, err := http.Post(url, "application/soap+xml; charset=UTF-8", strings.NewReader(reqBody))
- if nil != err {
- fmt.Println("http post err:", err)
- return nil, err
- }
- defer res.Body.Close()
- // return status
- if http.StatusOK != res.StatusCode {
- fmt.Println("WebService soap1.1 request fail, status: %s\n", res.StatusCode)
- return strconv.Itoa(http.StatusOK), nil
- }
- data, err := ioutil.ReadAll(res.Body)
- if nil != err {
- fmt.Println("ioutil ReadAll err:", err)
- return nil, err
- }
- return string(data), nil
- }
- func returnBody(body []byte) (interface{}, error) {
- if len(body) == 0 {
- return "", nil
- }
- jsonStr := string(body)
- firstChar := jsonStr[0:1]
- if firstChar == "[" || firstChar == "{" {
- jsondata := make(map[string]interface{})
- newStr := `{"a":` + jsonStr + `}`
- err := json.Unmarshal([]byte(newStr), &jsondata)
- if err != nil {
- return jsonStr, err
- }
- return jsondata["a"], nil
- } else {
- return jsonStr, nil
- }
- }
|