Release / build-and-push (push) Skipped
Build / build-and-push (push) Successful in 1m7s
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>
75 lines
1.4 KiB
Go
75 lines
1.4 KiB
Go
package internal
|
|
|
|
import (
|
|
"encoding/csv"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"strconv"
|
|
)
|
|
|
|
type Headings []string
|
|
|
|
func (h Headings) IndexOf(heading string) int {
|
|
for i, value := range h {
|
|
if value == heading {
|
|
return i
|
|
}
|
|
}
|
|
|
|
return -1
|
|
}
|
|
|
|
func ReadCsvRedirects(file string) (Redirects, error) {
|
|
reader, err := os.Open(file)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer reader.Close()
|
|
|
|
csvReader := csv.NewReader(reader)
|
|
|
|
// Process headings
|
|
textHeadings, err := csvReader.Read()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
headings := Headings(textHeadings)
|
|
fromCol := headings.IndexOf("From")
|
|
toCol := headings.IndexOf("To")
|
|
statusCol := headings.IndexOf("Status Code")
|
|
if fromCol == -1 || toCol == -1 || statusCol == -1 {
|
|
return nil, errors.New("CSV must contain From, To, and Status Code headings")
|
|
}
|
|
|
|
// Read data
|
|
redirects := Redirects{}
|
|
|
|
for line := 2; ; line++ {
|
|
row, err := csvReader.Read()
|
|
if err != nil {
|
|
if errors.Is(err, io.EOF) {
|
|
break
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
statusCode, err := strconv.Atoi(row[statusCol])
|
|
if err != nil {
|
|
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)
|
|
}
|
|
|
|
redirects = append(redirects, &Redirect{
|
|
From: row[fromCol],
|
|
To: row[toCol],
|
|
StatusCode: statusCode,
|
|
})
|
|
}
|
|
|
|
return redirects, nil
|
|
}
|