Query DNS TXT records using the Go standard library net.LookupTXT

by Hadley Bradley

Query DNS records

I’m working on a Windows service written in Go for which I needed a way of changing the execution state remotely. The service is installed on several computers within a secure Covid testing lab, and hence the configuration needs to be changed remotely to remove the need for visiting the site.

Initially, the software will be installed and used against the central development system. However, at some point, we’ll need to flip the switch and make the software run in production mode.

I realised I could set the run mode within a DNS TXT record for the applications domain name.

The application then periodically runs the lookupResultsModeFromDNS() function to query the TXT records using net.LookupTXT. After capturing all the TXT records, the function iterates over the results finding the runmode entry. Using the value of the runmode we set the environment boolean, which is used to control how the windows service connects to the backend.

func (app *App) lookupResultsModeFromDNS() {

    txtrecords, err := net.LookupTXT("hipres.app")
    if err != nil {
        log.Fatal(err.Error())
    }

    for _, txt := range txtrecords {
        if strings.Contains(txt, "runmode=") {
            mode := strings.Replace(txt, "runmode=", "", -1)

            switch mode {
                case "dev":
                    app.testEnvironment = true
                case "prod":
                    app.testEnvironment = false
                default:
                    app.testEnvironment = true
            }
        }
    }
}

 


If you’ve found this tutorial or blog post interesting, or it's helped you solve a particular issue, then please consider buying me a virtual coffee as a way of saying thanks. You can even leave me a comment. It’ll give me the freedom to write more technical content.