logoalt Hacker News

ricardobeatyesterday at 11:57 PM2 repliesview on HN

go is slightly more verbose (surprise) but you can achieve the same thing using struct binding in gin:

    type DatasetStatsQuery struct {
        Verbose bool `form:"verbose"`
    }
    
    func DatasetStatsHandler(c *gin.Context) {
        datasetID := c.Param("dataset_id")
        var query DatasetStatsQuery
        if err := c.ShouldBindQuery(&query); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        // query.Verbose == bool
    }}
This is actually a great example - what happens in that Rust version when the input parsing fails? Go makes it explicit.

Replies

sheepttoday at 3:18 AM

I'm not sure if that's a great example. What kind of errors could ShouldBindQuery return?

I would assume Axum returns a bad request error for you when query parsing fails, but if you do want more control over how the error is handled, you can change the parameter type to Result<Query<bool>, QueryRejection>, and the type system itself documents precisely what errors you can match against.[0]

[0]: https://docs.rs/axum/latest/axum/extract/rejection/enum.Quer...

sieabahlparktoday at 4:27 AM

[dead]