Home >Backend Development >Golang >Can Go\'s Standard Library Specify a Custom DNS Server for Lookup Functions?
Can Go's Lookup Functions Specify a Server?*
Go's dnsclient library seamlessly loads configuration from /etc/resolv.conf, providing essential DNS functionality. However, certain scenarios demand the utilization of a specific DNS server. Does the Go standard library offer a mechanism akin to:
func LookupTXT(name string, dnsServer string) (txt []string, err error)
that can override the default DNS server while maintaining the integrity of /etc/resolv.conf?
Solution
Although the DNS client provided by Go does not directly support specifying a server during DNS resolution, there are alternative approaches to achieve this functionality. One viable option is to leverage the comprehensive dns library developed by miekg:
import ( "log" "github.com/miekg/dns" ) func main() { target := "microsoft.com" server := "8.8.8.8" c := dns.Client{} m := dns.Msg{} m.SetQuestion(target+".", dns.TypeA) r, t, err := c.Exchange(&m, server+":53") if err != nil { log.Fatal(err) } log.Printf("Took %v", t) if len(r.Answer) == 0 { log.Fatal("No results") } for _, ans := range r.Answer { Arecord := ans.(*dns.A) log.Printf("%s", Arecord.A) } }
Upon executing this code, you will obtain the resolved IP addresses for the target domain, demonstrating the effective use of a specified DNS server without compromising the system's default configuration.
The above is the detailed content of Can Go\'s Standard Library Specify a Custom DNS Server for Lookup Functions?. For more information, please follow other related articles on the PHP Chinese website!