github.com/xuyutom/docker@v1.6.0/pkg/networkfs/etchosts/etchosts.go (about)

     1  package etchosts
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"io/ioutil"
     8  	"regexp"
     9  )
    10  
    11  type Record struct {
    12  	Hosts string
    13  	IP    string
    14  }
    15  
    16  func (r Record) WriteTo(w io.Writer) (int64, error) {
    17  	n, err := fmt.Fprintf(w, "%s\t%s\n", r.IP, r.Hosts)
    18  	return int64(n), err
    19  }
    20  
    21  var defaultContent = []Record{
    22  	{Hosts: "localhost", IP: "127.0.0.1"},
    23  	{Hosts: "localhost ip6-localhost ip6-loopback", IP: "::1"},
    24  	{Hosts: "ip6-localnet", IP: "fe00::0"},
    25  	{Hosts: "ip6-mcastprefix", IP: "ff00::0"},
    26  	{Hosts: "ip6-allnodes", IP: "ff02::1"},
    27  	{Hosts: "ip6-allrouters", IP: "ff02::2"},
    28  }
    29  
    30  func Build(path, IP, hostname, domainname string, extraContent []Record) error {
    31  	content := bytes.NewBuffer(nil)
    32  	if IP != "" {
    33  		var mainRec Record
    34  		mainRec.IP = IP
    35  		if domainname != "" {
    36  			mainRec.Hosts = fmt.Sprintf("%s.%s %s", hostname, domainname, hostname)
    37  		} else {
    38  			mainRec.Hosts = hostname
    39  		}
    40  		if _, err := mainRec.WriteTo(content); err != nil {
    41  			return err
    42  		}
    43  	}
    44  
    45  	for _, r := range defaultContent {
    46  		if _, err := r.WriteTo(content); err != nil {
    47  			return err
    48  		}
    49  	}
    50  
    51  	for _, r := range extraContent {
    52  		if _, err := r.WriteTo(content); err != nil {
    53  			return err
    54  		}
    55  	}
    56  
    57  	return ioutil.WriteFile(path, content.Bytes(), 0644)
    58  }
    59  
    60  func Update(path, IP, hostname string) error {
    61  	old, err := ioutil.ReadFile(path)
    62  	if err != nil {
    63  		return err
    64  	}
    65  	var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)", regexp.QuoteMeta(hostname)))
    66  	return ioutil.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2")), 0644)
    67  }