Skip to content

Commit

Permalink
refactor: MaxFileSizeInBytes
Browse files Browse the repository at this point in the history
  • Loading branch information
lidel committed Sep 23, 2022
1 parent 8d41a5e commit 903a8a0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 13 deletions.
21 changes: 9 additions & 12 deletions redirects.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package redirects

import (
"bufio"
"bytes"
"fmt"
"io"
"net/url"
Expand All @@ -15,7 +14,7 @@ import (
)

// 64 KiB
const maxFileSizeInBytes = 65536
const MaxFileSizeInBytes = 65536

// A Rule represents a single redirection or rewrite rule.
type Rule struct {
Expand Down Expand Up @@ -96,17 +95,15 @@ func Must(v []Rule, err error) []Rule {

// Parse the given reader.
func Parse(r io.Reader) (rules []Rule, err error) {
// not too large
b, err := bufio.NewReaderSize(r, maxFileSizeInBytes+1).Peek(maxFileSizeInBytes + 1)
if err != nil && err != io.EOF {
return nil, err
}
if len(b) > maxFileSizeInBytes {
return nil, fmt.Errorf("redirects file size cannot exceed %d bytes", maxFileSizeInBytes)
}

s := bufio.NewScanner(bytes.NewReader(b))
limiter := &io.LimitedReader{R: r, N: MaxFileSizeInBytes + 1}
s := bufio.NewScanner(limiter)
for s.Scan() {
// detect when we've read one byte beyond MaxFileSizeInBytes
// and return user-friendly error
if limiter.N <= 0 {
return nil, fmt.Errorf("redirects file size cannot exceed %d bytes", MaxFileSizeInBytes)
}

line := strings.TrimSpace(s.Text())

// empty
Expand Down
2 changes: 1 addition & 1 deletion redirects_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func TestParse(t *testing.T) {
totalBytes := 0

var b bytes.Buffer
for totalBytes <= maxFileSizeInBytes {
for totalBytes <= MaxFileSizeInBytes {
totalBytes += bytesPerLine
b.WriteString(line + "\n")
}
Expand Down

0 comments on commit 903a8a0

Please sign in to comment.