Blob


1 package main
3 import (
4 "bufio"
5 "context"
6 "errors"
7 "regexp"
8 "strings"
10 gemini "git.sr.ht/~adnano/go-gemini"
11 )
13 var (
14 ErrNoTitle = errors.New(`no title found`)
16 title1 = regexp.MustCompile(`^#[^#]`)
17 title2 = regexp.MustCompile(`^##[^#]`)
18 title3 = regexp.MustCompile(`^###`)
19 )
21 func geminiTitle(url string) (string, error) {
22 client := gemini.Client{}
23 ctx := context.Background()
24 resp, err := client.Get(ctx, url)
25 if err != nil {
26 return "", err
27 }
28 defer resp.Body.Close()
30 if resp.Status != 20 || !strings.HasPrefix(resp.Meta, "text/gemini") {
31 return "", ErrNoTitle
32 }
34 var t2, t3 string
36 scanner := bufio.NewScanner(resp.Body)
37 for scanner.Scan() {
38 line := scanner.Text()
40 switch {
41 case title1.MatchString(line):
42 return line, nil
43 case title2.MatchString(line) && t2 == "":
44 t2 = line
45 case title3.MatchString(line) && t3 == "":
46 t3 = line
47 }
48 }
50 if t2 != "" {
51 return t2, nil
52 }
54 if t3 != "" {
55 return t3, nil
56 }
58 return "", ErrNoTitle
59 }