| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- package beaconfire
- import (
- "bytes"
- "io/ioutil"
- "net/http"
- "time"
- )
- const (
- _DEFAULT_USER_AGENT = "curl v7.19.1"
- )
- func Get(url string) ([]byte, error) {
- return Request(http.MethodGet, url, nil, nil, "", "")
- }
- func PostJson(url string, body []byte) ([]byte, error) {
- return Request(http.MethodPost, url, body, map[string]string{"Content-Type": "application/json"}, "", "")
- }
- // Delivery a HTTP request
- //
- // @method: http Method, eg. http.MethodGet
- // @url: endpoint
- // @body: post body
- // @headers: request headers
- // @usename: basic auth
- // @password: basic auth
- // @return: response, error
- func Request(method string, url string, body []byte, headers map[string]string, username, password string) ([]byte, error) {
- client := http.Client{
- Timeout: time.Second * 5,
- }
- req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
- if err != nil {
- return nil, err
- }
- if len(username) > 0 || len(password) > 0 {
- req.SetBasicAuth(username, password)
- }
- req.Header.Set("User-Agent", _DEFAULT_USER_AGENT)
- for k, v := range headers {
- req.Header.Set(k, v)
- }
- resp, err := client.Do(req)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
- return ioutil.ReadAll(resp.Body)
- }
|