move config parsing into a separate module, fix project name

This commit is contained in:
Von Random 2025-02-09 16:06:39 +02:00
parent 0ab510adef
commit d6d8b1a9a6
4 changed files with 46 additions and 25 deletions

18
config/config.go Normal file
View file

@ -0,0 +1,18 @@
package config
import (
"log"
"os"
"gopkg.in/yaml.v3"
)
func Parse(path string, spec interface{}) error {
configData, err := os.ReadFile(path)
if err != nil {
log.Fatal(err)
return err
}
err = yaml.Unmarshal(configData, spec)
return nil
}

15
main.go
View file

@ -2,18 +2,25 @@ package main
import (
"log"
"os"
"time"
"mechanus.net/pgobot/matcher"
"mechanus.net/pgobot/responder"
"mechanus.net/pgbot/config"
"mechanus.net/pgbot/matcher"
"mechanus.net/pgbot/responder"
"gopkg.in/telebot.v4"
)
type ConfigSpec struct {
Token string `yaml:"token"`
}
func main() {
var conf ConfigSpec
config.Parse("config.yml", &conf)
pref := telebot.Settings{
Token: os.Getenv("TOKEN"),
Token: conf.Token,
Poller: &telebot.LongPoller{Timeout: 10 * time.Second},
}

View file

@ -1,12 +1,16 @@
package matcher
import (
"os"
"regexp"
"gopkg.in/yaml.v3"
"mechanus.net/pgbot/config"
)
type tokenSpec struct {
Token string `yaml:"token"`
Regex []string `yaml:"regex"`
}
type Matcher struct {
tokens []TokenCompiled
}
@ -16,11 +20,11 @@ type TokenCompiled struct {
regex []*regexp.Regexp
}
func createToken(token string, regexList []string) TokenCompiled {
func createToken(spec tokenSpec) TokenCompiled {
result := new(TokenCompiled)
result.token = token
result.regex = make([]*regexp.Regexp, len(regexList))
for i, regex := range regexList {
result.token = spec.Token
result.regex = make([]*regexp.Regexp, len(spec.Regex))
for i, regex := range spec.Regex {
result.regex[i] = regexp.MustCompile(regex)
}
return *result
@ -46,22 +50,14 @@ func (m *Matcher) Tokenize(input string) []string {
return result
}
func InitMatcher(config string) *Matcher {
configData, err := os.ReadFile(config)
if err != nil {
panic(err)
}
var configMap map[string][]string
func InitMatcher(tokenPath string) *Matcher {
var list []tokenSpec
_ = config.Parse(tokenPath, &list)
err = yaml.Unmarshal(configData, &configMap)
if err != nil {
panic(err)
}
tokens := make([]TokenCompiled, 0, len(list))
tokens := make([]TokenCompiled, 0, len(configMap))
for k, v := range configMap {
tokensCompiled := createToken(k, v)
for _, spec := range list {
tokensCompiled := createToken(spec)
tokens = append(tokens, tokensCompiled)
}
result := new(Matcher)

View file

@ -3,7 +3,7 @@ package responder
import (
"strings"
"mechanus.net/pgobot/matcher"
"mechanus.net/pgbot/matcher"
"gopkg.in/telebot.v4"
)