konbata/perrors.go

94 lines
1.8 KiB
Go

package main
import (
"bufio"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"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{
Code: gemini.Status(code),
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()
}