网站首页 文章专栏 Go 语言好用的库
[toc]
go mod 管理包版本
代理,比goproxy.io快
export GOPROXY=”https://mirrors.aliyun.com/goproxy/” export GO111MODULE=on
requests-go http client
获取 response header
fmt.Println(resp.R.Header["Content-Type"])
fmt.Println(resp.R.Header["Content-Encoding"])
获取cookies
resp,err := requests.Get("http://xcc.vip.qikan.com/")
if err != nil{
return
}
coo := resp.Cookies()
for _, c:= range coo{
fmt.Println(c.Name,c.Value)
}
import "golang.org/x/text/encoding/simplifiedchinese"
simplifiedchinese.GBK.NewEncoder().Bytes() //utf-8 转 gbk
simplifiedchinese.GBK.NewDecoder().Bytes() //gbk 转 utf-8
func main() {
str := "月色真美,风也温柔,233333333,~!@#" //go字符串编码为utf-8
fmt.Println("before convert:", str) //打印转换前的字符串
fmt.Println("isUtf8:", isUtf8([]byte(str))) //判断是否是utf-8
gbkData, _ := simplifiedchinese.GBK.NewEncoder().Bytes([]byte(str)) //使用官方库将utf-8转换为gbk
fmt.Println("gbk直接打印会出现乱码:", string(gbkData)) //乱码字符串
fmt.Println("isGBK:", isGBK(gbkData)) //判断是否是gbk
utf8Data, _ := simplifiedchinese.GBK.NewDecoder().Bytes(gbkData) //将gbk再转换为utf-8
fmt.Println("isUtf8:", isUtf8(utf8Data) ) //判断是否是utf-8
fmt.Println("after convert:", string(utf8Data)) //打印转换前的字符串
}
resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
当获取到响应体的时候,客户端必须手动关闭链接:
resp, err := http.Get("http://example.com/")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...
控制 Http
客户端 headers
, redirect
策略以及其他的设置,需要这样创建一个 Client
:
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
resp, err := client.Get("http://example.com")
// ...
req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...
分行写长字符串时,用反引号包起来就可以”