1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
package main
import (
"encoding/csv"
"fmt"
"io"
"os"
)
// getURLFromShortcode looks for the shortcode inside the file
// specified by filename (default "urls.csv" in the top-level project
// directory), and returns the associated URL.
//
// Right now we perform an O(n) search across the entire file just to
// get a single URL, so there's room for improvement here.
func getURLFromShortcode(filename, shortcode string) (string, error) {
f, err := os.Open(filename)
if err != nil {
return "", fmt.Errorf("can't open shortcode file: %w", err)
}
defer f.Close()
r := csv.NewReader(f)
// Read, vet, and discard the column-header row.
header, err := r.Read()
if err != nil {
return "", fmt.Errorf("missing header line: %w", err)
}
if header[0] != "shortcode" || header[1] != "url" {
return "", fmt.Errorf("invalid CSV header: %v", header)
}
for i := 1; ; i++ {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return "", fmt.Errorf("error reading %s, row %d: %w", filename, i, err)
}
if record[0] == shortcode {
return record[1], nil
}
}
return "", fmt.Errorf("no URL with shortcode %s", shortcode)
}
|