Blame
Date:
Sat Jan 8 15:47:57 2022 UTC
Message:
fetch the title also for gemini URLs
01
2022-01-08
op
package main
02
2022-01-08
op
03
2022-01-08
op
import (
04
2022-01-08
op
"bufio"
05
2022-01-08
op
"context"
06
2022-01-08
op
"errors"
07
2022-01-08
op
"regexp"
08
2022-01-08
op
"strings"
09
2022-01-08
op
10
2022-01-08
op
gemini "git.sr.ht/~adnano/go-gemini"
11
2022-01-08
op
)
12
2022-01-08
op
13
2022-01-08
op
var (
14
2022-01-08
op
ErrNoTitle = errors.New(`no title found`)
15
2022-01-08
op
16
2022-01-08
op
title1 = regexp.MustCompile(`^#[^#]`)
17
2022-01-08
op
title2 = regexp.MustCompile(`^##[^#]`)
18
2022-01-08
op
title3 = regexp.MustCompile(`^###`)
19
2022-01-08
op
)
20
2022-01-08
op
21
2022-01-08
op
func geminiTitle(url string) (string, error) {
22
2022-01-08
op
client := gemini.Client{}
23
2022-01-08
op
ctx := context.Background()
24
2022-01-08
op
resp, err := client.Get(ctx, url)
25
2022-01-08
op
if err != nil {
26
2022-01-08
op
return "", err
27
2022-01-08
op
}
28
2022-01-08
op
defer resp.Body.Close()
29
2022-01-08
op
30
2022-01-08
op
if resp.Status != 20 || !strings.HasPrefix(resp.Meta, "text/gemini") {
31
2022-01-08
op
return "", ErrNoTitle
32
2022-01-08
op
}
33
2022-01-08
op
34
2022-01-08
op
var t2, t3 string
35
2022-01-08
op
36
2022-01-08
op
scanner := bufio.NewScanner(resp.Body)
37
2022-01-08
op
for scanner.Scan() {
38
2022-01-08
op
line := scanner.Text()
39
2022-01-08
op
40
2022-01-08
op
switch {
41
2022-01-08
op
case title1.MatchString(line):
42
2022-01-08
op
return line, nil
43
2022-01-08
op
case title2.MatchString(line) && t2 == "":
44
2022-01-08
op
t2 = line
45
2022-01-08
op
case title3.MatchString(line) && t3 == "":
46
2022-01-08
op
t3 = line
47
2022-01-08
op
}
48
2022-01-08
op
}
49
2022-01-08
op
50
2022-01-08
op
if t2 != "" {
51
2022-01-08
op
return t2, nil
52
2022-01-08
op
}
53
2022-01-08
op
54
2022-01-08
op
if t3 != "" {
55
2022-01-08
op
return t3, nil
56
2022-01-08
op
}
57
2022-01-08
op
58
2022-01-08
op
return "", ErrNoTitle
59
2022-01-08
op
}
Omar Polo