package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "Hello World!", }) }) router.Run(":8080") }
package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.Use(func(c *gin.Context) { c.Next() if c.Writer.Status() == http.StatusNotFound { c.JSON(http.StatusNotFound, gin.H{"error": "Invalid request URL"}) } }) router.GET("/books/:title", func(c *gin.Context) { title := c.Param("title") c.JSON(http.StatusOK, gin.H{ "title": title, }) }) router.Run(":8080") }In this example, we define a middleware function that checks if a requested URL is valid. If the URL is invalid, it responds with an error message. We also define a GET request handler for a dynamic path using a parameter `title`. When a client sends a GET request to `/books/{title}`, the handler function extracts the title parameter and responds with a JSON message. Overall, the gin-gonic/gin package provides a comprehensive set of features for building scalable, reliable, and simple web applications and APIs in Go.