Golang詳細講解常用Http庫及Gin框架的應用
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 檢查請求重定向
//檢查重定向函數(shù)
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數(shù)據(jù)處理
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)
//序列化后的字節(jié)切片,
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. 自然語言處理
可以調(diào)用阿里云的自然語言處理api進行數(shù)據(jù)的處理
3.1 使用Map處理
func mapUnmarshall() {
str := `{
"data": [
{
"id": 0,
"word": "請",
"tags": [
"基本詞-中文"
]
},
{
"id": 1,
"word": "輸入",
"tags": [
"基本詞-中文",
"產(chǎn)品類型修飾詞"
]
},
{
"id": 2,
"word": "文本",
"tags": [
"基本詞-中文",
"產(chǎn)品類型修飾詞"
]
}
]
}`
//map存儲數(shù)據(jù)都使用interface來存儲
m := make(map[string]any)
err := json.Unmarshal([]byte(str), &m)
if err != nil {
return
}
//如果需要取id為2的數(shù)據(jù),需要指明所取的值是一個切片 使用type assertion,包括取后續(xù)的數(shù)據(jù)的時候都要指定類型
fmt.Printf("%+v\n", m["data"].([]any)[2].(map[string]any)["tags"])
}
3.2 定義實體處理
//map存儲數(shù)據(jù)都使用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))
//放行,如果不釋放,后續(xù)就不能進行處理
c.Next()
//獲取到response對象
logger.Info("處理狀態(tài):", zap.Int("status", c.Writer.Status()))
}
func printHello(c *gin.Context) {
fmt.Println("hello:", c.Request.URL.Path)
//放行,如果不釋放,后續(xù)就不能進行處理
c.Next()
}
4.1.3 設置請求ID
func setRequestId(c *gin.Context) {
c.Set("requestId", rand.Int())
c.Next()
}
到此這篇關于Golang詳細講解常用Http庫及Gin框架的應用的文章就介紹到這了,更多相關Golang Http庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Go中time.RFC3339 時間格式化的實現(xiàn)
這篇文章主要介紹了Go中time.RFC3339 時間格式化的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01
Go語言實現(xiàn)一個簡單的并發(fā)聊天室的項目實戰(zhàn)
本文主要介紹了Go語言實現(xiàn)一個簡單的并發(fā)聊天室的項目實戰(zhàn),文中根據(jù)實例編碼詳細介紹的十分詳盡,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03

