konbata/perrors.go

94 lines
1.8 KiB
Go
Raw Normal View History

2021-08-11 10:49:59 +00:00
package main
import (
"bufio"
"net/url"
2021-08-11 13:22:30 +00:00
"os"
2021-08-11 10:49:59 +00:00
"path/filepath"
2021-08-11 13:22:30 +00:00
"strconv"
"strings"
2021-08-11 10:49:59 +00:00
"git.sr.ht/~adnano/go-gemini"
)
var perrors map[string]PError
type PError struct {
Code gemini.Status
Message string
}
func populatePErrors() error {
file, err := os.OpenFile(filepath.Join(xdgDataHome(), "konbata", "perrors"), os.O_RDONLY|os.O_CREATE, 0600)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
perrors = make(map[string]PError)
unescaper := strings.NewReplacer("\\n", "\n", "\\\\", "\\")
for scanner.Scan() {
values := strings.SplitN(scanner.Text(), " ", 3)
if len(values) != 3 {
continue
}
url, err := url.Parse(values[0])
if err != nil {
continue
}
if url.Scheme != "gemini" {
continue
}
code, err := strconv.Atoi(values[1])
if err != nil {
continue
}
perrors[url.String()] = PError{
2021-08-11 13:22:30 +00:00
Code: gemini.Status(code),
2021-08-11 10:49:59 +00:00
Message: unescaper.Replace(values[2]),
}
}
return nil
}
func savePErrors() error {
file, err := os.OpenFile(filepath.Join(xdgDataHome(), "konbata", "perrors"), os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return err
}
defer file.Close()
err = file.Truncate(0)
if err != nil {
return err
}
writer := bufio.NewWriter(file)
escaper := strings.NewReplacer("\\", "\\\\", "\n", "\\n")
for url, perror := range perrors {
_, err = writer.WriteString(url)
if err != nil {
return err
}
_, err = writer.WriteRune(' ')
if err != nil {
return err
}
_, err = writer.WriteString(strconv.Itoa(int(perror.Code)))
if err != nil {
return err
}
_, err = writer.WriteRune(' ')
if err != nil {
return err
}
_, err = escaper.WriteString(writer, perror.Message)
if err != nil {
return err
}
_, err = writer.WriteRune('\n')
if err != nil {
return err
}
}
return writer.Flush()
}