-
Notifications
You must be signed in to change notification settings - Fork 89
/
hosts.go
85 lines (67 loc) · 1.97 KB
/
hosts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package hosts
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/nanobox-io/nanobox/config"
)
// HasDomain
func HasDomain() (has bool) {
// open the /etc/hosts file for scanning...
f, err := os.Open(hostsPath)
if err != nil {
config.Fatal("[util/file/hosts] os.Open() failed", err.Error())
}
defer f.Close()
// scan hosts file looking for an entry corresponding to this app...
scanner := bufio.NewScanner(f)
for scanner.Scan() {
// if an entry with the IP is detected, indicate that it's not needed
if strings.HasPrefix(scanner.Text(), config.Nanofile.IP) {
has = true
}
}
return
}
// AddDomain
func AddDomain() {
// open hosts file
f, err := os.OpenFile(hostsPath, os.O_RDWR|os.O_APPEND, 0644)
if err != nil {
config.Fatal("[util/file/hosts] os.OpenFile() failed", err.Error())
}
defer f.Close()
// write the entry to the file
entry := fmt.Sprintf("\n%-15v %s # '%v' private network (added by nanobox)", config.Nanofile.IP, config.Nanofile.Domain, config.Nanofile.Name)
if _, err := f.WriteString(entry); err != nil {
config.Fatal("[util/file/hosts] file.WriteString() failed", err.Error())
}
}
// RemoveDomain
func RemoveDomain() {
var contents string
// open hosts file
f, err := os.OpenFile(hostsPath, os.O_RDWR, 0644)
if err != nil {
config.Fatal("[util/file/hosts] os.OpenFile() failed", err.Error())
}
defer f.Close()
// remove entry from /etc/hosts
scanner := bufio.NewScanner(f)
for scanner.Scan() {
// if the line contain the entry skip it
if strings.HasPrefix(scanner.Text(), config.Nanofile.IP) {
continue
}
// add each line back into the file
contents += fmt.Sprintf("%s\n", scanner.Text())
}
// trim the contents to avoid any extra newlines
contents = strings.TrimSpace(contents)
// write back the contents of the hosts file minus the removed entry
if err := ioutil.WriteFile(hostsPath, []byte(contents), 0644); err != nil {
config.Fatal("[util/file/hosts] ioutil.WriteFile failed", err.Error())
}
}