Skip to content

Commit

Permalink
Add a Gin middleware for limiting the maximum request size
Browse files Browse the repository at this point in the history
  • Loading branch information
justinclift committed Jan 4, 2024
1 parent d5482db commit 154f0c1
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,13 +191,8 @@ func currentReleaseHandler(c *gin.Context) {

// Handler for download requests
func fileHandler(c *gin.Context) {
// TODO: How to do this with Gin?
// Set the maximum accepted http request size, for safety
//r.Body = http.MaxBytesReader(w, r.Body, 4096) // 4k seems like a reasonable max size

fileName := c.Param("filename")

// If the requested file is unknown, then abort
fileName := c.Param("filename")
ts, ok := timeStamps[fileName]
if !ok {
fmt.Fprintf(c.Writer, "Unknown file requested")
Expand Down Expand Up @@ -551,6 +546,14 @@ func readConfig() (err error) {
return
}

// maxSizeMiddleware limits the maximum request size, to help prevent DOS attacks
func maxSizeMiddleware(maxSize int64) gin.HandlerFunc {
return func(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxSize)
c.Next()
}
}

// rootHandler serves the html index page that lists the available downloads
func rootHandler(c *gin.Context) {
c.HTML(http.StatusOK, "downloads", nil)
Expand All @@ -570,6 +573,9 @@ func setupRouter(testingMode bool) (router *gin.Engine, err error) {
router.Use(gin.Logger())
}

// Limit the maximum size (in bytes) of incoming requests
router.Use(maxSizeMiddleware(8192)) // 8k seems like a reasonable max size

// Add gzip middleware
router.Use(gzip.Gzip(gzip.DefaultCompression))

Expand Down

0 comments on commit 154f0c1

Please # to comment.