Introduce middleware for parsing ID from URI

This commit is contained in:
eikendev 2020-08-02 17:06:11 +02:00
parent e1cd2d2f8e
commit 018ce2e537
No known key found for this signature in database
GPG key ID: A1BDB1B28C8EF694
8 changed files with 74 additions and 50 deletions

36
api/middleware.go Normal file
View file

@ -0,0 +1,36 @@
package api
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
)
type idInURI struct {
ID uint `uri:"id" binding:"required"`
}
// RequireIDInURI returns a Gin middleware which requires an ID to be supplied in the URI of the request.
func RequireIDInURI() gin.HandlerFunc {
return func(ctx *gin.Context) {
var requestModel idInURI
if err := ctx.BindUri(&requestModel); err != nil {
return
}
ctx.Set("id", requestModel.ID)
}
}
func getID(ctx *gin.Context) (uint, error) {
id, ok := ctx.MustGet("user").(uint)
if !ok {
err := errors.New("an error occured while retrieving ID from context")
ctx.AbortWithError(http.StatusInternalServerError, err)
return 0, err
}
return id, nil
}