dns

DNS client and server implementations using the Go project's dnsmessage package
Log | Files | Refs | README | LICENSE

config.go (1269B)


      1 package main
      2 
      3 import (
      4 	"bufio"
      5 	"fmt"
      6 	"io"
      7 	"os"
      8 	"strings"
      9 )
     10 
     11 type config struct {
     12 	forwardaddr string
     13 	listenaddr  string
     14 	usetls      bool
     15 }
     16 
     17 func configFromFile(name string) (config, error) {
     18 	f, err := os.Open(name)
     19 	if err != nil {
     20 		return config{}, err
     21 	}
     22 	defer f.Close()
     23 	return parseConfig(f)
     24 }
     25 
     26 func parseConfig(r io.Reader) (config, error) {
     27 	sc := bufio.NewScanner(r)
     28 	var c config
     29 	for sc.Scan() {
     30 		line := strings.TrimSpace(sc.Text())
     31 		if strings.HasPrefix(line, "#") {
     32 			continue // skip config comments
     33 		}
     34 		fields := strings.Fields(line)
     35 		switch k := fields[0]; k {
     36 		case "listen":
     37 			if len(fields) < 2 {
     38 				return c, fmt.Errorf("missing value for key %s", k)
     39 			} else if len(fields) > 2 {
     40 				return c, fmt.Errorf("too many values for key %s", k)
     41 			}
     42 			c.listenaddr = fields[1]
     43 		case "forward":
     44 			if len(fields) < 2 {
     45 				return c, fmt.Errorf("missing value for key %s", k)
     46 			} else if len(fields) > 3 {
     47 				return c, fmt.Errorf("too many values for key %s", k)
     48 			}
     49 			c.forwardaddr = fields[1]
     50 			if len(fields) == 3 {
     51 				if fields[2] == "tls" {
     52 					c.usetls = true
     53 				} else {
     54 					return c, fmt.Errorf("invalid tls option in forward")
     55 				}
     56 			}
     57 		default:
     58 			return c, fmt.Errorf("unknown key %s", k)
     59 		}
     60 	}
     61 	return c, nil
     62 }