Golang詳細(xì)講解常用Http庫(kù)及Gin框架的應(yīng)用
1. Http標(biāo)準(zhǔn)庫(kù)
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 自定義請(qǐng)求頭
func main() { request, err := http.NewRequest(http.MethodGet, "https://www.imooc.com", nil) if err != nil { return } //自定義請(qǐng)求頭 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 檢查請(qǐng)求重定向
//檢查重定向函數(shù) client := http.Client{CheckRedirect: func(req *http.Request, via []*http.Request) error { // via: 所有重定向的路徑 // req: 當(dāng)前重定向的路徑 return nil }} response, err := client.Do(request) if err != nil { return }
1.4 http服務(wù)器性能分析
圖形界面的使用需要安裝 graphviz
導(dǎo)入 :_ “net/http/pprof” , 下劃線代表只使用其中的依賴,不加就會(huì)編譯報(bào)錯(cuò)
訪問(wèn):/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數(shù)據(jù)處理
2.1 實(shí)體序列化
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) //序列化后的字節(jié)切片, bytes, err := json.Marshal(o) if err != nil { return } fmt.Printf("%s\n", bytes) }
注意:首寫字母為小寫,Marshal不會(huì)進(jìn)行序列化
2.2 處理字段為小寫下劃線
使用屬性標(biāo)簽
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) } //使用泛型的方法,可以解析出對(duì)應(yīng)的實(shí)體類 func unmarshal[T any](str string, t T) any { err := json.Unmarshal([]byte(str), &t) if err != nil { return nil } return t }
3. 自然語(yǔ)言處理
可以調(diào)用阿里云的自然語(yǔ)言處理api進(jìn)行數(shù)據(jù)的處理
3.1 使用Map處理
func mapUnmarshall() { str := `{ "data": [ { "id": 0, "word": "請(qǐng)", "tags": [ "基本詞-中文" ] }, { "id": 1, "word": "輸入", "tags": [ "基本詞-中文", "產(chǎn)品類型修飾詞" ] }, { "id": 2, "word": "文本", "tags": [ "基本詞-中文", "產(chǎn)品類型修飾詞" ] } ] }` //map存儲(chǔ)數(shù)據(jù)都使用interface來(lái)存儲(chǔ) m := make(map[string]any) err := json.Unmarshal([]byte(str), &m) if err != nil { return } //如果需要取id為2的數(shù)據(jù),需要指明所取的值是一個(gè)切片 使用type assertion,包括取后續(xù)的數(shù)據(jù)的時(shí)候都要指定類型 fmt.Printf("%+v\n", m["data"].([]any)[2].(map[string]any)["tags"]) }
3.2 定義實(shí)體處理
//map存儲(chǔ)數(shù)據(jù)都使用interface來(lái)存儲(chǔ) 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 (日志庫(kù))
4.1.1 啟動(dòng)服務(wù)
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 結(jié)構(gòu)體其中包含了請(qǐng)求相關(guān)的信息
可以為web服務(wù)添加 “攔截器” ,添加 middleware 攔截請(qǐng)求打印自己需要的日志
logger, _ := zap.NewProduction() r.Use(printRequestLog, printHello) //如果添加多個(gè),先定義上方法,直接添加即可 func printRequestLog(c *gin.Context) { logger.Info("Incoming request", zap.String("path", c.Request.URL.Path)) //放行,如果不釋放,后續(xù)就不能進(jìn)行處理 c.Next() //獲取到response對(duì)象 logger.Info("處理狀態(tài):", zap.Int("status", c.Writer.Status())) } func printHello(c *gin.Context) { fmt.Println("hello:", c.Request.URL.Path) //放行,如果不釋放,后續(xù)就不能進(jìn)行處理 c.Next() }
4.1.3 設(shè)置請(qǐng)求ID
func setRequestId(c *gin.Context) { c.Set("requestId", rand.Int()) c.Next() }
到此這篇關(guān)于Golang詳細(xì)講解常用Http庫(kù)及Gin框架的應(yīng)用的文章就介紹到這了,更多相關(guān)Golang Http庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
go-zero 應(yīng)對(duì)海量定時(shí)/延遲任務(wù)的技巧
這篇文章主要介紹了go-zero 如何應(yīng)對(duì)海量定時(shí)/延遲任務(wù),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10Golang 實(shí)現(xiàn)超大文件讀取的兩種方法
這篇文章主要介紹了Golang 實(shí)現(xiàn)超大文件讀取的兩種方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04深入淺出Golang中select的實(shí)現(xiàn)原理
在go語(yǔ)言中,select語(yǔ)句就是用來(lái)監(jiān)聽和channel有關(guān)的IO操作,當(dāng)IO操作發(fā)生時(shí),觸發(fā)相應(yīng)的case操作,有了select語(yǔ)句,可以實(shí)現(xiàn)main主線程與goroutine線程之間的互動(dòng)。本文就來(lái)詳細(xì)講講select的實(shí)現(xiàn)原理,需要的可以參考一下2022-08-08Go中time.RFC3339 時(shí)間格式化的實(shí)現(xiàn)
這篇文章主要介紹了Go中time.RFC3339 時(shí)間格式化的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01Go語(yǔ)言實(shí)現(xiàn)一個(gè)簡(jiǎn)單的并發(fā)聊天室的項(xiàng)目實(shí)戰(zhàn)
本文主要介紹了Go語(yǔ)言實(shí)現(xiàn)一個(gè)簡(jiǎn)單的并發(fā)聊天室的項(xiàng)目實(shí)戰(zhàn),文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03