github.com/guilhermebr/docker@v1.4.2-0.20150428121140-67da055cebca/pkg/etchosts/etchosts.go (about) 1 package etchosts 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "io/ioutil" 8 "regexp" 9 ) 10 11 // Structure for a single host record 12 type Record struct { 13 Hosts string 14 IP string 15 } 16 17 // Writes record to file and returns bytes written or error 18 func (r Record) WriteTo(w io.Writer) (int64, error) { 19 n, err := fmt.Fprintf(w, "%s\t%s\n", r.IP, r.Hosts) 20 return int64(n), err 21 } 22 23 // Default hosts config records slice 24 var defaultContent = []Record{ 25 {Hosts: "localhost", IP: "127.0.0.1"}, 26 {Hosts: "localhost ip6-localhost ip6-loopback", IP: "::1"}, 27 {Hosts: "ip6-localnet", IP: "fe00::0"}, 28 {Hosts: "ip6-mcastprefix", IP: "ff00::0"}, 29 {Hosts: "ip6-allnodes", IP: "ff02::1"}, 30 {Hosts: "ip6-allrouters", IP: "ff02::2"}, 31 } 32 33 // Build function 34 // path is path to host file string required 35 // IP, hostname, and domainname set main record leave empty for no master record 36 // extraContent is an array of extra host records. 37 func Build(path, IP, hostname, domainname string, extraContent []Record) error { 38 content := bytes.NewBuffer(nil) 39 if IP != "" { 40 //set main record 41 var mainRec Record 42 mainRec.IP = IP 43 if domainname != "" { 44 mainRec.Hosts = fmt.Sprintf("%s.%s %s", hostname, domainname, hostname) 45 } else { 46 mainRec.Hosts = hostname 47 } 48 if _, err := mainRec.WriteTo(content); err != nil { 49 return err 50 } 51 } 52 // Write defaultContent slice to buffer 53 for _, r := range defaultContent { 54 if _, err := r.WriteTo(content); err != nil { 55 return err 56 } 57 } 58 // Write extra content from function arguments 59 for _, r := range extraContent { 60 if _, err := r.WriteTo(content); err != nil { 61 return err 62 } 63 } 64 65 return ioutil.WriteFile(path, content.Bytes(), 0644) 66 } 67 68 // Update all IP addresses where hostname matches. 69 // path is path to host file 70 // IP is new IP address 71 // hostname is hostname to search for to replace IP 72 func Update(path, IP, hostname string) error { 73 old, err := ioutil.ReadFile(path) 74 if err != nil { 75 return err 76 } 77 var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)", regexp.QuoteMeta(hostname))) 78 return ioutil.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2")), 0644) 79 }