x

Programs, configuration and documentation that don't fit anywhere else
Log | Files | Refs | README | LICENSE

config.go (831B)


      1 package main
      2 
      3 import (
      4 	"bufio"
      5 	"fmt"
      6 	"os"
      7 	"strings"
      8 )
      9 
     10 type Config struct {
     11 	BaseURL      string
     12 	Token        string
     13 	DefaultModel string
     14 }
     15 
     16 func readConfig(name string) (*Config, error) {
     17 	f, err := os.Open(name)
     18 	if err != nil {
     19 		return nil, err
     20 	}
     21 	defer f.Close()
     22 
     23 	var conf Config
     24 	sc := bufio.NewScanner(f)
     25 	for sc.Scan() {
     26 		if strings.HasPrefix(sc.Text(), "#") {
     27 			continue
     28 		} else if sc.Text() == "" {
     29 			continue
     30 		}
     31 
     32 		k, v, ok := strings.Cut(strings.TrimSpace(sc.Text()), " ")
     33 		if !ok {
     34 			return nil, fmt.Errorf("key %q: expected space after key", k)
     35 		}
     36 		v = strings.TrimSpace(v)
     37 		switch k {
     38 		case "token":
     39 			conf.Token = v
     40 		case "url":
     41 			conf.BaseURL = v
     42 		case "model":
     43 			conf.DefaultModel = v
     44 		default:
     45 			return nil, fmt.Errorf("unknown configuration key %q", k)
     46 		}
     47 	}
     48 	return &conf, sc.Err()
     49 }