/
hostname.go
65 lines (58 loc) · 1.37 KB
/
hostname.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/spf13/cobra"
)
func init() {
http.HandleFunc("/"+API_VERSION+"/hostname", handleHostname)
cmds = append(cmds, &cobra.Command{
Use: "hostname [hostname]",
Short: "Get or Set Hostname",
Long: "This gets or sets the hostname for the system.",
Run: cmdHostname,
})
inits["hostname"] = &initFunc{
Func: initHostname,
Status: false,
}
}
func cmdHostname(cmd *cobra.Command, args []string) {
if len(args) == 0 {
fmt.Printf("%s", MyAPIGet("hostname"))
} else if len(args) == 1 {
MyAPIPost("hostname", args[0])
} else {
cmd.HelpFunc()
}
}
func initHostname() bool {
SetHostname([]byte(config.Hostname))
return true
}
func SetHostname(hostname []byte) error {
fmt.Println("Setting hostname")
err := MyWriteFile("/proc/sys/kernel/hostname", hostname, 0644)
return err
}
func handleHostname(w http.ResponseWriter, r *http.Request) {
//w.Header().Add("Content-Type", "application/json")
if r.Method == "POST" {
body, _ := ioutil.ReadAll(r.Body)
err := SetHostname(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
config.Hostname = string(body)
saveConfig()
} else {
hostnameBytes, err := MyReadFile("/proc/sys/kernel/hostname")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(hostnameBytes)
}
}