1. package main
    2. import (
    3. "bytes"
    4. "encoding/json"
    5. "io"
    6. "io/ioutil"
    7. "net/http"
    8. "time"
    9. )
    10. // 发送GET请求
    11. // url: 请求地址
    12. // response: 请求返回的内容
    13. func Get(url string) string {
    14. // 超时时间:5秒
    15. client := &http.Client{Timeout: 5 * time.Second}
    16. resp, err := client.Get(url)
    17. if err != nil {
    18. panic(err)
    19. }
    20. defer resp.Body.Close()
    21. var buffer [512]byte
    22. result := bytes.NewBuffer(nil)
    23. for {
    24. n, err := resp.Body.Read(buffer[0:])
    25. result.Write(buffer[0:n])
    26. if err != nil && err == io.EOF {
    27. break
    28. } else if err != nil {
    29. panic(err)
    30. }
    31. }
    32. return result.String()
    33. }
    34. // 发送POST请求
    35. // url: 请求地址
    36. // data: POST请求提交的数据
    37. // contentType: 请求体格式,如:application/json
    38. // content: 请求放回的内容
    39. func Post(url string, data interface{}, contentType string) string {
    40. // 超时时间:5秒
    41. client := &http.Client{Timeout: 5 * time.Second}
    42. jsonStr, _ := json.Marshal(data)
    43. resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
    44. if err != nil {
    45. panic(err)
    46. }
    47. defer resp.Body.Close()
    48. result, _ := ioutil.ReadAll(resp.Body)
    49. return string(result)
    50. }