Skip to content

Commit

Permalink
flathttp: add max duration to wait until we timeout a request
Browse files Browse the repository at this point in the history
  • Loading branch information
lithdew committed May 24, 2020
1 parent 5e30c01 commit fb7afd5
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions flathttp/middleware.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,43 @@
package flathttp

import (
"context"
"errors"
"net/http"
"strconv"
"time"
)

type Middleware struct {
MinContentLength int64 // inclusive
MaxContentLength int64 // inclusive

Timeout time.Duration // max duration we are allowing a request to take

Accepts []string // content types that are accepted
}

func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if m.Timeout > 0 {
ctx, cancel := context.WithTimeout(r.Context(), m.Timeout)

defer func() {
cancel()

if !errors.Is(ctx.Err(), context.DeadlineExceeded) {
return
}

tmpl := `{"error": "request took too long", "max_timeout": "[[TIMEOUT]]"}`

w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")

w.WriteHeader(http.StatusGatewayTimeout)
w.Write(T(tmpl, F{"TIMEOUT": m.Timeout.String()}))
}()
}

if r.ContentLength <= m.MinContentLength || r.ContentLength >= m.MaxContentLength {
tmpl := `{"error": "content length is not acceptable", "given": [[GIVEN]], "min": [[MIN]], "max": [[MAX]]}`

Expand Down

0 comments on commit fb7afd5

Please sign in to comment.