-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
99 lines (83 loc) · 2.27 KB
/
main.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
)
// Timer structure
type Timer struct {
isFinished bool
}
func main() {
myTimer := &Timer{isFinished: false}
go myTimer.timer()
// for !myTimer.isFinished {
// time.Sleep(1 * time.Second)
// fmt.Println(myTimer.isFinished)
// }
http.HandleFunc("/", helloWorld)
http.HandleFunc("/envs", environmentVariables)
http.HandleFunc("/readdir", readDir)
http.HandleFunc("/readfile", readFile)
http.HandleFunc("/healthcheckok", healthcheckok)
http.HandleFunc("/healthcheckfail", myTimer.healthcheckfail)
http.ListenAndServe(":8000", nil)
}
// just check if it works
// localhost/
func helloWorld(writer http.ResponseWriter, request *http.Request) {
io.WriteString(writer, "Hello world!\n")
}
// readDir lists all items in a dir from get request
// localhost/readdir?directory=dirname
func readDir(writer http.ResponseWriter, request *http.Request) {
directory := request.FormValue("q")
files, err := ioutil.ReadDir(directory)
if err != nil {
fmt.Println(err)
io.WriteString(writer, err.Error())
} else {
filenames := make([]string, len(files))
for i, f := range files {
filenames[i] = f.Name()
}
io.WriteString(writer, "content of "+directory+":\n"+strings.Join(filenames, "\n"))
}
}
func readFile(writer http.ResponseWriter, request *http.Request) {
file := request.FormValue("q")
fileContent, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
io.WriteString(writer, err.Error())
} else {
io.WriteString(writer, "content of "+file+":\n"+string(fileContent))
}
}
// environmentVariables lists all environmental variables in system
// localhost/envs
func environmentVariables(writer http.ResponseWriter, request *http.Request) {
io.WriteString(writer, strings.Join(os.Environ(), "\n"))
}
// healthcheckok returns 200
// localhost/envs
func healthcheckok(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(200)
}
// healthcheckfail returns 200 and after 3 minutes switch to returning 400
// localhost/envs
func (t *Timer) healthcheckfail(writer http.ResponseWriter, request *http.Request) {
if t.isFinished {
writer.WriteHeader(400)
} else {
writer.WriteHeader(200)
}
}
func (t *Timer) timer() {
time.Sleep(3 * time.Minute)
t.isFinished = true
}