amuz.es/src/infra/goutils@v0.1.3/net/ipv4_resolver.go (about)

     1  package net
     2  
     3  import (
     4  	"context"
     5  	"github.com/benburkert/dns"
     6  	"net"
     7  )
     8  
     9  func ReplaceDefaultDnsResolver(){
    10  	cli := &dns.Client{Resolver: &PreferIPV4Resolver{}}
    11  	net.DefaultResolver.PreferGo = true
    12  	net.DefaultResolver.Dial = cli.Dial
    13  }
    14  
    15  type PreferIPV4Resolver struct{}
    16  
    17  func (p *PreferIPV4Resolver) ServeDNS(ctx context.Context, w dns.MessageWriter, r *dns.Query) {
    18  	if r.Questions[0].Type == dns.TypeAAAA {
    19  		w.Status(dns.ServFail)
    20  	} else if msg, err := w.Recur(ctx); err != nil {
    21  		w.Status(dns.ServFail)
    22  	} else {
    23  		p.writeMessage(w, msg)
    24  	}
    25  }
    26  
    27  func (p *PreferIPV4Resolver) writeMessage(w dns.MessageWriter, msg *dns.Message) {
    28  	w.Status(msg.RCode)
    29  	w.Authoritative(msg.Authoritative)
    30  	w.Recursion(msg.RecursionAvailable)
    31  
    32  	for _, res := range msg.Answers {
    33  		w.Answer(res.Name, res.TTL, res.Record)
    34  	}
    35  	for _, res := range msg.Authorities {
    36  		w.Authority(res.Name, res.TTL, res.Record)
    37  	}
    38  	for _, res := range msg.Additionals {
    39  		w.Additional(res.Name, res.TTL, res.Record)
    40  	}
    41  }