From 03e698d928c335ff804c26068413f3293c9eb276 Mon Sep 17 00:00:00 2001 From: Jiun Lee Date: Tue, 30 Jul 2024 19:52:45 +0800 Subject: [PATCH] docs(hertz): function signature error (#1114) --- .../en/blog/releases/Hertz/release-v080.md | 4 +- .../en/docs/hertz/getting-started/_index.md | 2 +- .../basic-feature/binding-and-validate.md | 2 +- .../hertz/tutorials/basic-feature/client.md | 4 +- .../basic-feature/context/request.md | 230 ++++++++-------- .../basic-feature/context/response.md | 5 +- .../hertz/tutorials/basic-feature/engine.md | 10 +- .../basic-feature/middleware/_index.md | 6 +- .../basic-feature/middleware/csrf.md | 22 +- .../basic-feature/middleware/paseto.md | 24 +- .../basic-feature/protocol/websocket.md | 12 +- .../tutorials/basic-feature/unit-test.md | 10 +- .../tutorials/framework-exten/protocol.md | 12 +- .../framework-exten/response_writer.md | 24 +- .../tutorials/service-governance/sentinel.md | 2 +- .../service_discovery/etcd.md | 4 +- .../service_discovery/redis.md | 4 +- .../tutorials/service-migration/_index.md | 8 +- .../detail/cloudwego-sa-2022-2/index.md | 6 +- .../zh/blog/releases/Hertz/release-v060.md | 10 +- .../zh/blog/releases/Hertz/release-v080.md | 4 +- .../zh/docs/hertz/getting-started/_index.md | 2 +- .../basic-feature/binding-and-validate.md | 8 +- .../hertz/tutorials/basic-feature/client.md | 6 +- .../basic-feature/context/request.md | 248 +++++++++--------- .../basic-feature/context/response.md | 29 +- .../hertz/tutorials/basic-feature/engine.md | 18 +- .../hertz/tutorials/basic-feature/hooks.md | 4 +- .../basic-feature/middleware/_index.md | 6 +- .../basic-feature/middleware/casbin.md | 4 +- .../basic-feature/middleware/csrf.md | 40 +-- .../basic-feature/middleware/i18n.md | 14 +- .../tutorials/basic-feature/middleware/jwt.md | 4 +- .../basic-feature/middleware/keyauth.md | 30 +-- .../basic-feature/middleware/paseto.md | 30 +-- .../basic-feature/middleware/pprof.md | 4 +- .../basic-feature/middleware/recovery.md | 4 +- .../basic-feature/middleware/sentry.md | 2 +- .../basic-feature/middleware/swagger.md | 2 +- .../tutorials/basic-feature/protocol/http2.md | 16 +- .../tutorials/basic-feature/protocol/http3.md | 8 +- .../tutorials/basic-feature/protocol/tls.md | 6 +- .../basic-feature/protocol/websocket.md | 16 +- .../hertz/tutorials/basic-feature/render.md | 4 +- .../hertz/tutorials/basic-feature/route.md | 14 +- .../tutorials/basic-feature/unit-test.md | 10 +- .../tutorials/framework-exten/protocol.md | 10 +- .../framework-exten/response_writer.md | 8 +- .../docs/hertz/tutorials/observability/log.md | 4 +- .../tutorials/observability/monitoring.md | 2 +- .../tutorials/service-governance/sentinel.md | 2 +- .../service_discovery/etcd.md | 4 +- .../service_discovery/redis.md | 4 +- .../tutorials/service-migration/_index.md | 6 +- 54 files changed, 486 insertions(+), 488 deletions(-) diff --git a/content/en/blog/releases/Hertz/release-v080.md b/content/en/blog/releases/Hertz/release-v080.md index 971110f8fd..a920638a3a 100644 --- a/content/en/blog/releases/Hertz/release-v080.md +++ b/content/en/blog/releases/Hertz/release-v080.md @@ -37,7 +37,7 @@ Hertz added support for Partitioned Cookies in v0.8.0. You need to upgrade to > Currently, Hertz supports Partitioned Cookies, but does not yet support passing whether it is Partitioned through SetCookie. We will add this feature in the next minor version. Before that, you can refer to the following code example to use Partitioned Cookies. ``` -func SetPartitionedCookie(ctx *app.RequestContext, name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool) { +func SetPartitionedCookie(c *app.RequestContext, name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool) { if path == "" { path = "/" } @@ -54,7 +54,7 @@ func SetPartitionedCookie(ctx *app.RequestContext, name, value string, maxAge in cookie.SetHTTPOnly(httpOnly) cookie.SetSameSite(sameSite) cookie.SetPartitioned(true) - ctx.Response.Header.SetCookie(cookie) + c.Response.Header.SetCookie(cookie) } func main() { diff --git a/content/en/docs/hertz/getting-started/_index.md b/content/en/docs/hertz/getting-started/_index.md index e0c471203b..cdce58bb0c 100644 --- a/content/en/docs/hertz/getting-started/_index.md +++ b/content/en/docs/hertz/getting-started/_index.md @@ -39,7 +39,7 @@ After completing the environment preparation, you can quickly start the Hertz Se h := server.Default() h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"message": "pong"}) + c.JSON(consts.StatusOK, utils.H{"message": "pong"}) }) h.Spin() diff --git a/content/en/docs/hertz/tutorials/basic-feature/binding-and-validate.md b/content/en/docs/hertz/tutorials/basic-feature/binding-and-validate.md index ac0ee470bb..3e4e98a837 100644 --- a/content/en/docs/hertz/tutorials/basic-feature/binding-and-validate.md +++ b/content/en/docs/hertz/tutorials/basic-feature/binding-and-validate.md @@ -45,7 +45,7 @@ func main() { > hertz version >= v0.7.0 | API | Description | -| :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +|:----------------------| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ctx.BindAndValidate | Use the following go-tag for parameter binding, and do a parameter validation after successful binding (if there is a validation tag) | | ctx.Bind | Same as `BindAndValidate` but without parameter validation | | ctx.BindQuery | Bind all Query parameters, which is equivalent to declaring a `query` tag for each field, for scenarios where no tag is written | diff --git a/content/en/docs/hertz/tutorials/basic-feature/client.md b/content/en/docs/hertz/tutorials/basic-feature/client.md index 25e63ad5f1..997c9d8773 100644 --- a/content/en/docs/hertz/tutorials/basic-feature/client.md +++ b/content/en/docs/hertz/tutorials/basic-feature/client.md @@ -43,7 +43,7 @@ func performRequest() { func main() { h := server.New(server.WithHostPorts(":8080")) h.GET("/hello", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, "hello hertz") + c.JSON(consts.StatusOK, "hello hertz") }) go performRequest() h.Spin() @@ -749,7 +749,7 @@ The `UseAsLast` function adds the middleware to the end of the client middleware If the client middleware chain has already set the last middleware before, the `UseAsLast` function will return an `errorLastMiddlewareExist` error. Therefore, to ensure that the last middleware in the client middleware chain is empty, you can first use the [TakeOutLastMiddleware](#takeoutlastmiddleware) function to clear the last middleware in the client middleware chain. -> Note: The `UseAsLast` function sets the middleware in `c.lastMiddleware`, while the middleware chain set using the [Use](#use) function is stored in `c.mws`. The two functions are relatively independent. `c.lastMiddleware` is executed only at the end of the client middleware chain. Therefore, the `UseAsLast` function can be called before or after the [Use](#use) function. +> Note: The `UseAsLast` function sets the middleware in `ctx.lastMiddleware`, while the middleware chain set using the [Use](#use) function is stored in `ctx.mws`. The two functions are relatively independent. `ctx.lastMiddleware` is executed only at the end of the client middleware chain. Therefore, the `UseAsLast` function can be called before or after the [Use](#use) function. Function Signature: diff --git a/content/en/docs/hertz/tutorials/basic-feature/context/request.md b/content/en/docs/hertz/tutorials/basic-feature/context/request.md index 997ce3e958..b3ea55a11f 100644 --- a/content/en/docs/hertz/tutorials/basic-feature/context/request.md +++ b/content/en/docs/hertz/tutorials/basic-feature/context/request.md @@ -162,7 +162,7 @@ Example Code: // GET http://example.com/user?name=bar h.GET("/user", func(ctx context.Context, c *app.RequestContext) { name := c.Query("name") // name == "bar" - id := ctx.Query("id") // id == "" + id := c.Query("id") // id == "" }) ``` @@ -181,9 +181,9 @@ Example Code: ```go // GET http://example.com/user?name=bar&&age= h.GET("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.DefaultQuery("name", "tom") // name == "bar" - id := ctx.DefaultQuery("id", "123") // id == "123" - age := ctx.DefaultQuery("age", "45") // age == "" + name := c.DefaultQuery("name", "tom") // name == "bar" + id := c.DefaultQuery("id", "123") // id == "123" + age := c.DefaultQuery("age", "45") // age == "" }) ``` @@ -202,9 +202,9 @@ Example Code: ```go // GET http://example.com/user?name=bar&&age= h.GET("/user", func(ctx context.Context, c *app.RequestContext) { - name, hasName := ctx.GetQuery("name") // name == "bar", hasName == true - id, hasId := ctx.GetQuery("id") // id == "", hasId == false - age, hasAge := ctx.GetQuery("age") // age == "", hasAge == true + name, hasName := c.GetQuery("name") // name == "bar", hasName == true + id, hasId := c.GetQuery("id") // id == "", hasId == false + age, hasAge := c.GetQuery("age") // age == "", hasAge == true }) ``` @@ -247,7 +247,7 @@ Example Code: ```go // GET http://example.com/user?name=bar&&age=&&pets=dog&&pets=cat h.GET("/user", func(ctx context.Context, c *app.RequestContext) { - args := ctx.QueryArgs() + args := c.QueryArgs() // get information from args s := args.String() // s == "name=bar&age=&pets=dog&pets=cat" @@ -388,15 +388,15 @@ Example Code: ```go hertz.GET("/example", func(ctx context.Context, c *app.RequestContext) { - ctx.Request.Header.Add("hertz1", "value1") - ctx.Request.Header.Add("hertz1", "value2") - ctx.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded")) - contentType1 := ctx.Request.Header.ContentType() + c.Request.Header.Add("hertz1", "value1") + c.Request.Header.Add("hertz1", "value2") + c.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded")) + contentType1 := c.Request.Header.ContentType() // contentType1 == []byte("application/x-www-form-urlencoded") - ctx.Request.Header.Add("Content-Type", "application/json; charset=utf-8") - hertz1 := ctx.Request.Header.GetAll("hertz1") + c.Request.Header.Add("Content-Type", "application/json; charset=utf-8") + hertz1 := c.Request.Header.GetAll("hertz1") // hertz1 == []string{"value1", "value2"} - contentType2 := ctx.Request.Header.ContentType() + contentType2 := c.Request.Header.ContentType() // contentType2 == []byte("application/json; charset=utf-8") }) ``` @@ -417,15 +417,15 @@ Example Code: ```go hertz.GET("/example", func(ctx context.Context, c *app.RequestContext) { - ctx.Request.Header.Set("hertz1", "value1") - ctx.Request.Header.Set("hertz1", "value2") - ctx.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded")) - contentType1 := ctx.Request.Header.ContentType() + c.Request.Header.Set("hertz1", "value1") + c.Request.Header.Set("hertz1", "value2") + c.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded")) + contentType1 := c.Request.Header.ContentType() // contentType1 == []byte("application/x-www-form-urlencoded") - ctx.Request.Header.Set("Content-Type", "application/json; charset=utf-8") - hertz1 := ctx.Request.Header.GetAll("hertz1") + c.Request.Header.Set("Content-Type", "application/json; charset=utf-8") + hertz1 := c.Request.Header.GetAll("hertz1") // hertz1 == []string{"value2"} - contentType2 := ctx.Request.Header.ContentType() + contentType2 := c.Request.Header.ContentType() // contentType2 == []byte("application/json; charset=utf-8") }) ``` @@ -444,8 +444,8 @@ Example Code: ```go hertz.GET("/example", func(ctx context.Context, c *app.RequestContext) { - ctx.Request.Header.Set("hertz1", "value1") - header := ctx.Request.Header.Header() + c.Request.Header.Set("hertz1", "value1") + header := c.Request.Header.Header() // header == []byte("GET /example HTTP/1.1 //User-Agent: PostmanRuntime-ApipostRuntime/1.1.0 //Host: localhost:8888 @@ -471,8 +471,8 @@ Example Code: ```go hertz.GET("/example", func(ctx context.Context, c *app.RequestContext) { - ctx.Request.Header.Set("hertz1", "value1") - header := ctx.Request.Header.String() + c.Request.Header.Set("hertz1", "value1") + header := c.Request.Header.String() // header == "GET /example HTTP/1.1 //User-Agent: PostmanRuntime-ApipostRuntime/1.1.0 //Host: localhost:8888 @@ -498,11 +498,11 @@ Example Code: ```go hertz.GET("/example", func(ctx context.Context, c *app.RequestContext) { - ctx.Request.Header.Add("Hertz1", "value1") - ctx.Request.Header.Add("Hertz1", "value2") + c.Request.Header.Add("Hertz1", "value1") + c.Request.Header.Add("Hertz1", "value2") var hertzString []string - ctx.Request.Header.VisitAll(func(key, value []byte) { + c.Request.Header.VisitAll(func(key, value []byte) { if string(key) == "Hertz1" { hertzString = append(hertzString, string(value)) } @@ -526,7 +526,7 @@ Example Code: ```go // POST http://example.com/user h.Any("/user", func(ctx context.Context, c *app.RequestContext) { - method := ctx.Method() // method == []byte("POST") + method := c.Method() // method == []byte("POST") }) ``` @@ -546,7 +546,7 @@ Example Code: // POST http://example.com/user // Content-Type: application/json h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - contentType := ctx.ContentType() // contentType == []byte("application/json") + contentType := c.ContentType() // contentType == []byte("application/json") }) ``` @@ -569,10 +569,10 @@ Example Code: // If-Modified-Since: Wed, 21 Oct 2023 07:28:00 GMT h.Post("/user", func(ctx context.Context, c *app.RequestContext) { t2022, _ := time.Parse(time.RFC1123, "Wed, 21 Oct 2022 07:28:00 GMT") - ifModifiedSince := ctx.IfModifiedSince(t2022) // ifModifiedSince == false + ifModifiedSince := c.IfModifiedSince(t2022) // ifModifiedSince == false t2024, _ := time.Parse(time.RFC1123, "Wed, 21 Oct 2024 07:28:00 GMT") - ifModifiedSince = ctx.IfModifiedSince(t2024) // ifModifiedSince == true + ifModifiedSince = c.IfModifiedSince(t2024) // ifModifiedSince == true }) ``` @@ -592,9 +592,9 @@ Example Code: // POST http://example.com/user // Cookie: foo_cookie=choco; bar_cookie=strawberry h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - fCookie := ctx.Cookie("foo_cookie") // fCookie == []byte("choco") - bCookie := ctx.Cookie("bar_cookie") // bCookie == []byte("strawberry") - noneCookie := ctx.Cookie("none_cookie") // noneCookie == nil + fCookie := c.Cookie("foo_cookie") // fCookie == []byte("choco") + bCookie := c.Cookie("bar_cookie") // bCookie == []byte("strawberry") + noneCookie := c.Cookie("none_cookie") // noneCookie == nil }) ``` @@ -614,7 +614,7 @@ Example Code: // POST http://example.com/user // User-Agent: Chrome/51.0.2704.103 Safari/537.36 h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - ua := ctx.UserAgent() // ua == []byte("Chrome/51.0.2704.103 Safari/537.36") + ua := c.UserAgent() // ua == []byte("Chrome/51.0.2704.103 Safari/537.36") }) ``` @@ -634,7 +634,7 @@ Example Code: // POST http://example.com/user // Say-Hello: hello h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - customHeader := ctx.GetHeader("Say-Hello") // customHeader == []byte("hello") + customHeader := c.GetHeader("Say-Hello") // customHeader == []byte("hello") }) ``` @@ -754,7 +754,7 @@ Example Code: // Content-Type: application/json // {"pet":"cat"} h.Post("/pet", func(ctx context.Context, c *app.RequestContext) { - data, err := ctx.Body() // data == []byte("{\"pet\":\"cat\"}") , err == nil + data, err := c.Body() // data == []byte("{\"pet\":\"cat\"}") , err == nil }) ``` @@ -776,7 +776,7 @@ Example Code: // abcdefg h := server.Default(server.WithStreamBody(true)) h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - sr := ctx.RequestBodyStream() + sr := c.RequestBodyStream() data, _ := io.ReadAll(sr) // data == []byte("abcdefg") }) ``` @@ -801,7 +801,7 @@ Example Code: // Content-Disposition: form-data; name="name" // tom h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - form, err := ctx.MultipartForm() + form, err := c.MultipartForm() name := form.Value["name"][0] // name == "tom" }) ``` @@ -826,7 +826,7 @@ Example Code: // Content-Disposition: form-data; name="name" // tom h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.PostForm("name") // name == "tom" + name := c.PostForm("name") // name == "tom" }) ``` @@ -850,8 +850,8 @@ Example Code: // Content-Disposition: form-data; name="name" // tom h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.PostForm("name", "jack") // name == "tom" - age := ctx.PostForm("age", "10") // age == "10" + name := c.PostForm("name", "jack") // name == "tom" + age := c.PostForm("age", "10") // age == "10" }) ``` @@ -872,7 +872,7 @@ Example Code: // Content-Type: application/x-www-form-urlencoded // name=tom&pet=cat&pet=dog h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - args := ctx.PostArgs() + args := c.PostArgs() name := args.Peek("name") // name == "tom" var pets []string @@ -906,8 +906,8 @@ Example Code: // Content-Type: application/x-www-form-urlencoded // age=10 h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.FormValue("name") // name == []byte("tom"), get by QueryArgs - age := ctx.FormValue("age") // age == []byte("10"), get by PostArgs + name := c.FormValue("name") // name == []byte("tom"), get by QueryArgs + age := c.FormValue("age") // age == []byte("10"), get by PostArgs }) // POST http://example.com/user @@ -915,7 +915,7 @@ h.POST("/user", func(ctx context.Context, c *app.RequestContext) { // Content-Disposition: form-data; name="name" // tom h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.FormValue("name") // name == []byte("tom"), get by MultipartForm + name := c.FormValue("name") // name == []byte("tom"), get by MultipartForm }) ``` @@ -938,7 +938,7 @@ Example Code: // 10 h.POST("/user", func(ctx context.Context, c *app.RequestContext) { // only return multipart form value - ctx.SetFormValueFunc(func(rc *app.RequestContext, s string) []byte { + c.SetFormValueFunc(func(rc *app.RequestContext, s string) []byte { mf, err := rc.MultipartForm() if err == nil && mf.Value != nil { vv := mf.Value[s] @@ -949,8 +949,8 @@ h.POST("/user", func(ctx context.Context, c *app.RequestContext) { return nil }) - name := ctx.FormValue("name") // name == nil - age := ctx.FormValue("age") // age == []byte("10") + name := c.FormValue("name") // name == nil + age := c.FormValue("age") // age == []byte("10") }) ``` @@ -981,7 +981,7 @@ Example Code: // Content-Type: multipart/form-data; // Content-Disposition: form-data; name="avatar"; filename="abc.jpg" h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - form, err := ctx.MultipartForm() + form, err := c.MultipartForm() avatarFile := form.File["avatar"][0] // avatarFile.Filename == "abc.jpg" }) ``` @@ -1003,7 +1003,7 @@ Example Code: // Content-Type: multipart/form-data; // Content-Disposition: form-data; name="avatar"; filename="abc.jpg" h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - avatarFile, err := ctx.FormFile("avatar") // avatarFile.Filename == "abc.jpg", err == nil + avatarFile, err := c.FormFile("avatar") // avatarFile.Filename == "abc.jpg", err == nil }) ``` @@ -1024,9 +1024,9 @@ Example Code: // Content-Type: multipart/form-data; // Content-Disposition: form-data; name="avatar"; filename="abc.jpg" h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - avatarFile, err := ctx.FormFile("avatar") // avatarFile.Filename == "abc.jpg", err == nil + avatarFile, err := c.FormFile("avatar") // avatarFile.Filename == "abc.jpg", err == nil // save file - ctx.SaveUploadedFile(avatarFile, avatarFile.Filename) // save file "abc.jpg" + c.SaveUploadedFile(avatarFile, avatarFile.Filename) // save file "abc.jpg" }) ``` @@ -1062,70 +1062,70 @@ Example Code: ```go h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - ctx.Set("version1", "v1") - v := ctx.Value("version1") // v == interface{}(string) "v1" + c.Set("version1", "v1") + v := c.Value("version1") // v == interface{}(string) "v1" - ctx.Set("version2", "v2") - v, exists := ctx.Get("version2") // v == interface{}(string) "v2", exists == true - v, exists = ctx.Get("pet") // v == interface{} nil, exists == false + c.Set("version2", "v2") + v, exists := c.Get("version2") // v == interface{}(string) "v2", exists == true + v, exists = c.Get("pet") // v == interface{} nil, exists == false - ctx.Set("version3", "v3") - v := ctx.MustGet("version3") // v == interface{}(string) "v3" + c.Set("version3", "v3") + v := c.MustGet("version3") // v == interface{}(string) "v3" - ctx.Set("version4", "v4") - vString := ctx.GetString("version4") // vString == "v4" + c.Set("version4", "v4") + vString := c.GetString("version4") // vString == "v4" - ctx.Set("isAdmin", true) - vBool := ctx.GetBool("isAdmin") // vBool == true + c.Set("isAdmin", true) + vBool := c.GetBool("isAdmin") // vBool == true - ctx.Set("age1", 20) - vInt := ctx.GetInt("age1") // vInt == 20 + c.Set("age1", 20) + vInt := c.GetInt("age1") // vInt == 20 - ctx.Set("age2", int32(20)) - vInt32 := ctx.GetInt32("age2") // vInt32 == 20 + c.Set("age2", int32(20)) + vInt32 := c.GetInt32("age2") // vInt32 == 20 - ctx.Set("age3", int64(20)) - vInt64 := ctx.GetInt64("age3") // vInt64 == 20 + c.Set("age3", int64(20)) + vInt64 := c.GetInt64("age3") // vInt64 == 20 - ctx.Set("age4", uint(20)) - vUInt := ctx.GetUint("age4") // vUInt == 20 + c.Set("age4", uint(20)) + vUInt := c.GetUint("age4") // vUInt == 20 - ctx.Set("age5", uint32(20)) - vUInt32 := ctx.GetUint32("age5") // vUInt32 == 20 + c.Set("age5", uint32(20)) + vUInt32 := c.GetUint32("age5") // vUInt32 == 20 - ctx.Set("age6", uint64(20)) - vUInt64 := ctx.GetUint64("age6") // vUInt64 == 20 + c.Set("age6", uint64(20)) + vUInt64 := c.GetUint64("age6") // vUInt64 == 20 - ctx.Set("age7", float32(20.1)) - vFloat32 := ctx.GetFloat32("age7") // vFloat32 == 20.1 + c.Set("age7", float32(20.1)) + vFloat32 := c.GetFloat32("age7") // vFloat32 == 20.1 - ctx.Set("age8", 20.1) - vFloat64 := ctx.GetFloat64("age8") // vFloat64 == 20.1 + c.Set("age8", 20.1) + vFloat64 := c.GetFloat64("age8") // vFloat64 == 20.1 t2022, _ := time.Parse(time.RFC1123, "Wed, 21 Oct 2022 07:28:00 GMT") - ctx.Set("birthday", t2022) - vTime := ctx.GetTime("birthday") // vTime == t2022 + c.Set("birthday", t2022) + vTime := c.GetTime("birthday") // vTime == t2022 - ctx.Set("duration", time.Minute) - vDuration := ctx.GetDuration("duration") // vDuration == time.Minute + c.Set("duration", time.Minute) + vDuration := c.GetDuration("duration") // vDuration == time.Minute - ctx.Set("pet", []string{"cat", "dog"}) - vStringSlice := ctx.GetStringSlice("pet") // vStringSlice == []string{"cat", "dog"} + c.Set("pet", []string{"cat", "dog"}) + vStringSlice := c.GetStringSlice("pet") // vStringSlice == []string{"cat", "dog"} - ctx.Set("info1", map[string]interface{}{"name": "tom"}) - vStringMap := ctx.GetStringMap("info1") // vStringMap == map[string]interface{}{"name": "tom"} + c.Set("info1", map[string]interface{}{"name": "tom"}) + vStringMap := c.GetStringMap("info1") // vStringMap == map[string]interface{}{"name": "tom"} - ctx.Set("info2", map[string]string{"name": "tom"}) - vStringMapString := ctx.GetStringMapString("info2") + c.Set("info2", map[string]string{"name": "tom"}) + vStringMapString := c.GetStringMapString("info2") // vStringMapString == map[string]string{}{"name": "tom"} - ctx.Set("smss", map[string][]string{"pets": {"cat", "dog"}}) - vStringMapStringSlice := ctx.GetStringMapStringSlice("smss") + c.Set("smss", map[string][]string{"pets": {"cat", "dog"}}) + vStringMapStringSlice := c.GetStringMapStringSlice("smss") // vStringMapStringSlice == map[string][]string{"pets": {"cat", "dog"}} - ctx.Set("duration", time.Minute) - ctx.Set("version", "v1") - ctx.ForEachKey(func(k string, v interface{}) { + c.Set("duration", time.Minute) + c.Set("version", "v1") + c.ForEachKey(func(k string, v interface{}) { // 1. k == "duration", v == interface{}(time.Duration) time.Minute // 2. k == "version", v == interface{}(string) "v1" }) @@ -1160,7 +1160,7 @@ Example Code: ```go h.POST("/user", func(ctx context.Context, c *app.RequestContext) { c.Next(ctx) - v := ctx.GetString("version") // v == "v1" + v := c.GetString("version") // v == "v1" }, func(ctx context.Context, c *app.RequestContext) { c.Set("version", "v1") }) @@ -1183,7 +1183,7 @@ middleware1 := func(ctx context.Context, c *app.RequestContext) { } handler1 := func(ctx context.Context, c *app.RequestContext) { - handlers := ctx.Handlers() // []Handler{middleware1, handler1} + handlers := c.Handlers() // []Handler{middleware1, handler1} } h.POST("/user", middleware1, handler1) @@ -1203,7 +1203,7 @@ Example Code: ```go middleware1 := func(ctx context.Context, c *app.RequestContext) { - lastHandler := ctx.Handler() // lastHandler == handler1 + lastHandler := c.Handler() // lastHandler == handler1 } handler1 := func(ctx context.Context, c *app.RequestContext) { @@ -1230,11 +1230,11 @@ handler1 := func(ctx context.Context, c *app.RequestContext) { } handler := func(ctx context.Context, c *app.RequestContext) { - hc := app.HandlersChain{ctx.Handlers()[0], handler1} // append handler1 into handlers chain - ctx.SetHandlers(hc) + hc := app.HandlersChain{c.Handlers()[0], handler1} // append handler1 into handlers chain + c.SetHandlers(hc) c.Next(ctx) - current := ctx.GetString("current") // current == "handler1" - ctx.String(consts.StatusOK, current) + current := c.GetString("current") // current == "handler1" + c.String(consts.StatusOK, current) } h.POST("/user", handler) @@ -1258,7 +1258,7 @@ package main func main() { h := server.New() h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - hn := ctx.HandlerName() // hn == "main.main.func1" + hn := c.HandlerName() // hn == "main.main.func1" }) } ``` @@ -1277,9 +1277,9 @@ Example Code: ```go h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - index := ctx.GetIndex() // index == 0 + index := c.GetIndex() // index == 0 }, func(ctx context.Context, c *app.RequestContext) { - index := ctx.GetIndex() // index == 1 + index := c.GetIndex() // index == 1 }) ``` @@ -1318,7 +1318,7 @@ Example Code: ```go h.POST("/user", func(ctx context.Context, c *app.RequestContext) { c.Abort() - isAborted := ctx.IsAborted() // isAborted == true + isAborted := c.IsAborted() // isAborted == true }, func(ctx context.Context, c *app.RequestContext) { // will not execute }) @@ -1359,7 +1359,7 @@ Example Code: // X-Forwarded-For: 20.20.20.20, 30.30.30.30 // X-Real-IP: 10.10.10.10 h.Use(func(ctx context.Context, c *app.RequestContext) { - ip := ctx.ClientIP() // 20.20.20.20 + ip := c.ClientIP() // 20.20.20.20 }) ``` @@ -1384,11 +1384,11 @@ Example Code: // X-Forwarded-For: 30.30.30.30 h.POST("/user", func(ctx context.Context, c *app.RequestContext) { // method 1 - customClientIPFunc := func(ctx *app.RequestContext) string { + customClientIPFunc := func(c *app.RequestContext) string { return "127.0.0.1" } - ctx.SetClientIPFunc(customClientIPFunc) - ip := ctx.ClientIP() // ip == "127.0.0.1" + c.SetClientIPFunc(customClientIPFunc) + ip := c.ClientIP() // ip == "127.0.0.1" // method 2 _, cidr, _ := net.ParseCIDR("127.0.0.1/32") @@ -1396,9 +1396,9 @@ h.POST("/user", func(ctx context.Context, c *app.RequestContext) { RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, TrustedCIDRs: []*net.IPNet{cidr}, } - ctx.SetClientIPFunc(app.ClientIPWithOption(opts)) + c.SetClientIPFunc(app.ClientIPWithOption(opts)) - ip = ctx.ClientIP() // ip == "30.30.30.30" + ip = c.ClientIP() // ip == "30.30.30.30" }) ``` @@ -1422,7 +1422,7 @@ Example Code: ```go h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - ctx1 := ctx.Copy() + ctx1 := c.Copy() go func(context *app.RequestContext) { // safely }(ctx1) diff --git a/content/en/docs/hertz/tutorials/basic-feature/context/response.md b/content/en/docs/hertz/tutorials/basic-feature/context/response.md index 7e32377796..3ddfff1e89 100644 --- a/content/en/docs/hertz/tutorials/basic-feature/context/response.md +++ b/content/en/docs/hertz/tutorials/basic-feature/context/response.md @@ -142,8 +142,7 @@ Example Code: ```go h.GET("/user", func(ctx context.Context, c *app.RequestContext) { - c.NotFound() - // Status Code: 404 + c.NotFound() // Status Code: 404 }) ``` @@ -253,7 +252,7 @@ and subject to future changes. Example Code: ```go -func SetPartitionedCookie(ctx *app.RequestContext, name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool) { +func SetPartitionedCookie(c *app.RequestContext, name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool) { if path == "" { path = "/" } diff --git a/content/en/docs/hertz/tutorials/basic-feature/engine.md b/content/en/docs/hertz/tutorials/basic-feature/engine.md index 4f27f38890..019f7fb823 100644 --- a/content/en/docs/hertz/tutorials/basic-feature/engine.md +++ b/content/en/docs/hertz/tutorials/basic-feature/engine.md @@ -32,7 +32,7 @@ type Hertz struct { | WithUnescapePathValues | true | If true, the request path will be escaped automatically (eg. '%2F' -> '/'). If UseRawPath is false (the default), UnescapePathValues is true, because URI().Path() will be used and it is already escaped. To set WithUnescapePathValues to false, you need to set WithUseRawPath to true | | WithUseRawPath | false | If true, the original path will be used to match the route | | WithHandleMethodNotAllowed | false | If true when the current path cannot match any method, the server will check whether other methods are registered with the route of the current path, and if exist other methods, it will respond "Method Not Allowed" and return the status code 405; if not, it will use the handler of NotFound to handle it | -| WithDisablePreParseMultipartForm | false | If true, the multipart form will not be preprocessed. The body can be obtained via ctx.Request.Body() and then can be processed by user | +| WithDisablePreParseMultipartForm | false | If true, the multipart form will not be preprocessed. The body can be obtained via c.Request.Body() and then can be processed by user | | WithStreamBody | false | If true, the body will be handled by stream processing | | WithNetwork | "tcp" | Set the network protocol, optional: tcp,udp,unix(unix domain socket) | | WithExitWaitTime | 5s | Set the graceful exit time. the Server will stop connection establishment for new requests and set the Connection: Close header for each request after closing. When the set time is reached, Server will to be closed. the Server can be closed early when all connections have been closed | @@ -314,7 +314,7 @@ Two methods are provided: }() go func() { - <-ctx.Finished() + <-c..Finished() fmt.Println("request process end") }() }) @@ -336,7 +336,7 @@ Two methods are provided: }() go func() { - <-ctx.Finished() + <-c..Finished() fmt.Println("request process end") }() }) @@ -516,13 +516,13 @@ Example Code: ```go func getHandler() app.HandlerFunc { return func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "get handler") + c.String(consts.StatusOK, "get handler") } } func postHandler() app.HandlerFunc { return func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "post handler") + c.String(consts.StatusOK, "post handler") } } diff --git a/content/en/docs/hertz/tutorials/basic-feature/middleware/_index.md b/content/en/docs/hertz/tutorials/basic-feature/middleware/_index.md index 33650c66b3..34c5eaa5c3 100644 --- a/content/en/docs/hertz/tutorials/basic-feature/middleware/_index.md +++ b/content/en/docs/hertz/tutorials/basic-feature/middleware/_index.md @@ -247,6 +247,6 @@ A server-side middleware is a handler, and the related operations of the handler The server-side middleware will be executed in the order defined, if you want to terminate the middleware call quickly, you can use the following methods, noting that **the current middleware will still execute**. -- `c.Abort()`:terminate subsequent calls -- `c.AbortWithMsg(msg string, statusCode int)`:terminates subsequent calls and sets the body and status code for the Response -- `c.AbortWithStatus(code int)`:terminates subsequent calls and sets the status code +- `ctx.Abort()`:terminate subsequent calls +- `ctx.AbortWithMsg(msg string, statusCode int)`:terminates subsequent calls and sets the body and status code for the Response +- `ctx.AbortWithStatus(code int)`:terminates subsequent calls and sets the status code diff --git a/content/en/docs/hertz/tutorials/basic-feature/middleware/csrf.md b/content/en/docs/hertz/tutorials/basic-feature/middleware/csrf.md index 7ecd442677..3df64a27bd 100644 --- a/content/en/docs/hertz/tutorials/basic-feature/middleware/csrf.md +++ b/content/en/docs/hertz/tutorials/basic-feature/middleware/csrf.md @@ -193,7 +193,7 @@ func myErrFunc(ctx context.Context, c *app.RequestContext) { c.String(400, err.Error()) c.Abort() } - ctx.AbortWithMsg(ctx.Errors.Last().Error(), http.StatusBadRequest) + c.AbortWithMsg(c.Errors.Last().Error(), http.StatusBadRequest) } func main() { @@ -204,10 +204,10 @@ func main() { h.Use(csrf.New(csrf.WithErrorFunc(myErrFunc))) h.GET("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, csrf.GetToken(ctx)) + c.String(200, csrf.GetToken(ctx)) }) h.POST("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "CSRF token is valid") + c.String(200, "CSRF token is valid") }) h.Spin() @@ -253,10 +253,10 @@ func main() { h.Use(csrf.New(csrf.WithKeyLookUp("form:csrf"))) h.GET("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, csrf.GetToken(ctx)) + c.String(200, csrf.GetToken(ctx)) }) h.POST("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "CSRF token is valid") + c.String(200, "CSRF token is valid") }) h.Spin() @@ -291,8 +291,8 @@ import ( "github.com/hertz-contrib/sessions/cookie" ) -func isPostMethod(_ context.Context, ctx *app.RequestContext) bool { - if string(ctx.Method()) == "POST" { +func isPostMethod(_ context.Context, c *app.RequestContext) bool { + if string(c.Method()) == "POST" { return true } else { return false @@ -309,7 +309,7 @@ func main() { h.Use(csrf.New(csrf.WithNext(isPostMethod))) h.POST("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "success even no csrf-token in header") + c.String(200, "success even no csrf-token in header") }) h.Spin() } @@ -356,7 +356,7 @@ import ( ) func myExtractor(ctx context.Context, c *app.RequestContext) (string, error) { - token := ctx.FormValue("csrf-token") + token := c.FormValue("csrf-token") if token == nil { return "", errors.New("missing token in form-data") } @@ -371,10 +371,10 @@ func main() { h.Use(csrf.New(csrf.WithExtractor(myExtractor))) h.GET("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, csrf.GetToken(ctx)) + c.String(200, csrf.GetToken(ctx)) }) h.POST("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "CSRF token is valid") + c.String(200, "CSRF token is valid") }) h.Spin() diff --git a/content/en/docs/hertz/tutorials/basic-feature/middleware/paseto.md b/content/en/docs/hertz/tutorials/basic-feature/middleware/paseto.md index 27351610d0..d94697c2a3 100644 --- a/content/en/docs/hertz/tutorials/basic-feature/middleware/paseto.md +++ b/content/en/docs/hertz/tutorials/basic-feature/middleware/paseto.md @@ -164,7 +164,7 @@ func main() { }) h.POST("/paseto", paseto.New(paseto.WithNext(next)), func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "token is valid") + c.String(consts.StatusOK, "token is valid") }) go performRequest() @@ -254,7 +254,7 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.GET("/paseto/witherrorfunc", func(ctx context.Context, c *app.RequestContext) { @@ -269,11 +269,11 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.POST("/paseto", paseto.New(paseto.WithErrorFunc(handler)), func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "token is valid") + c.String(consts.StatusOK, "token is valid") }) go performRequest() @@ -363,7 +363,7 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.GET("/paseto/withnosecret", func(ctx context.Context, c *app.RequestContext) { @@ -378,11 +378,11 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.POST("/paseto", paseto.New(paseto.WithSuccessHandler(handler)), func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "token is valid") + c.String(consts.StatusOK, "token is valid") }) go performRequest() @@ -451,11 +451,11 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.POST("/paseto", paseto.New(paseto.WithKeyLookUp("form:Authorization")), func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "token is valid") + c.String(consts.StatusOK, "token is valid") }) go performRequest() @@ -511,7 +511,7 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.POST("/paseto", paseto.New(paseto.WithTokenPrefix("Bearer ")), func(ctx context.Context, c *app.RequestContext) { @@ -595,7 +595,7 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.GET("/paseto/wrong-issuer", func(ctx context.Context, c *app.RequestContext) { now := time.Now() @@ -608,7 +608,7 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) parseFunc, _ := paseto.NewV4PublicParseFunc(paseto.DefaultPublicKey, []byte(paseto.DefaultImplicit), paseto.WithIssuer("CloudWeGo-issuer")) diff --git a/content/en/docs/hertz/tutorials/basic-feature/protocol/websocket.md b/content/en/docs/hertz/tutorials/basic-feature/protocol/websocket.md index 18ba75540d..3485f50ebd 100644 --- a/content/en/docs/hertz/tutorials/basic-feature/protocol/websocket.md +++ b/content/en/docs/hertz/tutorials/basic-feature/protocol/websocket.md @@ -158,14 +158,14 @@ If Error is nil, then use the API provided by Hertz to generate the HTTP error r Function signatures: ```go -func(ctx *app.RequestContext, status int, reason error) +func(c *app.RequestContext, status int, reason error) ``` Sample Code: ```go var upgrader = websocket.HertzUpgrader{ - Error: func(ctx *app.RequestContext, status int, reason error) { + Error: func(c *app.RequestContext, status int, reason error) { c.Response.Header.Set("Sec-Websocket-Version", "13") c.AbortWithMsg(reason.Error(), status) }, @@ -182,14 +182,14 @@ prevent cross-site request forgery. Function signatures: ```go -func(ctx *app.RequestContext) bool +func(c *app.RequestContext) bool ``` Default Implementation: ```go -func fastHTTPCheckSameOrigin(ctx *app.RequestContext) bool { - origin := ctx.Request.Header.Peek("Origin") +func fastHTTPCheckSameOrigin(c *app.RequestContext) bool { + origin := c.Request.Header.Peek("Origin") if len(origin) == 0 { return true } @@ -197,7 +197,7 @@ func fastHTTPCheckSameOrigin(ctx *app.RequestContext) bool { if err != nil { return false } - return equalASCIIFold(u.Host, b2s(ctx.Host())) + return equalASCIIFold(u.Host, b2s(c.Host())) } ``` diff --git a/content/en/docs/hertz/tutorials/basic-feature/unit-test.md b/content/en/docs/hertz/tutorials/basic-feature/unit-test.md index 1f3b111016..b2549a9554 100644 --- a/content/en/docs/hertz/tutorials/basic-feature/unit-test.md +++ b/content/en/docs/hertz/tutorials/basic-feature/unit-test.md @@ -43,15 +43,15 @@ func TestCreateUtRequestContext(t *testing.T) { path := "/hey/dy" headerKey := "Connection" headerValue := "close" - ctx := ut.CreateUtRequestContext(method, path, &ut.Body{Body: bytes.NewBufferString(body), Len: len(body)}, + c := ut.CreateUtRequestContext(method, path, &ut.Body{Body: bytes.NewBufferString(body), Len: len(body)}, ut.Header{Key: headerKey, Value: headerValue}) - assert.DeepEqual(t, method, string(ctx.Method())) - assert.DeepEqual(t, path, string(ctx.Path())) - body1, err := ctx.Body() + assert.DeepEqual(t, method, string(c.Method())) + assert.DeepEqual(t, path, string(c.Path())) + body1, err := c.Body() assert.DeepEqual(t, nil, err) assert.DeepEqual(t, body, string(body1)) - assert.DeepEqual(t, headerValue, string(ctx.GetHeader(headerKey))) + assert.DeepEqual(t, headerValue, string(c.GetHeader(headerKey))) } ``` diff --git a/content/en/docs/hertz/tutorials/framework-exten/protocol.md b/content/en/docs/hertz/tutorials/framework-exten/protocol.md index ecceb8b8ab..5b51141a4b 100644 --- a/content/en/docs/hertz/tutorials/framework-exten/protocol.md +++ b/content/en/docs/hertz/tutorials/framework-exten/protocol.md @@ -180,20 +180,20 @@ type myServer struct { suite.Core } -func (m myServer) Serve(c context.Context, conn network.Conn) error { +func (m myServer) Serve(ctx context.Context, conn network.Conn) error { firstThreeBytes, _ := conn.Peek(3) if !bytes.Equal(firstThreeBytes, []byte("GET")) { return errors.NewPublic("not a GET method") } - ctx := m.GetCtxPool().Get().(*app.RequestContext) + c := m.GetCtxPool().Get().(*app.RequestContext) defer func() { - m.GetCtxPool().Put(ctx) + m.GetCtxPool().Put(c) conn.Skip(conn.Len()) conn.Flush() }() - ctx.Request.SetMethod("GET") - ctx.Request.SetRequestURI("/test") - m.ServeHTTP(c, ctx) + c.Request.SetMethod("GET") + c.Request.SetRequestURI("/test") + m.ServeHTTP(ctx, c) conn.WriteBinary([]byte("HTTP/1.1 200 OK\n" + "Server: hertz\n" + "Date: Sun, 29 May 2022 10:49:33 GMT\n" + diff --git a/content/en/docs/hertz/tutorials/framework-exten/response_writer.md b/content/en/docs/hertz/tutorials/framework-exten/response_writer.md index cb50556bf5..3c8bed9d02 100644 --- a/content/en/docs/hertz/tutorials/framework-exten/response_writer.md +++ b/content/en/docs/hertz/tutorials/framework-exten/response_writer.md @@ -42,9 +42,9 @@ provides another way for response writing process. Example: ```go - h.GET("/hijack", func (ctx context.Context, c *app.RequestContext) { -// Hijack the writer of response -ctx.Response.HijackWriter(**yourResponseWriter**) +h.GET("/hijack", func (ctx context.Context, c *app.RequestContext) { + // Hijack the writer of response + c.Response.HijackWriter(**yourResponseWriter**) }) ``` @@ -59,15 +59,15 @@ ctx.Response.HijackWriter(**yourResponseWriter**) Example: ```go - h.GET("/flush/chunk", func (ctx context.Context, c *app.RequestContext) { -// Hijack the writer of response -ctx.Response.HijackWriter(resp.NewChunkedBodyWriter(&ctx.Response, ctx.GetWriter())) - -for i := 0; i < 10; i++ { -ctx.Write([]byte(fmt.Sprintf("chunk %d: %s", i, strings.Repeat("hi~", i)))) // nolint: errcheck -ctx.Flush() // nolint: errcheck -time.Sleep(200 * time.Millisecond) -} +h.GET("/flush/chunk", func (ctx context.Context, c *app.RequestContext) { + // Hijack the writer of response + c.Response.HijackWriter(resp.NewChunkedBodyWriter(&c.Response, c.GetWriter())) + + for i := 0; i < 10; i++ { + c.Write([]byte(fmt.Sprintf("chunk %d: %s", i, strings.Repeat("hi~", i)))) // nolint: errcheck + c.Flush() // nolint: errcheck + time.Sleep(200 * time.Millisecond) + } }) ``` diff --git a/content/en/docs/hertz/tutorials/service-governance/sentinel.md b/content/en/docs/hertz/tutorials/service-governance/sentinel.md index 84a11f70b9..9967a8a925 100644 --- a/content/en/docs/hertz/tutorials/service-governance/sentinel.md +++ b/content/en/docs/hertz/tutorials/service-governance/sentinel.md @@ -87,7 +87,7 @@ func main() { // customize block fallback if required // abort with status 429 by default adaptor.WithServerBlockFallback(func(ctx context.Context, c *app.RequestContext) { - ctx.AbortWithStatusJSON(400, utils.H{ + c.AbortWithStatusJSON(400, utils.H{ "err": "too many request; the quota used up", "code": 10222, }) diff --git a/content/en/docs/hertz/tutorials/service-governance/service_discovery/etcd.md b/content/en/docs/hertz/tutorials/service-governance/service_discovery/etcd.md index ce106475c5..1263cd5c8b 100644 --- a/content/en/docs/hertz/tutorials/service-governance/service_discovery/etcd.md +++ b/content/en/docs/hertz/tutorials/service-governance/service_discovery/etcd.md @@ -347,8 +347,8 @@ func main() { Weight: 10, Tags: nil, })) - h.GET("/ping", func(_ context.Context, ctx *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong2"}) + h.GET("/ping", func(_ context.Context, c *app.RequestContext) { + c.JSON(consts.StatusOK, utils.H{"ping": "pong2"}) }) h.Spin() } diff --git a/content/en/docs/hertz/tutorials/service-governance/service_discovery/redis.md b/content/en/docs/hertz/tutorials/service-governance/service_discovery/redis.md index 8e169cf6ce..e4941dfdd8 100644 --- a/content/en/docs/hertz/tutorials/service-governance/service_discovery/redis.md +++ b/content/en/docs/hertz/tutorials/service-governance/service_discovery/redis.md @@ -483,8 +483,8 @@ func main() { Tags: nil, }), ) - h.GET("/ping", func(_ context.Context, ctx *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"}) + h.GET("/ping", func(_ context.Context, c *app.RequestContext) { + c.JSON(consts.StatusOK, utils.H{"ping": "pong"}) }) h.Spin() } diff --git a/content/en/docs/hertz/tutorials/service-migration/_index.md b/content/en/docs/hertz/tutorials/service-migration/_index.md index 251cbd383e..2f54237231 100644 --- a/content/en/docs/hertz/tutorials/service-migration/_index.md +++ b/content/en/docs/hertz/tutorials/service-migration/_index.md @@ -55,8 +55,8 @@ type HandlerFunc = func(ctx context.Context, c *app.RequestContext) ```Go // fasthttp + fasthttp router example -func Hello(ctx *fasthttp.RequestCtx) { - fmt.Fprintf(ctx, "Hello, %s!\n", ctx.UserValue("name")) +func Hello(c *fasthttp.RequestCtx) { + fmt.Fprintf(ctx, "Hello, %s!\n", c.UserValue("name")) } func main() { @@ -70,7 +70,7 @@ func main() { ```Go // the corresponding hertz example func Hello(ctx context.Context, c *app.RequestContext) { - fmt.Fprintf(ctx, "Hello, %s!\n", ctx.Param("name")) + fmt.Fprintf(ctx, "Hello, %s!\n", c.Param("name")) } func main() { @@ -140,7 +140,7 @@ func Hello(ctx context.Context, c *app.RequestContext) { fmt.Fprintf(ctx, "Hello, World\n") // Then, Set a Header - ctx.Header("Hertz", "test") + c.Header("Hertz", "test") } ``` diff --git a/content/en/security/safety-bulletin/detail/cloudwego-sa-2022-2/index.md b/content/en/security/safety-bulletin/detail/cloudwego-sa-2022-2/index.md index d9a55793ee..9ed121ae4b 100644 --- a/content/en/security/safety-bulletin/detail/cloudwego-sa-2022-2/index.md +++ b/content/en/security/safety-bulletin/detail/cloudwego-sa-2022-2/index.md @@ -17,16 +17,16 @@ Middle Fixed concurrency issues in extreme scenarios. -Scenario: "peer Close & local user Close" occurs at the same time, and `C.onClose` executes `lock(user)`, and Poller also executes `p.detaches` (all three conditions are met) +Scenario: "peer Close & local user Close" occurs at the same time, and `ctx.onClose` executes `lock(user)`, and Poller also executes `p.detaches` (all three conditions are met) When two goroutines execute `op.Control(PollDetach)` at the same time, `op.unused` will be executed twice. -When the program is idle, it is possible that `c.onclose` has completed the `close` callback, `freeop` has been reused, and the state becomes `inuse` again. +When the program is idle, it is possible that `ctx.onclose` has completed the `close` callback, `freeop` has been reused, and the state becomes `inuse` again. That's when the `op.unused` in `p.detaches` is executed; This will incorrectly set the operator of a new connection to 0, causing all subsequent `op.do` to fail in an infinite loop. ## Solution -`Poller` no longer executes `detach` asynchronously to ensure that it does not run concurrently with `C.onclose` and the changes are performance-neutral. +`Poller` no longer executes `detach` asynchronously to ensure that it does not run concurrently with `ctx.onclose` and the changes are performance-neutral. ## Affected Components diff --git a/content/zh/blog/releases/Hertz/release-v060.md b/content/zh/blog/releases/Hertz/release-v060.md index 958a92d010..afceec635a 100644 --- a/content/zh/blog/releases/Hertz/release-v060.md +++ b/content/zh/blog/releases/Hertz/release-v060.md @@ -19,7 +19,7 @@ Hertz 0.6.0 版本中,除了常规迭代优化之外,我们还带来了多 ```go // server 端 func handler(ctx context.Context, c *app.RequestContext){ - ctx.Response.Header.Trailer().Set("Hertz", "Good") + c.Response.Header.Trailer().Set("Hertz", "Good") } // client 端 @@ -31,7 +31,7 @@ req.Header.Trailer().Set("Hertz", "Good") ```go // server 端 func handler(ctx context.Context, c *app.RequestContext){ - ctx.Request.Header.Trailer().Get("Hertz") + c.Request.Header.Trailer().Get("Hertz") } // client 端 @@ -73,11 +73,11 @@ resp.Header.Trailer().Get("Hertz") ```go h.GET("/flush/chunk", func(ctx context.Context, c *app.RequestContext) { // Hijack the writer of response - ctx.Response.HijackWriter(resp.NewChunkedBodyWriter(&ctx.Response, ctx.GetWriter())) + c.Response.HijackWriter(resp.NewChunkedBodyWriter(&c.Response, c.GetWriter())) for i := 0; i < 10; i++ { - ctx.Write([]byte(fmt.Sprintf("chunk %d: %s", i, strings.Repeat("hi~", i)))) // nolint: errcheck - ctx.Flush() // nolint: errcheck + c.Write([]byte(fmt.Sprintf("chunk %d: %s", i, strings.Repeat("hi~", i)))) // nolint: errcheck + c.Flush() // nolint: errcheck time.Sleep(200 * time.Millisecond) } }) diff --git a/content/zh/blog/releases/Hertz/release-v080.md b/content/zh/blog/releases/Hertz/release-v080.md index fb774bc531..dcc6c23516 100644 --- a/content/zh/blog/releases/Hertz/release-v080.md +++ b/content/zh/blog/releases/Hertz/release-v080.md @@ -37,7 +37,7 @@ Hertz 在 v0.8.0 添加了对 Partitioned Cookies 的支持,你需要升级到 目前 Hertz 支持 Partitioned Cookies,但还不支持通过 SetCookie 传入是否为 Partitioned,我们将在下个小版本增加此功能。在此之前,你可以参考下面的代码示例来使用 Partitioned Cookies。 ``` -func SetPartitionedCookie(ctx *app.RequestContext, name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool) { +func SetPartitionedCookie(c *app.RequestContext, name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool) { if path == "" { path = "/" } @@ -54,7 +54,7 @@ func SetPartitionedCookie(ctx *app.RequestContext, name, value string, maxAge in cookie.SetHTTPOnly(httpOnly) cookie.SetSameSite(sameSite) cookie.SetPartitioned(true) - ctx.Response.Header.SetCookie(cookie) + c.Response.Header.SetCookie(cookie) } func main() { diff --git a/content/zh/docs/hertz/getting-started/_index.md b/content/zh/docs/hertz/getting-started/_index.md index aaab3e6f72..b82d7fc5f9 100644 --- a/content/zh/docs/hertz/getting-started/_index.md +++ b/content/zh/docs/hertz/getting-started/_index.md @@ -39,7 +39,7 @@ description: "Hertz 开发环境准备、快速上手与代码生成工具 hz h := server.Default() h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"message": "pong"}) + c.JSON(consts.StatusOK, utils.H{"message": "pong"}) }) h.Spin() diff --git a/content/zh/docs/hertz/tutorials/basic-feature/binding-and-validate.md b/content/zh/docs/hertz/tutorials/basic-feature/binding-and-validate.md index 280b25e9a1..0b1c562b99 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/binding-and-validate.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/binding-and-validate.md @@ -20,18 +20,18 @@ func main() { // BindAndValidate var req Test - err := ctx.BindAndValidate(&req) + err := c.BindAndValidate(&req) ... // Bind 只做参数绑定 req = Test{} - err = ctx.Bind(&req) + err = c.Bind(&req) ... // Validate,需要使用 "vd" tag - err = ctx.Validate(&req) + err = c.Validate(&req) ... }) @@ -44,7 +44,7 @@ func main() { > hertz version >= v0.7.0 | API | 说明 | -| :-------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +|:----------------------| :------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ctx.BindAndValidate | 利用下述的 go-tag 进行参数绑定,并在绑定成功后做一次参数校验 (如果有校验 tag 的话) | | ctx.Bind | 同 `BindAndValidate` 但是不做参数校验 | | ctx.BindQuery | 绑定所有 Query 参数,相当于给每一个 field 声明一个 `query` tag,适用于没写 tag 的场景 | diff --git a/content/zh/docs/hertz/tutorials/basic-feature/client.md b/content/zh/docs/hertz/tutorials/basic-feature/client.md index 670d3d30b6..967546e67f 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/client.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/client.md @@ -36,7 +36,7 @@ func performRequest() { func main() { h := server.New(server.WithHostPorts(":8080")) h.GET("/hello", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, "hello hertz") + c.JSON(consts.StatusOK, "hello hertz") }) go performRequest() h.Spin() @@ -277,7 +277,7 @@ func (c *Client) Post(ctx context.Context, dst []byte, url string, postArgs *pro ```go func main() { - // hertz server:http://localhost:8080/hello ctx.String(consts.StatusOK, "hello %s", ctx.PostForm("name")) + // hertz server:http://localhost:8080/hello ctx.String(consts.StatusOK, "hello %s", c.PostForm("name")) c, err := client.NewClient() if err != nil { return @@ -741,7 +741,7 @@ func (c *Client) Use(mws ...Middleware) 如果客户端中间件链在之前已经设置了最后一个中间件,`UseAsLast` 函数将会返回 `errorLastMiddlewareExist` 错误。因此,为确保客户端中间件链的最后一个中间件为空,可以先使用 [TakeOutLastMiddleware](#takeoutlastmiddleware) 函数清空客户端中间件链的最后一个中间件。 -> 注意:`UseAsLast` 函数将中间件设置在了 `c.lastMiddleware` 中,而使用 [Use](#use) 函数设置的中间件链存放在 `c.mws` 中,两者相对独立,只是在执行客户端中间件链的最后才执行 `c.lastMiddleware`,因此 `UseAsLast` 函数在 [Use](#use) 函数之前或之后调用皆可。 +> 注意:`UseAsLast` 函数将中间件设置在了 `ctx.lastMiddleware` 中,而使用 [Use](#use) 函数设置的中间件链存放在 `ctx.mws` 中,两者相对独立,只是在执行客户端中间件链的最后才执行 `ctx.lastMiddleware`,因此 `UseAsLast` 函数在 [Use](#use) 函数之前或之后调用皆可。 函数签名: diff --git a/content/zh/docs/hertz/tutorials/basic-feature/context/request.md b/content/zh/docs/hertz/tutorials/basic-feature/context/request.md index a275f51e01..6c3f435bef 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/context/request.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/context/request.md @@ -49,7 +49,7 @@ func (ctx *RequestContext) Host() []byte ```go // GET http://example.com h.GET("/", func(ctx context.Context, c *app.RequestContext) { - host := ctx.Host() // host == []byte("example.com") + host := c.Host() // host == []byte("example.com") }) ``` @@ -70,17 +70,17 @@ h := server.Default(server.WithHandleMethodNotAllowed(true)) // GET http://example.com/user/bar h.GET("/user/:name", func(ctx context.Context, c *app.RequestContext) { - fpath := ctx.FullPath() // fpath == "/user/:name" + fpath := c.FullPath() // fpath == "/user/:name" }) // GET http://example.com/bar h.NoRoute(func(ctx context.Context, c *app.RequestContext) { - fpath := ctx.FullPath() // fpath == "" + fpath := c.FullPath() // fpath == "" }) // POST http://example.com/user/bar h.NoMethod(func(ctx context.Context, c *app.RequestContext) { - fpath := ctx.FullPath() // fpath == "" + fpath := c.FullPath() // fpath == "" }) ``` @@ -101,7 +101,7 @@ func (ctx *RequestContext) SetFullPath(p string) ```go h.GET("/user/:name", func(ctx context.Context, c *app.RequestContext) { c.SetFullPath("/v1/user/:name") - fpath := ctx.FullPath() // fpath == "/v1/user/:name" + fpath := c.FullPath() // fpath == "/v1/user/:name" }) ``` @@ -122,7 +122,7 @@ func (ctx *RequestContext) Path() []byte ```go // GET http://example.com/user/bar h.GET("/user/:name", func(ctx context.Context, c *app.RequestContext) { - path := ctx.Path() // path == []byte("/user/bar") + path := c.Path() // path == []byte("/user/bar") }) ``` @@ -141,8 +141,8 @@ func (ctx *RequestContext) Param(key string) string ```go // GET http://example.com/user/bar h.GET("/user/:name", func(ctx context.Context, c *app.RequestContext) { - name := ctx.Param("name") // name == "bar" - id := ctx.Param("id") // id == "" + name := c.Param("name") // name == "bar" + id := c.Param("id") // id == "" }) ``` @@ -161,8 +161,8 @@ func (ctx *RequestContext) Query(key string) string ```go // GET http://example.com/user?name=bar h.GET("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.Query("name") // name == "bar" - id := ctx.Query("id") // id == "" + name := c.Query("name") // name == "bar" + id := c.Query("id") // id == "" }) ``` @@ -181,9 +181,9 @@ func (ctx *RequestContext) DefaultQuery(key, defaultValue string) string ```go // GET http://example.com/user?name=bar&&age= h.GET("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.DefaultQuery("name", "tom") // name == "bar" - id := ctx.DefaultQuery("id", "123") // id == "123" - age := ctx.DefaultQuery("age", "45") // age == "" + name := c.DefaultQuery("name", "tom") // name == "bar" + id := c.DefaultQuery("id", "123") // id == "123" + age := c.DefaultQuery("age", "45") // age == "" }) ``` @@ -202,9 +202,9 @@ func (ctx *RequestContext) GetQuery(key string) (string, bool) ```go // GET http://example.com/user?name=bar&&age= h.GET("/user", func(ctx context.Context, c *app.RequestContext) { - name, hasName := ctx.GetQuery("name") // name == "bar", hasName == true - id, hasId := ctx.GetQuery("id") // id == "", hasId == false - age, hasAge := ctx.GetQuery("age") // age == "", hasAge == true + name, hasName := c.GetQuery("name") // name == "bar", hasName == true + id, hasId := c.GetQuery("id") // id == "", hasId == false + age, hasAge := c.GetQuery("age") // age == "", hasAge == true }) ``` @@ -247,7 +247,7 @@ Args 对象提供了以下方法获取/设置 Query String 参数。 ```go // GET http://example.com/user?name=bar&&age=&&pets=dog&&pets=cat h.GET("/user", func(ctx context.Context, c *app.RequestContext) { - args := ctx.QueryArgs() + args := c.QueryArgs() // get information from args s := args.String() // s == "name=bar&age=&pets=dog&pets=cat" @@ -388,15 +388,15 @@ func (h *RequestHeader) Add(key, value string) ```go hertz.GET("/example", func(ctx context.Context, c *app.RequestContext) { - ctx.Request.Header.Add("hertz1", "value1") - ctx.Request.Header.Add("hertz1", "value2") - ctx.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded")) - contentType1 := ctx.Request.Header.ContentType() + c.Request.Header.Add("hertz1", "value1") + c.Request.Header.Add("hertz1", "value2") + c.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded")) + contentType1 := c.Request.Header.ContentType() // contentType1 == []byte("application/x-www-form-urlencoded") - ctx.Request.Header.Add("Content-Type", "application/json; charset=utf-8") - hertz1 := ctx.Request.Header.GetAll("hertz1") + c.Request.Header.Add("Content-Type", "application/json; charset=utf-8") + hertz1 := c.Request.Header.GetAll("hertz1") // hertz1 == []string{"value1", "value2"} - contentType2 := ctx.Request.Header.ContentType() + contentType2 := c.Request.Header.ContentType() // contentType2 == []byte("application/json; charset=utf-8") }) ``` @@ -417,15 +417,15 @@ func (h *RequestHeader) Set(key, value string) ```go hertz.GET("/example", func(ctx context.Context, c *app.RequestContext) { - ctx.Request.Header.Set("hertz1", "value1") - ctx.Request.Header.Set("hertz1", "value2") - ctx.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded")) - contentType1 := ctx.Request.Header.ContentType() + c.Request.Header.Set("hertz1", "value1") + c.Request.Header.Set("hertz1", "value2") + c.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded")) + contentType1 := c.Request.Header.ContentType() // contentType1 == []byte("application/x-www-form-urlencoded") - ctx.Request.Header.Set("Content-Type", "application/json; charset=utf-8") - hertz1 := ctx.Request.Header.GetAll("hertz1") + c.Request.Header.Set("Content-Type", "application/json; charset=utf-8") + hertz1 := c.Request.Header.GetAll("hertz1") // hertz1 == []string{"value2"} - contentType2 := ctx.Request.Header.ContentType() + contentType2 := c.Request.Header.ContentType() // contentType2 == []byte("application/json; charset=utf-8") }) ``` @@ -444,8 +444,8 @@ func (h *RequestHeader) Header() []byte ```go hertz.GET("/example", func(ctx context.Context, c *app.RequestContext) { - ctx.Request.Header.Set("hertz1", "value1") - header := ctx.Request.Header.Header() + c.Request.Header.Set("hertz1", "value1") + header := c.Request.Header.Header() // header == []byte("GET /example HTTP/1.1 //User-Agent: PostmanRuntime-ApipostRuntime/1.1.0 //Host: localhost:8888 @@ -471,8 +471,8 @@ func (h *RequestHeader) String() string ```go hertz.GET("/example", func(ctx context.Context, c *app.RequestContext) { - ctx.Request.Header.Set("hertz1", "value1") - header := ctx.Request.Header.String() + c.Request.Header.Set("hertz1", "value1") + header := c.Request.Header.String() // header == "GET /example HTTP/1.1 //User-Agent: PostmanRuntime-ApipostRuntime/1.1.0 //Host: localhost:8888 @@ -498,11 +498,11 @@ func (h *RequestHeader) VisitAll(f func(key, value []byte)) ```go hertz.GET("/example", func(ctx context.Context, c *app.RequestContext) { - ctx.Request.Header.Add("Hertz1", "value1") - ctx.Request.Header.Add("Hertz1", "value2") + c.Request.Header.Add("Hertz1", "value1") + c.Request.Header.Add("Hertz1", "value2") var hertzString []string - ctx.Request.Header.VisitAll(func(key, value []byte) { + c.Request.Header.VisitAll(func(key, value []byte) { if string(key) == "Hertz1" { hertzString = append(hertzString, string(value)) } @@ -526,7 +526,7 @@ func (ctx *RequestContext) Method() []byte ```go // POST http://example.com/user h.Any("/user", func(ctx context.Context, c *app.RequestContext) { - method := ctx.Method() // method == []byte("POST") + method := c.Method() // method == []byte("POST") }) ``` @@ -546,7 +546,7 @@ func (ctx *RequestContext) ContentType() []byte // POST http://example.com/user // Content-Type: application/json h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - contentType := ctx.ContentType() // contentType == []byte("application/json") + contentType := c.ContentType() // contentType == []byte("application/json") }) ``` @@ -569,10 +569,10 @@ func (ctx *RequestContext) IfModifiedSince(lastModified time.Time) bool // If-Modified-Since: Wed, 21 Oct 2023 07:28:00 GMT h.Post("/user", func(ctx context.Context, c *app.RequestContext) { t2022, _ := time.Parse(time.RFC1123, "Wed, 21 Oct 2022 07:28:00 GMT") - ifModifiedSince := ctx.IfModifiedSince(t2022) // ifModifiedSince == false + ifModifiedSince := c.IfModifiedSince(t2022) // ifModifiedSince == false t2024, _ := time.Parse(time.RFC1123, "Wed, 21 Oct 2024 07:28:00 GMT") - ifModifiedSince = ctx.IfModifiedSince(t2024) // ifModifiedSince == true + ifModifiedSince = c.IfModifiedSince(t2024) // ifModifiedSince == true }) ``` @@ -592,9 +592,9 @@ func (ctx *RequestContext) Cookie(key string) []byte // POST http://example.com/user // Cookie: foo_cookie=choco; bar_cookie=strawberry h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - fCookie := ctx.Cookie("foo_cookie") // fCookie == []byte("choco") - bCookie := ctx.Cookie("bar_cookie") // bCookie == []byte("strawberry") - noneCookie := ctx.Cookie("none_cookie") // noneCookie == nil + fCookie := c.Cookie("foo_cookie") // fCookie == []byte("choco") + bCookie := c.Cookie("bar_cookie") // bCookie == []byte("strawberry") + noneCookie := c.Cookie("none_cookie") // noneCookie == nil }) ``` @@ -614,7 +614,7 @@ func (ctx *RequestContext) UserAgent() []byte // POST http://example.com/user // User-Agent: Chrome/51.0.2704.103 Safari/537.36 h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - ua := ctx.UserAgent() // ua == []byte("Chrome/51.0.2704.103 Safari/537.36") + ua := c.UserAgent() // ua == []byte("Chrome/51.0.2704.103 Safari/537.36") }) ``` @@ -634,7 +634,7 @@ func (ctx *RequestContext) GetHeader(key string) []byte // POST http://example.com/user // Say-Hello: hello h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - customHeader := ctx.GetHeader("Say-Hello") // customHeader == []byte("hello") + customHeader := c.GetHeader("Say-Hello") // customHeader == []byte("hello") }) ``` @@ -754,7 +754,7 @@ func (ctx *RequestContext) Body() ([]byte, error) // Content-Type: application/json // {"pet":"cat"} h.Post("/pet", func(ctx context.Context, c *app.RequestContext) { - data, err := ctx.Body() // data == []byte("{\"pet\":\"cat\"}") , err == nil + data, err := c.Body() // data == []byte("{\"pet\":\"cat\"}") , err == nil }) ``` @@ -776,7 +776,7 @@ func (ctx *RequestContext) RequestBodyStream() io.Reader // abcdefg h := server.Default(server.WithStreamBody(true)) h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - sr := ctx.RequestBodyStream() + sr := c.RequestBodyStream() data, _ := io.ReadAll(sr) // data == []byte("abcdefg") }) ``` @@ -801,7 +801,7 @@ func (ctx *RequestContext) MultipartForm() (*multipart.Form, error) // Content-Disposition: form-data; name="name" // tom h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - form, err := ctx.MultipartForm() + form, err := c.MultipartForm() name := form.Value["name"][0] // name == "tom" }) ``` @@ -826,7 +826,7 @@ func (ctx *RequestContext) PostForm(key string) string // Content-Disposition: form-data; name="name" // tom h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.PostForm("name") // name == "tom" + name := c.PostForm("name") // name == "tom" }) ``` @@ -850,8 +850,8 @@ func (ctx *RequestContext) DefaultPostForm(key, defaultValue string) string // Content-Disposition: form-data; name="name" // tom h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.PostForm("name", "jack") // name == "tom" - age := ctx.PostForm("age", "10") // age == "10" + name := c.PostForm("name", "jack") // name == "tom" + age := c.PostForm("age", "10") // age == "10" }) ``` @@ -872,7 +872,7 @@ func (ctx *RequestContext) PostArgs() *protocol.Args // Content-Type: application/x-www-form-urlencoded // name=tom&pet=cat&pet=dog h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - args := ctx.PostArgs() + args := c.PostArgs() name := args.Peek("name") // name == "tom" var pets []string @@ -906,8 +906,8 @@ func (ctx *RequestContext) FormValue(key string) []byte // Content-Type: application/x-www-form-urlencoded // age=10 h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.FormValue("name") // name == []byte("tom"), get by QueryArgs - age := ctx.FormValue("age") // age == []byte("10"), get by PostArgs + name := c.FormValue("name") // name == []byte("tom"), get by QueryArgs + age := c.FormValue("age") // age == []byte("10"), get by PostArgs }) // POST http://example.com/user @@ -915,7 +915,7 @@ h.POST("/user", func(ctx context.Context, c *app.RequestContext) { // Content-Disposition: form-data; name="name" // tom h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - name := ctx.FormValue("name") // name == []byte("tom"), get by MultipartForm + name := c.FormValue("name") // name == []byte("tom"), get by MultipartForm }) ``` @@ -938,7 +938,7 @@ func (ctx *RequestContext) SetFormValueFunc(f FormValueFunc) // 10 h.POST("/user", func(ctx context.Context, c *app.RequestContext) { // only return multipart form value - ctx.SetFormValueFunc(func(rc *app.RequestContext, s string) []byte { + c.SetFormValueFunc(func(rc *app.RequestContext, s string) []byte { mf, err := rc.MultipartForm() if err == nil && mf.Value != nil { vv := mf.Value[s] @@ -949,8 +949,8 @@ h.POST("/user", func(ctx context.Context, c *app.RequestContext) { return nil }) - name := ctx.FormValue("name") // name == nil - age := ctx.FormValue("age") // age == []byte("10") + name := c.FormValue("name") // name == nil + age := c.FormValue("age") // age == []byte("10") }) ``` @@ -981,7 +981,7 @@ func (ctx *RequestContext) MultipartForm() (*multipart.Form, error) // Content-Type: multipart/form-data; // Content-Disposition: form-data; name="avatar"; filename="abc.jpg" h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - form, err := ctx.MultipartForm() + form, err := c.MultipartForm() avatarFile := form.File["avatar"][0] // avatarFile.Filename == "abc.jpg" }) ``` @@ -1003,7 +1003,7 @@ func (ctx *RequestContext) FormFile(name string) (*multipart.FileHeader, error) // Content-Type: multipart/form-data; // Content-Disposition: form-data; name="avatar"; filename="abc.jpg" h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - avatarFile, err := ctx.FormFile("avatar") // avatarFile.Filename == "abc.jpg", err == nil + avatarFile, err := c.FormFile("avatar") // avatarFile.Filename == "abc.jpg", err == nil }) ``` @@ -1024,9 +1024,9 @@ func (ctx *RequestContext) SaveUploadedFile(file *multipart.FileHeader, dst stri // Content-Type: multipart/form-data; // Content-Disposition: form-data; name="avatar"; filename="abc.jpg" h.Post("/user", func(ctx context.Context, c *app.RequestContext) { - avatarFile, err := ctx.FormFile("avatar") // avatarFile.Filename == "abc.jpg", err == nil + avatarFile, err := c.FormFile("avatar") // avatarFile.Filename == "abc.jpg", err == nil // save file - ctx.SaveUploadedFile(avatarFile, avatarFile.Filename) // save file "abc.jpg" + c.SaveUploadedFile(avatarFile, avatarFile.Filename) // save file "abc.jpg" }) ``` @@ -1062,70 +1062,70 @@ h.Post("/user", func(ctx context.Context, c *app.RequestContext) { ```go h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - ctx.Set("version1", "v1") - v := ctx.Value("version1") // v == interface{}(string) "v1" + c.Set("version1", "v1") + v := c.Value("version1") // v == interface{}(string) "v1" - ctx.Set("version2", "v2") - v, exists := ctx.Get("version2") // v == interface{}(string) "v2", exists == true - v, exists = ctx.Get("pet") // v == interface{} nil, exists == false + c.Set("version2", "v2") + v, exists := c.Get("version2") // v == interface{}(string) "v2", exists == true + v, exists = c.Get("pet") // v == interface{} nil, exists == false - ctx.Set("version3", "v3") - v := ctx.MustGet("version3") // v == interface{}(string) "v3" + c.Set("version3", "v3") + v := c.MustGet("version3") // v == interface{}(string) "v3" - ctx.Set("version4", "v4") - vString := ctx.GetString("version4") // vString == "v4" + c.Set("version4", "v4") + vString := c.GetString("version4") // vString == "v4" - ctx.Set("isAdmin", true) - vBool := ctx.GetBool("isAdmin") // vBool == true + c.Set("isAdmin", true) + vBool := c.GetBool("isAdmin") // vBool == true - ctx.Set("age1", 20) - vInt := ctx.GetInt("age1") // vInt == 20 + c.Set("age1", 20) + vInt := c.GetInt("age1") // vInt == 20 - ctx.Set("age2", int32(20)) - vInt32 := ctx.GetInt32("age2") // vInt32 == 20 + c.Set("age2", int32(20)) + vInt32 := c.GetInt32("age2") // vInt32 == 20 - ctx.Set("age3", int64(20)) - vInt64 := ctx.GetInt64("age3") // vInt64 == 20 + c.Set("age3", int64(20)) + vInt64 := c.GetInt64("age3") // vInt64 == 20 - ctx.Set("age4", uint(20)) - vUInt := ctx.GetUint("age4") // vUInt == 20 + c.Set("age4", uint(20)) + vUInt := c.GetUint("age4") // vUInt == 20 - ctx.Set("age5", uint32(20)) - vUInt32 := ctx.GetUint32("age5") // vUInt32 == 20 + c.Set("age5", uint32(20)) + vUInt32 := c.GetUint32("age5") // vUInt32 == 20 - ctx.Set("age6", uint64(20)) - vUInt64 := ctx.GetUint64("age6") // vUInt64 == 20 + c.Set("age6", uint64(20)) + vUInt64 := c.GetUint64("age6") // vUInt64 == 20 - ctx.Set("age7", float32(20.1)) - vFloat32 := ctx.GetFloat32("age7") // vFloat32 == 20.1 + c.Set("age7", float32(20.1)) + vFloat32 := c.GetFloat32("age7") // vFloat32 == 20.1 - ctx.Set("age8", 20.1) - vFloat64 := ctx.GetFloat64("age8") // vFloat64 == 20.1 + c.Set("age8", 20.1) + vFloat64 := c.GetFloat64("age8") // vFloat64 == 20.1 t2022, _ := time.Parse(time.RFC1123, "Wed, 21 Oct 2022 07:28:00 GMT") - ctx.Set("birthday", t2022) - vTime := ctx.GetTime("birthday") // vTime == t2022 + c.Set("birthday", t2022) + vTime := c.GetTime("birthday") // vTime == t2022 - ctx.Set("duration", time.Minute) - vDuration := ctx.GetDuration("duration") // vDuration == time.Minute + c.Set("duration", time.Minute) + vDuration := c.GetDuration("duration") // vDuration == time.Minute - ctx.Set("pet", []string{"cat", "dog"}) - vStringSlice := ctx.GetStringSlice("pet") // vStringSlice == []string{"cat", "dog"} + c.Set("pet", []string{"cat", "dog"}) + vStringSlice := c.GetStringSlice("pet") // vStringSlice == []string{"cat", "dog"} - ctx.Set("info1", map[string]interface{}{"name": "tom"}) - vStringMap := ctx.GetStringMap("info1") // vStringMap == map[string]interface{}{"name": "tom"} + c.Set("info1", map[string]interface{}{"name": "tom"}) + vStringMap := c.GetStringMap("info1") // vStringMap == map[string]interface{}{"name": "tom"} - ctx.Set("info2", map[string]string{"name": "tom"}) - vStringMapString := ctx.GetStringMapString("info2") + c.Set("info2", map[string]string{"name": "tom"}) + vStringMapString := c.GetStringMapString("info2") // vStringMapString == map[string]string{}{"name": "tom"} - ctx.Set("smss", map[string][]string{"pets": {"cat", "dog"}}) - vStringMapStringSlice := ctx.GetStringMapStringSlice("smss") + c.Set("smss", map[string][]string{"pets": {"cat", "dog"}}) + vStringMapStringSlice := c.GetStringMapStringSlice("smss") // vStringMapStringSlice == map[string][]string{"pets": {"cat", "dog"}} - ctx.Set("duration", time.Minute) - ctx.Set("version", "v1") - ctx.ForEachKey(func(k string, v interface{}) { + c.Set("duration", time.Minute) + c.Set("version", "v1") + c.ForEachKey(func(k string, v interface{}) { // 1. k == "duration", v == interface{}(time.Duration) time.Minute // 2. k == "version", v == interface{}(string) "v1" }) @@ -1160,7 +1160,7 @@ func (ctx *RequestContext) Next(c context.Context) ```go h.POST("/user", func(ctx context.Context, c *app.RequestContext) { c.Next(ctx) - v := ctx.GetString("version") // v == "v1" + v := c.GetString("version") // v == "v1" }, func(ctx context.Context, c *app.RequestContext) { c.Set("version", "v1") }) @@ -1183,7 +1183,7 @@ middleware1 := func(ctx context.Context, c *app.RequestContext) { } handler1 := func(ctx context.Context, c *app.RequestContext) { - handlers := ctx.Handlers() // []Handler{middleware1, handler1} + handlers := c.Handlers() // []Handler{middleware1, handler1} } h.POST("/user", middleware1, handler1) @@ -1203,7 +1203,7 @@ func (ctx *RequestContext) Handler() HandlerFunc ```go middleware1 := func(ctx context.Context, c *app.RequestContext) { - lastHandler := ctx.Handler() // lastHandler == handler1 + lastHandler := c.Handler() // lastHandler == handler1 } handler1 := func(ctx context.Context, c *app.RequestContext) { @@ -1230,11 +1230,11 @@ handler1 := func(ctx context.Context, c *app.RequestContext) { } handler := func(ctx context.Context, c *app.RequestContext) { - hc := app.HandlersChain{ctx.Handlers()[0], handler1} // append handler1 into handlers chain - ctx.SetHandlers(hc) + hc := app.HandlersChain{c.Handlers()[0], handler1} // append handler1 into handlers chain + c.SetHandlers(hc) c.Next(ctx) - current := ctx.GetString("current") // current == "handler1" - ctx.String(consts.StatusOK, current) + current := c.GetString("current") // current == "handler1" + c.String(consts.StatusOK, current) } h.POST("/user", handler) @@ -1258,7 +1258,7 @@ package main func main() { h := server.New() h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - hn := ctx.HandlerName() // hn == "main.main.func1" + hn := c.HandlerName() // hn == "main.main.func1" }) } ``` @@ -1277,9 +1277,9 @@ func (ctx *RequestContext) GetIndex() int8 ```go h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - index := ctx.GetIndex() // index == 0 + index := c.GetIndex() // index == 0 }, func(ctx context.Context, c *app.RequestContext) { - index := ctx.GetIndex() // index == 1 + index := c.GetIndex() // index == 1 }) ``` @@ -1318,7 +1318,7 @@ func (ctx *RequestContext) IsAborted() bool ```go h.POST("/user", func(ctx context.Context, c *app.RequestContext) { c.Abort() - isAborted := ctx.IsAborted() // isAborted == true + isAborted := c.IsAborted() // isAborted == true }, func(ctx context.Context, c *app.RequestContext) { // will not execute }) @@ -1359,7 +1359,7 @@ func (ctx *RequestContext) ClientIP() string // X-Forwarded-For: 20.20.20.20, 30.30.30.30 // X-Real-IP: 10.10.10.10 h.Use(func(ctx context.Context, c *app.RequestContext) { - ip := ctx.ClientIP() // 20.20.20.20 + ip := c.ClientIP() // 20.20.20.20 }) ``` @@ -1384,11 +1384,11 @@ func (ctx *RequestContext) SetClientIPFunc(f ClientIP) // X-Forwarded-For: 30.30.30.30 h.POST("/user", func(ctx context.Context, c *app.RequestContext) { // method 1 - customClientIPFunc := func(ctx *app.RequestContext) string { + customClientIPFunc := func(c *app.RequestContext) string { return "127.0.0.1" } - ctx.SetClientIPFunc(customClientIPFunc) - ip := ctx.ClientIP() // ip == "127.0.0.1" + c.SetClientIPFunc(customClientIPFunc) + ip := c.ClientIP() // ip == "127.0.0.1" // method 2 _, cidr, _ := net.ParseCIDR("127.0.0.1/32") @@ -1396,9 +1396,9 @@ h.POST("/user", func(ctx context.Context, c *app.RequestContext) { RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, TrustedCIDRs: []*net.IPNet{cidr}, } - ctx.SetClientIPFunc(app.ClientIPWithOption(opts)) + c.SetClientIPFunc(app.ClientIPWithOption(opts)) - ip = ctx.ClientIP() // ip == "30.30.30.30" + ip = c.ClientIP() // ip == "30.30.30.30" }) ``` @@ -1422,7 +1422,7 @@ func (ctx *RequestContext) Copy() *RequestContext ```go h.POST("/user", func(ctx context.Context, c *app.RequestContext) { - ctx1 := ctx.Copy() + ctx1 := c.Copy() go func(context *app.RequestContext) { // safely }(ctx1) diff --git a/content/zh/docs/hertz/tutorials/basic-feature/context/response.md b/content/zh/docs/hertz/tutorials/basic-feature/context/response.md index aa18b644bc..8be53b8ed1 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/context/response.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/context/response.md @@ -39,7 +39,7 @@ func (ctx *RequestContext) SetContentType(contentType string) ```go h.GET("/user", func(ctx context.Context, c *app.RequestContext) { c.Write([]byte(`{"foo":"bar"}`)) - ctx.SetContentType("application/json; charset=utf-8") + c.SetContentType("application/json; charset=utf-8") // Content-Type: application/json; charset=utf-8 }) ``` @@ -59,7 +59,7 @@ func (ctx *RequestContext) SetContentTypeBytes(contentType []byte) ```go h.GET("/user", func(ctx context.Context, c *app.RequestContext) { c.Write([]byte(`{"foo":"bar"}`)) - ctx.SetContentType([]byte("application/json; charset=utf-8")) + c.SetContentType([]byte("application/json; charset=utf-8")) // Content-Type: application/json; charset=utf-8 }) ``` @@ -207,8 +207,8 @@ func (ctx *RequestContext) Header(key, value string) ```go h.GET("/user", func(ctx context.Context, c *app.RequestContext) { c.Header("My-Name", "tom") - ctx.Header("My-Name", "") - ctx.Header("My-Name-Not-Exists", "yes") + c.Header("My-Name", "") + c.Header("My-Name-Not-Exists", "yes") }) ``` @@ -227,7 +227,7 @@ func (ctx *RequestContext) SetCookie(name, value string, maxAge int, path, domai ```go h.GET("/user", func(ctx context.Context, c *app.RequestContext) { c.SetCookie("user", "hertz", 1, "/", "localhost", protocol.CookieSameSiteLaxMode, true, true) - cookie := ctx.Response.Header.Get("Set-Cookie") + cookie := c.Response.Header.Get("Set-Cookie") // cookie == "user=hertz; max-age=1; domain=localhost; path=/; HttpOnly; secure; SameSite=Lax" }) ``` @@ -243,7 +243,7 @@ Chrome 从 2024 年第一季度开始,禁用了 1% 的用户的第三方 Cooki 示例: ```go -func SetPartitionedCookie(ctx *app.RequestContext, name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool) { +func SetPartitionedCookie(c *app.RequestContext, name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool) { if path == "" { path = "/" } @@ -263,8 +263,7 @@ func SetPartitionedCookie(ctx *app.RequestContext, name, value string, maxAge in cookie.SetSameSite(sameSite) cookie.SetPartitioned(true) // Set-Cookie: user=hertz; max-age=1; domain=localhost; path=/; HttpOnly; secure; SameSite=None; Partitioned - -ctx.Response.Header.SetCookie(cookie) + c.Response.Header.SetCookie(cookie) } func main() { @@ -314,7 +313,7 @@ func (ctx *RequestContext) AbortWithError(code int, err error) *errors.Error ```go h.GET("/user", func(ctx context.Context, c *app.RequestContext) { c.AbortWithError(consts.StatusOK, errors.New("hertz error")) - err := ctx.Errors.String() + err := c.Errors.String() // err == "Error #01: hertz error" }, func(ctx context.Context, c *app.RequestContext) { // will not execute @@ -431,13 +430,13 @@ func (ctx *RequestContext) SetBodyStream(bodyStream io.Reader, bodySize int) h.GET("/user", func(ctx context.Context, c *app.RequestContext) { data := "hello world" r := strings.NewReader(data) - ctx.SetBodyStream(r, -1) // Body: "hello world" + c.SetBodyStream(r, -1) // Body: "hello world" }) h.GET("/user1", func(ctx context.Context, c *app.RequestContext) { data := "hello world" r1 := strings.NewReader(data) - ctx.SetBodyStream(r1, 5) // Body: "hello" + c.SetBodyStream(r1, 5) // Body: "hello" }) ``` @@ -474,8 +473,8 @@ func (ctx *RequestContext) Write(p []byte) (int, error) ```go h.GET("/user", func(ctx context.Context, c *app.RequestContext) { c.Write([]byte("hello")) - ctx.Write([]byte(" ")) - ctx.Write([]byte("world")) + c.Write([]byte(" ")) + c.Write([]byte("world")) // Body: "hello world" }) ``` @@ -494,7 +493,7 @@ func (ctx *RequestContext) WriteString(s string) (int, error) ```go h.GET("/user", func(ctx context.Context, c *app.RequestContext) { - size, _ := ctx.WriteString("hello world")// Body: "hello world", size == 11 + size, _ := c.WriteString("hello world")// Body: "hello world", size == 11 }) ``` @@ -532,7 +531,7 @@ func (ctx *RequestContext) AbortWithStatusJSON(code int, jsonObj interface{}) ```go h.GET("/user", func(ctx context.Context, c *app.RequestContext) { - ctx.AbortWithStatusJSON(consts.StatusOK, utils.H{ + c.AbortWithStatusJSON(consts.StatusOK, utils.H{ "foo": "bar", "html": "", }) diff --git a/content/zh/docs/hertz/tutorials/basic-feature/engine.md b/content/zh/docs/hertz/tutorials/basic-feature/engine.md index 35096620c3..4ddf620130 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/engine.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/engine.md @@ -300,7 +300,7 @@ Hertz Server 支持流式写入响应。 h.GET("/streamWrite1", func(ctx context.Context, c *app.RequestContext) { rw := newChunkReader() line := []byte("line\r\n") - ctx.SetBodyStream(rw, 500*len(line)) + c.SetBodyStream(rw, 500*len(line)) go func() { for i := 1; i <= 500; i++ { @@ -313,7 +313,7 @@ Hertz Server 支持流式写入响应。 }() go func() { - <-ctx.Finished() + <-c..Finished() fmt.Println("request process end") }() }) @@ -322,7 +322,7 @@ Hertz Server 支持流式写入响应。 rw := newChunkReader() // Content-Length may be negative: // -1 means Transfer-Encoding: chunked. - ctx.SetBodyStream(rw, -1) + c.SetBodyStream(rw, -1) go func() { for i := 1; i < 1000; i++ { @@ -335,7 +335,7 @@ Hertz Server 支持流式写入响应。 }() go func() { - <-ctx.Finished() + <-c..Finished() fmt.Println("request process end") }() }) @@ -401,11 +401,11 @@ Hertz Server 支持流式写入响应。 ```go h.GET("/flush/chunk", func(ctx context.Context, c *app.RequestContext) { // Hijack the writer of response - ctx.Response.HijackWriter(resp.NewChunkedBodyWriter(&ctx.Response, ctx.GetWriter())) + c.Response.HijackWriter(resp.NewChunkedBodyWriter(&c.Response, c.GetWriter())) for i := 0; i < 10; i++ { - ctx.Write([]byte(fmt.Sprintf("chunk %d: %s", i, strings.Repeat("hi~", i)))) // nolint: errcheck - ctx.Flush() // nolint: errcheck + c.Write([]byte(fmt.Sprintf("chunk %d: %s", i, strings.Repeat("hi~", i)))) // nolint: errcheck + c.Flush() // nolint: errcheck time.Sleep(200 * time.Millisecond) } }) @@ -515,13 +515,13 @@ func (engine *Engine) Routes() (routes RoutesInfo) ```go func getHandler() app.HandlerFunc { return func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "get handler") + c.String(consts.StatusOK, "get handler") } } func postHandler() app.HandlerFunc { return func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "post handler") + c.String(consts.StatusOK, "post handler") } } diff --git a/content/zh/docs/hertz/tutorials/basic-feature/hooks.md b/content/zh/docs/hertz/tutorials/basic-feature/hooks.md index 40e3b32391..82c29ef865 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/hooks.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/hooks.md @@ -159,7 +159,7 @@ func main() { }) h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"}) + c.JSON(consts.StatusOK, utils.H{"ping": "pong"}) }) h.Spin() @@ -207,7 +207,7 @@ func main() { server.WithHostPorts("localhost:9230")) h.GET("", func(ctx context.Context, c *app.RequestContext) { hlog.Info("pong") - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"}) + c.JSON(consts.StatusOK, utils.H{"ping": "pong"}) }) h.Spin() diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/_index.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/_index.md index 6903021ef0..62c9977a8d 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/_index.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/_index.md @@ -240,6 +240,6 @@ func main() { 服务端中间件会按定义的先后顺序依次执行,如果想快速终止中间件调用,可以使用以下方法,注意**当前中间件仍将执行**。 -- `c.Abort()`:终止后续调用 -- `c.AbortWithMsg(msg string, statusCode int)`:终止后续调用,并设置 response 中 body 和状态码 -- `c.AbortWithStatus(code int)`:终止后续调用,并设置状态码 +- `ctx.Abort()`:终止后续调用 +- `ctx.AbortWithMsg(msg string, statusCode int)`:终止后续调用,并设置 response 中 body 和状态码 +- `ctx.AbortWithStatus(code int)`:终止后续调用,并设置状态码 diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/casbin.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/casbin.md index 41b468a075..55e1b70e61 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/casbin.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/casbin.md @@ -565,7 +565,7 @@ func main(){ h.GET("/book", m.RequiresPermissions("book:read", casbin.WithUnauthorized(func(ctx context.Context, c *app.RequestContext) { - ctx.AbortWithStatus(consts.StatusUnauthorized) + c.AbortWithStatus(consts.StatusUnauthorized) }), ), func(ctx context.Context, c *app.RequestContext) { @@ -601,7 +601,7 @@ func main(){ h.GET("/book", m.RequiresPermissions("book:read", casbin.WithForbidden(func(ctx context.Context, c *app.RequestContext) { - ctx.AbortWithStatus(consts.StatusForbidden) + c.AbortWithStatus(consts.StatusForbidden) }), ), func(ctx context.Context, c *app.RequestContext) { diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/csrf.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/csrf.md index 5a7eec8533..41d5142fc6 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/csrf.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/csrf.md @@ -39,11 +39,11 @@ func main() { h.Use(csrf.New()) h.GET("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, csrf.GetToken(ctx)) + c.String(200, csrf.GetToken(ctx)) }) h.POST("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "CSRF token is valid") + c.String(200, "CSRF token is valid") }) h.Spin() @@ -97,10 +97,10 @@ func main() { h.Use(csrf.New(csrf.WithSecret("your_secret"))) h.GET("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, csrf.GetToken(ctx)) + c.String(200, csrf.GetToken(ctx)) }) h.POST("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "CSRF token is valid") + c.String(200, "CSRF token is valid") }) h.Spin() @@ -143,11 +143,11 @@ func main() { h.Use(csrf.New(csrf.WithIgnoredMethods([]string{"GET", "HEAD", "TRACE"}))) h.GET("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, csrf.GetToken(ctx)) + c.String(200, csrf.GetToken(ctx)) }) h.OPTIONS("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "success") + c.String(200, "success") }) h.Spin() } @@ -188,12 +188,12 @@ import ( ) func myErrFunc(ctx context.Context, c *app.RequestContext) { - if ctx.Errors.Last() == nil { + if c.Errors.Last() == nil { err := fmt.Errorf("myErrFunc called when no error occurs") - ctx.String(400, err.Error()) - ctx.Abort() + c.String(400, err.Error()) + c.Abort() } - ctx.AbortWithMsg(ctx.Errors.Last().Error(), http.StatusBadRequest) + c.AbortWithMsg(c.Errors.Last().Error(), http.StatusBadRequest) } func main() { @@ -204,10 +204,10 @@ func main() { h.Use(csrf.New(csrf.WithErrorFunc(myErrFunc))) h.GET("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, csrf.GetToken(ctx)) + c.String(200, csrf.GetToken(ctx)) }) h.POST("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "CSRF token is valid") + c.String(200, "CSRF token is valid") }) h.Spin() @@ -253,10 +253,10 @@ func main() { h.Use(csrf.New(csrf.WithKeyLookUp("form:csrf"))) h.GET("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, csrf.GetToken(ctx)) + c.String(200, csrf.GetToken(ctx)) }) h.POST("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "CSRF token is valid") + c.String(200, "CSRF token is valid") }) h.Spin() @@ -291,8 +291,8 @@ import ( "github.com/hertz-contrib/sessions/cookie" ) -func isPostMethod(_ context.Context, ctx *app.RequestContext) bool { - if string(ctx.Method()) == "POST" { +func isPostMethod(_ context.Context, c *app.RequestContext) bool { + if string(c.Method()) == "POST" { return true } else { return false @@ -309,7 +309,7 @@ func main() { h.Use(csrf.New(csrf.WithNext(isPostMethod))) h.POST("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "success even no csrf-token in header") + c.String(200, "success even no csrf-token in header") }) h.Spin() } @@ -356,7 +356,7 @@ import ( ) func myExtractor(ctx context.Context, c *app.RequestContext) (string, error) { - token := ctx.FormValue("csrf-token") + token := c.FormValue("csrf-token") if token == nil { return "", errors.New("missing token in form-data") } @@ -371,10 +371,10 @@ func main() { h.Use(csrf.New(csrf.WithExtractor(myExtractor))) h.GET("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, csrf.GetToken(ctx)) + c.String(200, csrf.GetToken(ctx)) }) h.POST("/protected", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, "CSRF token is valid") + c.String(200, "CSRF token is valid") }) h.Spin() diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/i18n.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/i18n.md index 884b8b2967..9187efefd2 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/i18n.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/i18n.md @@ -36,7 +36,7 @@ func main() { c.String(200, hertzI18n.MustGetMessage(c, &i18n.LocalizeConfig{ MessageID: "welcomeWithName", TemplateData: map[string]string{ - "name": ctx.Param("name"), + "name": c.Param("name"), }, })) }) @@ -85,7 +85,7 @@ func main() { c.String(200, hertzI18n.MustGetMessage(c, &i18n.LocalizeConfig{ MessageID: "welcomeWithName", TemplateData: map[string]string{ - "name": ctx.Param("name"), + "name": c.Param("name"), }, })) }) @@ -111,15 +111,15 @@ func MustGetMessage(c context.Context, param interface{}) string ```go h.GET("/:name", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, hertzI18n.MustGetMessage(c, &i18n.LocalizeConfig{ + c.String(200, hertzI18n.MustGetMessage(c, &i18n.LocalizeConfig{ MessageID: "welcomeWithName", TemplateData: map[string]string{ - "name": ctx.Param("name"), + "name": c.Param("name"), }, })) }) h.GET("/", func(ctx context.Context, c *app.RequestContext) { - ctx.String(200, hertzI18n.MustGetMessage(c, "welcome")) + c.String(200, hertzI18n.MustGetMessage(c, "welcome")) }) ``` @@ -174,7 +174,7 @@ func main() { c.String(200, hertzI18n.MustGetMessage(c, &i18n.LocalizeConfig{ MessageID: "welcomeWithName", TemplateData: map[string]string{ - "name": ctx.Param("name"), + "name": c.Param("name"), }, })) }) @@ -215,7 +215,7 @@ func main() { h.Use(hertzI18n.Localize( hertzI18n.WithGetLangHandle( func(ctx context.Context, c *app.RequestContext, defaultLang string) string { - lang := ctx.Query("lang") + lang := c.Query("lang") if lang == "" { return defaultLang } diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/jwt.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/jwt.md index 610f7b20a4..c9739bd0e3 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/jwt.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/jwt.md @@ -40,8 +40,8 @@ type login struct { var identityKey = "id" func PingHandler(ctx context.Context, c *app.RequestContext) { - user, _ := ctx.Get(identityKey) - ctx.JSON(200, utils.H{ + user, _ := c.Get(identityKey) + c.JSON(200, utils.H{ "message": fmt.Sprintf("username:%v", user.(*User).UserName), }) } diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/keyauth.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/keyauth.md index aa628a7d08..235fb64cb4 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/keyauth.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/keyauth.md @@ -36,8 +36,8 @@ func main() { keyauth.WithKeyLookUp("query:token", ""), )) h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - value, _ := ctx.Get("token") - ctx.JSON(consts.StatusOK, utils.H{"ping": value}) + value, _ := c.Get("token") + c.JSON(consts.StatusOK, utils.H{"ping": value}) }) h.Spin() } @@ -74,12 +74,12 @@ func main() { h := server.Default() h.Use(keyauth.New( keyauth.WithFilter(func(ctx context.Context, c *app.RequestContext) bool { - return string(ctx.GetHeader("admin")) == "test" + return string(c.GetHeader("admin")) == "test" }), )) h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - value, _ := ctx.Get("token") - ctx.JSON(consts.StatusOK, utils.H{"ping": value}) + value, _ := c.Get("token") + c.JSON(consts.StatusOK, utils.H{"ping": value}) }) h.Spin() } @@ -121,8 +121,8 @@ func main() { }), )) h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - value, _ := ctx.Get("token") - ctx.JSON(consts.StatusOK, utils.H{"ping": value}) + value, _ := c.Get("token") + c.JSON(consts.StatusOK, utils.H{"ping": value}) }) h.Spin() } @@ -155,8 +155,8 @@ func main() { }), )) h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - value, _ := ctx.Get("token") - ctx.JSON(consts.StatusOK, utils.H{"ping": value}) + value, _ := c.Get("token") + c.JSON(consts.StatusOK, utils.H{"ping": value}) }) h.Spin() } @@ -177,10 +177,10 @@ type KeyAuthErrorHandler func(context.Context, *app.RequestContext, error) ```go func errHandler(ctx context.Context, c *app.RequestContext, err error) { if err == ErrMissingOrMalformedAPIKey { - ctx.AbortWithMsg(err.Error(), http.StatusBadRequest) + c.AbortWithMsg(err.Error(), http.StatusBadRequest) return } - ctx.AbortWithMsg(err.Error(), http.StatusUnauthorized) + c.AbortWithMsg(err.Error(), http.StatusUnauthorized) } ``` @@ -213,8 +213,8 @@ func main() { keyauth.WithKeyLookUp("header:token", "Bearer"), )) h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - value, _ := ctx.Get("token") - ctx.JSON(consts.StatusOK, utils.H{"ping": value}) + value, _ := c.Get("token") + c.JSON(consts.StatusOK, utils.H{"ping": value}) }) h.Spin() } @@ -245,8 +245,8 @@ func main() { keyauth.WithContextKey("token"), )) h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - value, _ := ctx.Get("token") - ctx.JSON(consts.StatusOK, utils.H{"ping": value}) + value, _ := c.Get("token") + c.JSON(consts.StatusOK, utils.H{"ping": value}) }) h.Spin() } diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/paseto.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/paseto.md index 2d8195b892..653eacb2c6 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/paseto.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/paseto.md @@ -65,11 +65,11 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(http.StatusOK, token) + c.String(http.StatusOK, token) }) h.POST("/paseto", paseto.New(), func(ctx context.Context, c *app.RequestContext) { - ctx.String(http.StatusOK, "token is valid") + c.String(http.StatusOK, "token is valid") }) go performRequest() @@ -160,11 +160,11 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.POST("/paseto", paseto.New(paseto.WithNext(next)), func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "token is valid") + c.String(consts.StatusOK, "token is valid") }) go performRequest() @@ -254,7 +254,7 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.GET("/paseto/witherrorfunc", func(ctx context.Context, c *app.RequestContext) { @@ -269,11 +269,11 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.POST("/paseto", paseto.New(paseto.WithErrorFunc(handler)), func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "token is valid") + c.String(consts.StatusOK, "token is valid") }) go performRequest() @@ -363,7 +363,7 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.GET("/paseto/withnosecret", func(ctx context.Context, c *app.RequestContext) { @@ -378,11 +378,11 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.POST("/paseto", paseto.New(paseto.WithSuccessHandler(handler)), func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "token is valid") + c.String(consts.StatusOK, "token is valid") }) go performRequest() @@ -451,11 +451,11 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.POST("/paseto", paseto.New(paseto.WithKeyLookUp("form:Authorization")), func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "token is valid") + c.String(consts.StatusOK, "token is valid") }) go performRequest() @@ -511,7 +511,7 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.POST("/paseto", paseto.New(paseto.WithTokenPrefix("Bearer ")), func(ctx context.Context, c *app.RequestContext) { @@ -595,7 +595,7 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) h.GET("/paseto/wrong-issuer", func(ctx context.Context, c *app.RequestContext) { now := time.Now() @@ -608,7 +608,7 @@ func main() { if err != nil { hlog.Error("generate token failed") } - ctx.String(consts.StatusOK, token) + c.String(consts.StatusOK, token) }) parseFunc, _ := paseto.NewV4PublicParseFunc(paseto.DefaultPublicKey, []byte(paseto.DefaultImplicit), paseto.WithIssuer("CloudWeGo-issuer")) diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/pprof.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/pprof.md index c49c30f5f6..329b0ef5f8 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/pprof.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/pprof.md @@ -78,7 +78,7 @@ func main() { pprof.Register(h, "dev/pprof") h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"}) + c.JSON(consts.StatusOK, utils.H{"ping": "pong"}) }) h.Spin() @@ -123,7 +123,7 @@ func main() { adminGroup := h.Group("/admin") adminGroup.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"}) + c.JSON(consts.StatusOK, utils.H{"ping": "pong"}) }) pprof.RouteRegister(adminGroup, "pprof") diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/recovery.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/recovery.md index c386fb6b43..71d938a0c3 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/recovery.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/recovery.md @@ -78,8 +78,8 @@ import ( func MyRecoveryHandler(ctx context.Context, c *app.RequestContext, err interface{}, stack []byte) { hlog.SystemLogger().CtxErrorf(c, "[Recovery] err=%v\nstack=%s", err, stack) - hlog.SystemLogger().Infof("Client: %s", ctx.Request.Header.UserAgent()) - ctx.AbortWithStatus(consts.StatusInternalServerError) + hlog.SystemLogger().Infof("Client: %s", c.Request.Header.UserAgent()) + c.AbortWithStatus(consts.StatusInternalServerError) } func main() { diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/sentry.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/sentry.md index f6b2b1bea7..769d3ce426 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/sentry.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/sentry.md @@ -72,7 +72,7 @@ func main() { hub.CaptureMessage("Just for debug") }) } - ctx.SetStatusCode(0) + c.SetStatusCode(0) }) h.Spin() diff --git a/content/zh/docs/hertz/tutorials/basic-feature/middleware/swagger.md b/content/zh/docs/hertz/tutorials/basic-feature/middleware/swagger.md index 1f1dbccba2..ec79c5c943 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/middleware/swagger.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/middleware/swagger.md @@ -129,7 +129,7 @@ import ( // @Produce application/json // @Router /ping [get] func PingHandler(ctx context.Context, c *app.RequestContext) { - ctx.JSON(200, map[string]string{ + c.JSON(200, map[string]string{ "ping": "pong", }) } diff --git a/content/zh/docs/hertz/tutorials/basic-feature/protocol/http2.md b/content/zh/docs/hertz/tutorials/basic-feature/protocol/http2.md index c7a9479f20..3094df030d 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/protocol/http2.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/protocol/http2.md @@ -94,7 +94,7 @@ func main() { h.POST("/", func(ctx context.Context, c *app.RequestContext) { var j map[string]string - _ = json.Unmarshal(ctx.Request.Body(), &j) + _ = json.Unmarshal(c.Request.Body(), &j) fmt.Printf("[server]: received request: %+v\n", j) r := map[string]string{ @@ -103,7 +103,7 @@ func main() { for k, v := range j { r[k] = v } - ctx.JSON(http.StatusOK, r) + c.JSON(http.StatusOK, r) }) go runClient() @@ -164,7 +164,7 @@ func main() { h.POST("/", func(ctx context.Context, c *app.RequestContext) { var j map[string]string - _ = json.Unmarshal(ctx.Request.Body(), &j) + _ = json.Unmarshal(c.Request.Body(), &j) fmt.Printf("server received request: %+v\n", j) r := map[string]string{ "msg": "hello world", @@ -172,7 +172,7 @@ func main() { for k, v := range j { r[k] = v } - ctx.JSON(http.StatusOK, r) + c.JSON(http.StatusOK, r) }) go runClient() @@ -271,7 +271,7 @@ func main() { h.POST("/", func(ctx context.Context, c *app.RequestContext) { var j map[string]string - _ = json.Unmarshal(ctx.Request.Body(), &j) + _ = json.Unmarshal(c.Request.Body(), &j) fmt.Printf("[server]: received request: %+v\n", j) r := map[string]string{ @@ -280,7 +280,7 @@ func main() { for k, v := range j { r[k] = v } - ctx.JSON(http.StatusOK, r) + c.JSON(http.StatusOK, r) }) go runClient() @@ -428,7 +428,7 @@ func main() { h.POST("/", func(ctx context.Context, c *app.RequestContext) { var j map[string]string - _ = json.Unmarshal(ctx.Request.Body(), &j) + _ = json.Unmarshal(c.Request.Body(), &j) fmt.Printf("[server]: received request: %+v\n", j) r := map[string]string{ @@ -437,7 +437,7 @@ func main() { for k, v := range j { r[k] = v } - ctx.JSON(http.StatusOK, r) + c.JSON(http.StatusOK, r) }) go runClient() diff --git a/content/zh/docs/hertz/tutorials/basic-feature/protocol/http3.md b/content/zh/docs/hertz/tutorials/basic-feature/protocol/http3.md index db5404f128..0e8cf3b301 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/protocol/http3.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/protocol/http3.md @@ -87,7 +87,7 @@ func run() { h.GET("/demo/tile", func(ctx context.Context, c *app.RequestContext) { // Small 40x40 png - ctx.Write([]byte{ + c.Write([]byte{ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x28, 0x01, 0x03, 0x00, 0x00, 0x00, 0xb6, 0x30, 0x2a, 0x2e, 0x00, 0x00, 0x00, @@ -99,11 +99,11 @@ func run() { }) h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"}) + c.JSON(consts.StatusOK, utils.H{"ping": "pong"}) }) h.GET("/struct", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, &Test{ + c.JSON(consts.StatusOK, &Test{ A: "aaa", B: "bbb", }) @@ -112,7 +112,7 @@ func run() { v1 := h.Group("/v1") { v1.GET("/hello/:name", func(ctx context.Context, c *app.RequestContext) { - fmt.Fprintf(ctx, "Hi %s, this is the response from Hertz.\n", ctx.Param("name")) + fmt.Fprintf(ctx, "Hi %s, this is the response from Hertz.\n", c.Param("name")) }) } diff --git a/content/zh/docs/hertz/tutorials/basic-feature/protocol/tls.md b/content/zh/docs/hertz/tutorials/basic-feature/protocol/tls.md index c8b38b33d2..1970cdea53 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/protocol/tls.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/protocol/tls.md @@ -251,7 +251,7 @@ func main() { // Ping handler h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "ping": "pong", }) }) @@ -302,7 +302,7 @@ func main() { // Ping handler h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "ping": "pong", }) }) @@ -346,7 +346,7 @@ func main() { // Ping handler h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "ping": "pong", }) }) diff --git a/content/zh/docs/hertz/tutorials/basic-feature/protocol/websocket.md b/content/zh/docs/hertz/tutorials/basic-feature/protocol/websocket.md index ae5806511c..e64196212b 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/protocol/websocket.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/protocol/websocket.md @@ -155,16 +155,16 @@ WebSocket 只是定义了一种交换任意消息的机制。这些消息是什 函数签名: ```go -func(ctx *app.RequestContext, status int, reason error) +func(c *app.RequestContext, status int, reason error) ``` 示例代码: ```go var upgrader = websocket.HertzUpgrader{ - Error: func(ctx *app.RequestContext, status int, reason error) { - ctx.Response.Header.Set("Sec-Websocket-Version", "13") - ctx.AbortWithMsg(reason.Error(), status) + Error: func(c *app.RequestContext, status int, reason error) { + c.Response.Header.Set("Sec-Websocket-Version", "13") + c.AbortWithMsg(reason.Error(), status) }, } ``` @@ -176,14 +176,14 @@ var upgrader = websocket.HertzUpgrader{ 函数签名: ```go -func(ctx *app.RequestContext) bool +func(c *app.RequestContext) bool ``` 默认实现: ```go -func fastHTTPCheckSameOrigin(ctx *app.RequestContext) bool { - origin := ctx.Request.Header.Peek("Origin") +func fastHTTPCheckSameOrigin(c *app.RequestContext) bool { + origin := c.Request.Header.Peek("Origin") if len(origin) == 0 { return true } @@ -191,7 +191,7 @@ func fastHTTPCheckSameOrigin(ctx *app.RequestContext) bool { if err != nil { return false } - return equalASCIIFold(u.Host, b2s(ctx.Host())) + return equalASCIIFold(u.Host, b2s(c.Host())) } ``` diff --git a/content/zh/docs/hertz/tutorials/basic-feature/render.md b/content/zh/docs/hertz/tutorials/basic-feature/render.md index b9471efd14..a4344d7678 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/render.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/render.md @@ -163,7 +163,7 @@ func main(){ //h.LoadHTMLFiles("render/html/index.tmpl") h.GET("/index", func(ctx context.Context, c *app.RequestContext) { - ctx.HTML(http.StatusOK, "index.tmpl", utils.H{ + c.HTML(http.StatusOK, "index.tmpl", utils.H{ "title": "Main website", }) }) @@ -221,7 +221,7 @@ func main() { h.LoadHTMLGlob("render/html/*") h.GET("/raw", func(ctx context.Context, c *app.RequestContext) { - ctx.HTML(http.StatusOK, "template1.html", map[string]interface{}{ + c.HTML(http.StatusOK, "template1.html", map[string]interface{}{ "now": time.Date(2017, 0o7, 0o1, 0, 0, 0, 0, time.UTC), }) }) diff --git a/content/zh/docs/hertz/tutorials/basic-feature/route.md b/content/zh/docs/hertz/tutorials/basic-feature/route.md index bfdd888149..f151ae0ea0 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/route.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/route.md @@ -142,7 +142,7 @@ func main() { v1 := h.Group("/v1", basic_auth.BasicAuth(map[string]string{"test": "test"})) v1.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK,"ping") + c.String(consts.StatusOK,"ping") }) h.Spin() } @@ -167,7 +167,7 @@ func main() { // use `Use` method v1.Use(basic_auth.BasicAuth(map[string]string{"test": "test"})) v1.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK,"ping") + c.String(consts.StatusOK,"ping") }) h.Spin() } @@ -289,7 +289,7 @@ import ( func main() { h := server.Default() h.AnyEX("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, app.GetHandlerName(ctx.Handler())) + c.String(consts.StatusOK, app.GetHandlerName(c.Handler())) }, "ping_handler") h.Spin() } @@ -331,7 +331,7 @@ import ( func main() { h := server.Default() h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"}) + c.JSON(consts.StatusOK, utils.H{"ping": "pong"}) }) routeInfo := h.Routes() hlog.Info(routeInfo) @@ -360,15 +360,15 @@ import ( func main() { h := server.Default(server.WithHandleMethodNotAllowed(true)) h.POST("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"}) + c.JSON(consts.StatusOK, utils.H{"ping": "pong"}) }) // set NoRoute handler h.NoRoute(func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "no route") + c.String(consts.StatusOK, "no route") }) // set NoMethod handler h.NoMethod(func(ctx context.Context, c *app.RequestContext) { - ctx.String(consts.StatusOK, "no method") + c.String(consts.StatusOK, "no method") }) h.Spin() diff --git a/content/zh/docs/hertz/tutorials/basic-feature/unit-test.md b/content/zh/docs/hertz/tutorials/basic-feature/unit-test.md index a82bf97daf..224cccf738 100644 --- a/content/zh/docs/hertz/tutorials/basic-feature/unit-test.md +++ b/content/zh/docs/hertz/tutorials/basic-feature/unit-test.md @@ -43,15 +43,15 @@ func TestCreateUtRequestContext(t *testing.T) { path := "/hey/dy" headerKey := "Connection" headerValue := "close" - ctx := ut.CreateUtRequestContext(method, path, &ut.Body{Body: bytes.NewBufferString(body), Len: len(body)}, + c := ut.CreateUtRequestContext(method, path, &ut.Body{Body: bytes.NewBufferString(body), Len: len(body)}, ut.Header{Key: headerKey, Value: headerValue}) - assert.DeepEqual(t, method, string(ctx.Method())) - assert.DeepEqual(t, path, string(ctx.Path())) - body1, err := ctx.Body() + assert.DeepEqual(t, method, string(c.Method())) + assert.DeepEqual(t, path, string(c.Path())) + body1, err := c.Body() assert.DeepEqual(t, nil, err) assert.DeepEqual(t, body, string(body1)) - assert.DeepEqual(t, headerValue, string(ctx.GetHeader(headerKey))) + assert.DeepEqual(t, headerValue, string(c.GetHeader(headerKey))) } ``` diff --git a/content/zh/docs/hertz/tutorials/framework-exten/protocol.md b/content/zh/docs/hertz/tutorials/framework-exten/protocol.md index 87cc33a0e5..a3579c5bef 100644 --- a/content/zh/docs/hertz/tutorials/framework-exten/protocol.md +++ b/content/zh/docs/hertz/tutorials/framework-exten/protocol.md @@ -179,19 +179,19 @@ type myServer struct { suite.Core } -func (m myServer) Serve(c context.Context, conn network.Conn) error { +func (m myServer) Serve(ctx context.Context, conn network.Conn) error { firstThreeBytes, _ := conn.Peek(3) if !bytes.Equal(firstThreeBytes, []byte("GET")) { return errors.NewPublic("not a GET method") } - ctx := m.GetCtxPool().Get().(*app.RequestContext) + c := m.GetCtxPool().Get().(*app.RequestContext) defer func() { - m.GetCtxPool().Put(ctx) + m.GetCtxPool().Put(c) conn.Skip(conn.Len()) conn.Flush() }() - ctx.Request.SetMethod("GET") - ctx.Request.SetRequestURI("/test") + c.Request.SetMethod("GET") + c.Request.SetRequestURI("/test") m.ServeHTTP(c, ctx) conn.WriteBinary([]byte("HTTP/1.1 200 OK\n" + "Server: hertz\n" + diff --git a/content/zh/docs/hertz/tutorials/framework-exten/response_writer.md b/content/zh/docs/hertz/tutorials/framework-exten/response_writer.md index 41cadf997e..eb554be759 100644 --- a/content/zh/docs/hertz/tutorials/framework-exten/response_writer.md +++ b/content/zh/docs/hertz/tutorials/framework-exten/response_writer.md @@ -37,7 +37,7 @@ Hertz 在 `app.RequestContext` 中提供了 `Response.HijackWriter` 方法让用 ```go h.GET("/hijack", func(ctx context.Context, c *app.RequestContext) { // Hijack the writer of Response - ctx.Response.HijackWriter(**yourResponseWriter**) + c.Response.HijackWriter(**yourResponseWriter**) }) ``` @@ -52,11 +52,11 @@ Hertz 在 `app.RequestContext` 中提供了 `Response.HijackWriter` 方法让用 ```go h.GET("/flush/chunk", func(ctx context.Context, c *app.RequestContext) { // Hijack the writer of Response - ctx.Response.HijackWriter(resp.NewChunkedBodyWriter(&ctx.Response, ctx.GetWriter())) + c.Response.HijackWriter(resp.NewChunkedBodyWriter(&c.Response, c.GetWriter())) for i := 0; i < 10; i++ { - ctx.Write([]byte(fmt.Sprintf("chunk %d: %s", i, strings.Repeat("hi~", i)))) // nolint: errcheck - ctx.Flush() // nolint: errcheck + c.Write([]byte(fmt.Sprintf("chunk %d: %s", i, strings.Repeat("hi~", i)))) // nolint: errcheck + c.Flush() // nolint: errcheck time.Sleep(200 * time.Millisecond) } }) diff --git a/content/zh/docs/hertz/tutorials/observability/log.md b/content/zh/docs/hertz/tutorials/observability/log.md index 31abf693f6..f5d986498f 100644 --- a/content/zh/docs/hertz/tutorials/observability/log.md +++ b/content/zh/docs/hertz/tutorials/observability/log.md @@ -20,8 +20,8 @@ func AccessLog() app.HandlerFunc { end := time.Now() latency := end.Sub(start).Microseconds hlog.CtxTracef(c, "status=%d cost=%d method=%s full_path=%s client_ip=%s host=%s", - ctx.Response.StatusCode(), latency, - ctx.Request.Header.Method(), ctx.Request.URI().PathOriginal(), ctx.ClientIP(), ctx.Request.Host()) + c.Response.StatusCode(), latency, + c.Request.Header.Method(), c.Request.URI().PathOriginal(), c.ClientIP(), c.Request.Host()) } } ``` diff --git a/content/zh/docs/hertz/tutorials/observability/monitoring.md b/content/zh/docs/hertz/tutorials/observability/monitoring.md index 1ce81ff11f..8601fb53b4 100644 --- a/content/zh/docs/hertz/tutorials/observability/monitoring.md +++ b/content/zh/docs/hertz/tutorials/observability/monitoring.md @@ -39,7 +39,7 @@ func main() { ··· h := server.Default(server.WithTracer(prometheus.NewServerTracer(":9091", "/hertz"))) h.GET("/ping", func(ctx context.Context, c *app.RequestContext) { - ctx.JSON(200, utils.H{"ping": "pong"}) + c.JSON(200, utils.H{"ping": "pong"}) }) h.Spin() ··· diff --git a/content/zh/docs/hertz/tutorials/service-governance/sentinel.md b/content/zh/docs/hertz/tutorials/service-governance/sentinel.md index f3038d4369..7e07de80d5 100644 --- a/content/zh/docs/hertz/tutorials/service-governance/sentinel.md +++ b/content/zh/docs/hertz/tutorials/service-governance/sentinel.md @@ -91,7 +91,7 @@ func main() { // customize block fallback if required // abort with status 429 by default adaptor.WithServerBlockFallback(func(ctx context.Context, c *app.RequestContext) { - ctx.AbortWithStatusJSON(400, utils.H{ + c.AbortWithStatusJSON(400, utils.H{ "err": "too many request; the quota used up", "code": 10222, }) diff --git a/content/zh/docs/hertz/tutorials/service-governance/service_discovery/etcd.md b/content/zh/docs/hertz/tutorials/service-governance/service_discovery/etcd.md index 05f30ecb36..f25c1d2e76 100644 --- a/content/zh/docs/hertz/tutorials/service-governance/service_discovery/etcd.md +++ b/content/zh/docs/hertz/tutorials/service-governance/service_discovery/etcd.md @@ -347,8 +347,8 @@ func main() { Weight: 10, Tags: nil, })) - h.GET("/ping", func(_ context.Context, ctx *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong2"}) + h.GET("/ping", func(_ context.Context, c *app.RequestContext) { + c.JSON(consts.StatusOK, utils.H{"ping": "pong2"}) }) h.Spin() } diff --git a/content/zh/docs/hertz/tutorials/service-governance/service_discovery/redis.md b/content/zh/docs/hertz/tutorials/service-governance/service_discovery/redis.md index e2670e8ce4..c009ef269a 100644 --- a/content/zh/docs/hertz/tutorials/service-governance/service_discovery/redis.md +++ b/content/zh/docs/hertz/tutorials/service-governance/service_discovery/redis.md @@ -483,8 +483,8 @@ func main() { Tags: nil, }), ) - h.GET("/ping", func(_ context.Context, ctx *app.RequestContext) { - ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"}) + h.GET("/ping", func(_ context.Context, c *app.RequestContext) { + c.JSON(consts.StatusOK, utils.H{"ping": "pong"}) }) h.Spin() } diff --git a/content/zh/docs/hertz/tutorials/service-migration/_index.md b/content/zh/docs/hertz/tutorials/service-migration/_index.md index fe95573600..eab3b0f53d 100644 --- a/content/zh/docs/hertz/tutorials/service-migration/_index.md +++ b/content/zh/docs/hertz/tutorials/service-migration/_index.md @@ -47,8 +47,8 @@ type HandlerFunc = func(ctx context.Context, c *app.RequestContext) ```Go // fasthttp + fasthttp router example -func Hello(ctx *fasthttp.RequestCtx) { - fmt.Fprintf(ctx, "Hello, %s!\n", ctx.UserValue("name")) +func Hello(c *fasthttp.RequestCtx) { + fmt.Fprintf(ctx, "Hello, %s!\n", c.UserValue("name")) } func main() { @@ -62,7 +62,7 @@ func main() { ```Go // the corresponding hertz example func Hello(ctx context.Context, c *app.RequestContext) { - fmt.Fprintf(ctx, "Hello, %s!\n", ctx.Param("name")) + fmt.Fprintf(ctx, "Hello, %s!\n", c.Param("name")) } func main() {