func handleRequest(c *gin.Context) { name := c.DefaultQuery("name", "default name") c.JSON(200, gin.H{"message": "Hello " + name}) }
func handleRequest(c *gin.Context) { name, err := c.GetQuery("name") if err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"message": "Invalid query parameter"}) return } c.JSON(200, gin.H{"message": "Hello " + name}) }In this example, we use the GetQuery method instead of DefaultQuery to retrieve a query parameter. The GetQuery method returns an error if the query parameter is not present in the request. We handle this error by returning a JSON response with a 400 Bad Request status code and a message explaining the error. This is a better practice than using DefaultQuery with a default value, as it avoids unexpected behavior in case of missing or invalid input. Overall, the gin-gonic/gin package is a powerful package for creating RESTful APIs in Go. Its use of the Context object and its various methods like DefaultQuery make it easy to handle HTTP requests and responses in a clean and concise way.