GO学习笔记(19) - 标准库

98 阅读3分钟

目录

  • HTTP
  • JSON
  • 其他标准库
  • 查看标准库文档

HTTP

httpclient

package main

import (
	"fmt"
	"net/http"
	"net/http/httputil"
	_ "net/http/pprof" //用于分析性能
)

func httpClientDemo() {
	request,err := http.NewRequest(http.MethodGet,"https://www.imooc.com/",nil)
	request.Header.Add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4385.0 Safari/537.36")

	//req:重定向的最重目标
	//via:多次重定向的数据列表s
	client := http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error{
			fmt.Println("CheckRedirect:",req)
			return nil
		},
	}
	resp,err := client.Do(request)
	//resp,err := http.Get("http://www.sina.com")
	if err != nil{
		panic(err)
	}
	defer resp.Body.Close()

	s,err := httputil.DumpResponse(resp,true)
	if err != nil{
		panic(err)
	}
	fmt.Printf("%s \n",s)

}

func main() {
	httpClientDemo()
}

http server

教程与源码见 《GO学习笔记(16) - 简易静态文件web应用》

性能分析
  • web.go改造:在之前代码的基础上增加如下包引入
_ "net/http/pprof"

网页版

http://localhost/debug/pprof

命令行

//cpu
go tool pprof  http://localhost/debug/ppro/profile  
//内存
go tool pprof  http://localhost/debug/ppro/heap
...

JSON

  • 注意json格式化输出
  • json数据格式打印
package main


import (
	"encoding/json"
	"fmt"
)

//格式输出
type Order struct {
	Id string  `json:"id"`
	Name string  `json:"name,omitempty"` //omitempty忽略空字段输出
	Quality int  `json:"quality"`
	TotalPrice float64  `json:"totalPrice"`
	Item []*OrderItem `json:"item"`
}

type OrderItem struct {
	Id string  `json:"id"`
	Name string `json:"name"`
	Price float64 `json:"price"`
}

func marshal()  {
	o := Order{
		Id: "1234",
		Name: "learn go",
		Quality: 10,
		TotalPrice: 100,
		Item: []*OrderItem{
			{
				Id: "item_1",
				Name: "learn go",
				Price: 15,
			},
			{
				Id: "item_2",
				Name: "netty",
				Price: 25,
			},
		},
	}
	//内存参数序列化为可以为网络上传输的byte[]数据
	b ,err := json.Marshal(o)
	if err != nil{
		panic(err)
	}
	//注意"+"号
	fmt.Printf("%+v \n",o)
	//可用于网络上传输
	//可用于跨语言间json的传输,输出为小写的字段
	fmt.Printf("%+s \n",b)
}

func main() {
	marshal()
}

  • 输出
{Id:1234 Name:learn go Quality:10 TotalPrice:100} 
{"id":"1234","name":"learn go","quality":10,"totalPrice":100,"item":{"id":"item_1","name":"earn go","price":15}} 

将字符串格式化为json

//将字符串变为json对象
func unmarshal()  {
	s := `{"id":"1234","name":"learn go","quality":10,"totalPrice":100,"item":[{"id":"item_1","name":"learn go","price":15},{"id":"item_2","name":"netty","price":25}]}`
	var o Order
	//注意&o(地址)
	err := json.Unmarshal([]byte(s),&o)
	if err != nil{
		panic(err)
	}
	fmt.Printf("%+v \n",o)

}

API接口取值

  • map方式
  • 结构体方式
func apiData()  {
	//...
	res :=`{
		"data": [
			{
			"synonym":"牛仔库",
			"weight":"0.8",
			"word":"韩都衣舍",
			"tag":"品牌"
			},
			{
			"synonym":"连衣裙",
			"weight":"0.9",
			"word":"lily",
			"tag":"品牌"
			},
			{
			"synonym":"上衣",
			"weight":"0.5",
			"word":"vero moda",
			"tag":"品牌"
			}	
		]}` //json格式字串

	m := make(map[string]interface{})
	//map送过来的数据后面一定要加interface()
	m1 := struct {
		Data []struct{
			Synonym string `json:"synonym"`
			Word string `json:"word"`
		} `json:"data"`
	}{}
	err1 := json.Unmarshal([]byte(res),&m)
	err2 := json.Unmarshal([]byte(res),&m1)
	if err1 != nil{
		panic(err1)
	}
	if err2 != nil{
		panic(err2)
	}
	fmt.Printf("1. %+v \n\n",m)
	fmt.Printf("1. %+v \n\n",m1)
	//type
	fmt.Printf("2. %+v \n\n",m["data"].([]interface{})[2])
	//取值
	fmt.Printf("3. %+v \n\n",m["data"].([]interface{})[2].(map[string]interface{})["word"])
	fmt.Printf("4. %+v \n\n",m1.Data[2].Synonym)
	fmt.Printf("5. %+v \n\n",m1.Data[2].Word)
}

输出

1. map[data:[map[synonym:牛仔库 tag:品牌 weight:0.8 word:韩都衣舍] map[synonym:连衣裙 tag:品牌 weight:0.9 word:lily] map[synonym:上衣 tag:品牌 weight:0.5 word:vero moda]]] 
2. {Data:[{Synonym:牛仔库 Word:韩都衣舍} {Synonym:连衣裙 Word:lily} {Synonym:上衣 Word:vero moda}]} 
3. map[synonym:上衣 tag:品牌 weight:0.5 word:vero moda] 
4. vero moda 
5. 上衣 
6. vero moda 

其他标准库:

  • bufio: 比io.Reader与Writer速度会高很多
  • encoding/json
  • log
  • regexp
  • time
  • strings/math/rand

如何查看标准库文档

  • 安装
go get golang.org/x/tools/cmd/godoc
  • 启动
$ godoc -http :8080
----
返回如下值,代表成功
using module mode; GOMOD=NUL
godoc -http :8080
  • 浏览访问
http://localhost:8080/pkg/

第三方库

  • 日志库:logrus
  • 国际化或编码库:golang.org/x/text
//  可用于处理乱码
transform.NewReader(resp.Body,simplifiedchinese.GBK.NewDecoder())
  • 自动检查网页编码: go get -g -v golang.org/x/net/html