doggo/cmd/doggo-v1/parse.go

46 lines
1.4 KiB
Go
Raw Normal View History

2020-12-10 10:39:05 +01:00
package main
2020-12-10 17:14:04 +01:00
import (
"strings"
2020-12-10 10:39:05 +01:00
2020-12-10 17:14:04 +01:00
"github.com/miekg/dns"
)
2020-12-10 10:39:05 +01:00
2020-12-17 12:27:44 +01:00
// loadUnparsedArgs tries to parse all the arguments
// which are unparsed by `flag` library. These arguments don't have any specific
2020-12-10 17:14:04 +01:00
// order so we have to deduce based on the pattern of argument.
// For eg, a nameserver must always begin with `@`. In this
2020-12-17 12:27:44 +01:00
// pattern we deduce the arguments and append it to the
// list of internal query flags.
// In case an argument isn't able to fit in any of the existing
// pattern it is considered to be a "hostname".
// Eg of unparsed argument: `dig mrkaran.dev @1.1.1.1 AAAA`
// where `@1.1.1.1` and `AAAA` are "unparsed" args.
// Returns a list of nameserver, queryTypes, queryClasses, queryNames.
func loadUnparsedArgs(args []string) ([]string, []string, []string, []string) {
var ns, qt, qc, qn []string
for _, arg := range args {
2020-12-10 17:14:04 +01:00
if strings.HasPrefix(arg, "@") {
ns = append(ns, strings.Trim(arg, "@"))
2020-12-10 17:14:04 +01:00
} else if _, ok := dns.StringToType[strings.ToUpper(arg)]; ok {
qt = append(qt, arg)
2020-12-10 17:14:04 +01:00
} else if _, ok := dns.StringToClass[strings.ToUpper(arg)]; ok {
qc = append(qc, arg)
2020-12-10 17:14:04 +01:00
} else {
// if nothing matches, consider it's a query name.
qn = append(qn, arg)
2020-12-10 17:14:04 +01:00
}
}
return ns, qt, qc, qn
2020-12-10 17:14:04 +01:00
}
// contains is a helper method to check if a paritcular element exists in the slice.
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}