reject non-3xx status codes; close the CSV file; add tests
CI / go-tests (pull_request) Successful in 2m4s

A row with a status code outside 3xx (e.g. "0" from a typo) was accepted
at load and then panicked net/http's WriteHeader on the first matching
request. ReadCsvRedirects now rejects anything that isn't 300-399, with a
line number in the message, and reports a non-numeric code clearly.

Also defer reader.Close() (the file was left open for the process
lifetime) and drop the unreachable "row == nil" check.

Adds internal/{csv,redirect,http}_test.go covering CSV parsing (valid,
reordered headings, header-only, missing heading, non-numeric and non-3xx
status, ragged row, missing file), Redirects.Find / Redirect.Match, and
ServeHTTP (redirect, 404, query string dropped).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-07 14:19:44 +01:00
co-authored by Claude Sonnet 5
parent 1dfa60a237
commit 68546badb3
4 changed files with 198 additions and 9 deletions
+9 -9
View File
@@ -3,6 +3,7 @@ package internal
import (
"encoding/csv"
"errors"
"fmt"
"io"
"os"
"strconv"
@@ -25,6 +26,7 @@ func ReadCsvRedirects(file string) (Redirects, error) {
if err != nil {
return nil, err
}
defer reader.Close()
csvReader := csv.NewReader(reader)
@@ -44,7 +46,7 @@ func ReadCsvRedirects(file string) (Redirects, error) {
// Read data
redirects := Redirects{}
for {
for line := 2; ; line++ {
row, err := csvReader.Read()
if err != nil {
if errors.Is(err, io.EOF) {
@@ -52,22 +54,20 @@ func ReadCsvRedirects(file string) (Redirects, error) {
}
return nil, err
}
if row == nil {
break
}
statusCode, err := strconv.Atoi(row[statusCol])
if err != nil {
return nil, err
return nil, fmt.Errorf("line %d: status code %q is not a number", line, row[statusCol])
}
if statusCode < 300 || statusCode > 399 {
return nil, fmt.Errorf("line %d: status code %d is not a redirect (must be 3xx)", line, statusCode)
}
redirect := &Redirect{
redirects = append(redirects, &Redirect{
From: row[fromCol],
To: row[toCol],
StatusCode: statusCode,
}
redirects = append(redirects, redirect)
})
}
return redirects, nil