1. http标准库
1.1 http客户端
func main() { response, err := http.get("https://www.imooc.com") if err != nil { return } defer response.body.close() bytes, err := httputil.dumpresponse(response, true) if err != nil { return } fmt.printf("%s", bytes) }
1.2 自定义请求头
func main() { request, err := http.newrequest(http.methodget, "https://www.imooc.com", nil) if err != nil { return } //自定义请求头 request.header.add("header", "value") response, err := http.defaultclient.do(request) if err != nil { return } defer response.body.close() bytes, err := httputil.dumpresponse(response, true) if err != nil { return } fmt.printf("%s", bytes) }
1.3 检查请求重定向
//检查重定向函数 client := http.client{checkredirect: func(req *http.request, via []*http.request) error { // via: 所有重定向的路径 // req: 当前重定向的路径 return nil }} response, err := client.do(request) if err != nil { return }
1.4 http服务器性能分析
图形界面的使用需要安装 graphviz
导入 :_ “net/http/pprof” , 下划线代表只使用其中的依赖,不加就会编译报错
访问:/debug/pprof
使用:
- go tool pprof http://localhost:8888/debug/pprof/profile 可以查看30秒的cpu使用率
- go tool pprof http://localhost:6060/debug/pprof/block 查看gorountine阻塞配置文件
2. json数据处理
2.1 实体序列化
type order struct { id string name string quantity int totalprice float64 } func main() { o := order{id: "1234", name: "learn go", quantity: 3, totalprice: 30.0} fmt.printf("%+v\n", o) //序列化后的字节切片, bytes, err := json.marshal(o) if err != nil { return } fmt.printf("%s\n", bytes) }
注意:首写字母为小写,marshal不会进行序列化
2.2 处理字段为小写下划线
使用属性标签
type order struct { id string `json:"id""` name string `json:"name"` quantity int `json:"quantity"` totalprice float64 `json:"total_price"` } func main() { o := order{id: "1234", name: "learn go", quantity: 3, totalprice: 30.0} fmt.printf("%+v\n", o) //序列化 bytes, err := json.marshal(o) if err != nil { return } fmt.printf("%s\n", bytes) }
2.3 省略空字段
在字段上添加 omitempty 可以省略空字的字段
type order struct { id string `json:"id""` name string `json:"name,omitempty"` quantity int `json:"quantity"` totalprice float64 `json:"total_price"` }
2.4 反序列化
func main() { //反序列化 str := `{"id":"1234","name":"learn go","quantity":3,"total_price":30}` order := unmarshal[order](str, order{}) fmt.printf("%+v\n", order) } //使用泛型的方法,可以解析出对应的实体类 func unmarshal[t any](str string, t t) any { err := json.unmarshal([]byte(str), &t) if err != nil { return nil } return t }
3. 自然语言处理
可以调用阿里云的自然语言处理api进行数据的处理
3.1 使用map处理
func mapunmarshall() { str := `{ "data": [ { "id": 0, "word": "请", "tags": [ "基本词-中文" ] }, { "id": 1, "word": "输入", "tags": [ "基本词-中文", "产品类型修饰词" ] }, { "id": 2, "word": "文本", "tags": [ "基本词-中文", "产品类型修饰词" ] } ] }` //map存储数据都使用interface来存储 m := make(map[string]any) err := json.unmarshal([]byte(str), &m) if err != nil { return } //如果需要取id为2的数据,需要指明所取的值是一个切片 使用type assertion,包括取后续的数据的时候都要指定类型 fmt.printf("%+v\n", m["data"].([]any)[2].(map[string]any)["tags"]) }
3.2 定义实体处理
//map存储数据都使用interface来存储 m := struct { data []struct{ id int32 `json:"id"` word string `json:"word"` tags []string `json:"tags"` } `json:"data"` }{} err := json.unmarshal([]byte(str), &m) if err != nil { return } fmt.printf("%+v\n", m.data[2].tags)
4. http框架
4.1 gin
下载依赖:go get -u github.com/gin-gonic/gin、go get -u go.uber.org/zap (日志库)
4.1.1 启动服务
func main() { r := gin.default() r.get("/ping", func(c *gin.context) { c.json(200, gin.h{ "message": "pong", }) }) r.run() // listen and serve on 0.0.0.0:8080 }
4.1.2 middleware
context 结构体其中包含了请求相关的信息
可以为web服务添加 “拦截器” ,添加 middleware 拦截请求打印自己需要的日志
logger, _ := zap.newproduction() r.use(printrequestlog, printhello) //如果添加多个,先定义上方法,直接添加即可 func printrequestlog(c *gin.context) { logger.info("incoming request", zap.string("path", c.request.url.path)) //放行,如果不释放,后续就不能进行处理 c.next() //获取到response对象 logger.info("处理状态:", zap.int("status", c.writer.status())) } func printhello(c *gin.context) { fmt.println("hello:", c.request.url.path) //放行,如果不释放,后续就不能进行处理 c.next() }
4.1.3 设置请求id
func setrequestid(c *gin.context) { c.set("requestid", rand.int()) c.next() }
到此这篇关于golang详细讲解常用http库及gin框架的应用的文章就介绍到这了,更多相关golang http库内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!