func myHandler(c *gin.Context) { name := c.GetString("name") // do something with name } func main() { r := gin.Default() r.GET("/", myHandler) err := r.Run(":8080") if err != nil { panic(err) } }
func myMiddleware(c *gin.Context) { c.Set("my_key", "my_value") c.Next() } func myHandler(c *gin.Context) { myValue := c.GetString("my_key") // do something with myValue } func main() { r := gin.Default() r.Use(myMiddleware) r.GET("/", myHandler) err := r.Run(":8080") if err != nil { panic(err) } }In this example, we define a middleware function that sets a string value for the "my_key" key in the context, and then calls the next middleware or handler function in the chain. We then define a handler function that reads the value for the "my_key" key from the context and uses it in some way. Finally, we attach the middleware to the router using gin's Use() function. Overall, the Context.String function is a useful tool for reading string values from the request context in Go web applications.