You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-fly/tools/http.go

75 lines
1.6 KiB

package tools
import (
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
)
func Get(url string) string {
res, err := http.Get(url)
if err != nil {
return ""
}
robots, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return ""
}
return string(robots)
}
//Post("http://xxxx","application/json;charset=utf-8",[]byte("{'aaa':'bbb'}"))
func Post(url string, contentType string, body []byte) (string, error) {
res, err := http.Post(url, contentType, strings.NewReader(string(body)))
if err != nil {
return "", err
}
defer res.Body.Close()
content, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
return string(content), nil
}
func PostHeader(url string, msg []byte, headers map[string]string) (string, error) {
client := &http.Client{}
req, err := http.NewRequest("POST", url, strings.NewReader(string(msg)))
if err != nil {
return "", err
}
for key, header := range headers {
req.Header.Set(key, header)
}
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func IsMobile(userAgent string) bool {
mobileRe, _ := regexp.Compile("(?i:Mobile|iPod|iPhone|Android|Opera Mini|BlackBerry|webOS|UCWEB|Blazer|PSP)")
str := mobileRe.FindString(userAgent)
if str != "" {
return true
}
return false
}
//发送http post请求数据为form
func PostForm(url string, data url.Values) (string, error) {
resp, err := http.PostForm(url, data)
if err != nil {
return "", err
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(content), nil
}