Home  >  Article  >  Backend Development  >  golang gin provides a route for different queries

golang gin provides a route for different queries

PHPz
PHPzforward
2024-02-14 11:27:08530browse

golang gin 为不同的查询提供一条路线

php Editor Xinyi will introduce you to a powerful Web framework, Golang Gin. Gin is a lightweight web framework based on Golang that provides a concise and efficient route for different queries. Whether it is a GET request or a POST request, Gin can handle it easily, making your development process simpler and faster. Whether processing JSON data or HTML templates, Gin provides rich functionality and flexible scalability. Whether you are a beginner or an experienced developer, Gin is your best choice.

Question content

Is it possible to have a route containing :item (name) or :id in gin?

Example:

r.get("/inventories/(:item|:id)", controllers.findinventory)

Then I might do something similar...

func FindInventory(g *gin.Context) {
    var inv models.Inventory

    if item:
       err := models.DB.Where("item = ?", g.Param("item")).First(&inv).Error
    else:
       err := models.DB.Where("id = ?", g.Param("id")).First(&inv).Error
       
    if err != nil {
        g.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
        return
    }

    g.JSON(http.StatusOK, gin.H{"data": inv})
}

Or is there a way to use one route to perform both types of queries?

Solution

No, this operation is not supported. But there must be some way to differentiate item and id. So it's easy to implement the logic yourself.

like this:

r.get("/inventories/:item", controllers.findinventory)
func FindInventory(g *gin.Context) {
    var inv models.Inventory

    item := g.Param("item")
    id, err := strconv.Atoi(item)
    if err != nil {
        err := models.DB.Where("item = ?", item).First(&inv).Error
    } else {
        err := models.DB.Where("id = ?", id).First(&inv).Error
    }
    if err != nil {
        g.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
        return
    }

    g.JSON(http.StatusOK, gin.H{"data": inv})
}

But if it cannot be distinguished, then you need to have two separate request paths, such as

  • /inventories/by-item/:item
  • and /inventories/by-id/:id

2023-05-31 Update: Merged comments from @epicadidash and @boyvinall into the answer. Thanks!

The above is the detailed content of golang gin provides a route for different queries. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete