139 lines
2.4 KiB
Go
139 lines
2.4 KiB
Go
package utils
|
|
|
|
import (
|
|
"io/ioutil"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
)
|
|
|
|
func Get(getUrl string, options ...interface{}) ([]byte, []*http.Cookie, error) {
|
|
client := &http.Client{}
|
|
|
|
var req *http.Request
|
|
var err error
|
|
headers := map[string]string{}
|
|
cookies := map[string]string{}
|
|
|
|
for key, option := range options {
|
|
switch key {
|
|
case 0:
|
|
if header, ok := option.(map[string]string); ok {
|
|
headers = header
|
|
}
|
|
case 1:
|
|
if cookie, ok := option.(map[string]string); ok {
|
|
cookies = cookie
|
|
}
|
|
}
|
|
}
|
|
|
|
req, err = http.NewRequest("GET", getUrl, nil)
|
|
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
for key, value := range headers {
|
|
req.Header.Add(key, value)
|
|
}
|
|
|
|
for key, value := range cookies {
|
|
cookie := &http.Cookie{
|
|
Name: key,
|
|
Value: value,
|
|
}
|
|
req.AddCookie(cookie)
|
|
}
|
|
|
|
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
|
return http.ErrUseLastResponse
|
|
}
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
cookie := resp.Cookies()
|
|
|
|
return body, cookie, err
|
|
}
|
|
|
|
func PostForm(postUrl string, options ...interface{}) ([]byte, []*http.Cookie, error) {
|
|
client := &http.Client{}
|
|
var req *http.Request
|
|
var err error
|
|
|
|
form := url.Values{}
|
|
headers := map[string]string{}
|
|
cookies := map[string]string{}
|
|
|
|
for key, option := range options {
|
|
switch key {
|
|
case 0:
|
|
if header, ok := option.(map[string]string); ok {
|
|
headers = header
|
|
}
|
|
case 1:
|
|
if cookie, ok := option.(map[string]string); ok {
|
|
cookies = cookie
|
|
}
|
|
case 2:
|
|
if body, ok := option.(map[string]string); ok {
|
|
for k, v := range body {
|
|
form.Add(k, v)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
req, err = http.NewRequest("POST", postUrl, strings.NewReader(form.Encode()))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
|
|
|
for key, value := range headers {
|
|
req.Header.Add(key, value)
|
|
}
|
|
|
|
for key, value := range cookies {
|
|
cookie := &http.Cookie{
|
|
Name: key,
|
|
Value: value,
|
|
}
|
|
req.AddCookie(cookie)
|
|
}
|
|
|
|
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
|
return http.ErrUseLastResponse
|
|
}
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
cookie := resp.Cookies()
|
|
|
|
return body, cookie, nil
|
|
}
|