-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput.go
96 lines (88 loc) · 2.21 KB
/
input.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
package main
import (
"bufio"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
/*
readPromptFromKeyboard reads prompt from keyboard (Stdin).
*/
func readPromptFromKeyboard(promptChannel chan string) {
reader := bufio.NewReader(os.Stdin)
for {
promptData, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("error [%v] at reader.ReadString()", err)
return
}
if promptData == "\n" || promptData == "\r\n" {
continue
}
// read prompt from given text file (e.g. "<<<MyQuery.txt" or "<<< MyQuery.txt")
var fileData []byte
if strings.HasPrefix(promptData, "<<<") {
filename := strings.TrimSpace(strings.TrimPrefix(promptData, "<<<"))
fileData, err = os.ReadFile(filename)
if err != nil {
fmt.Printf("error [%v] at os.ReadFile()\n", err)
continue
}
if len(fileData) > 0 {
promptChannel <- string(fileData)
}
} else {
promptChannel <- promptData
}
}
}
/*
readPromptFromFile reads prompt (user input) from named file.
*/
func readPromptFromFile(filePath string, promptChannel chan string) {
currentStat, err := os.Stat(filePath)
if err != nil {
fmt.Printf("error [%v] at os.Stat()", err)
}
for {
stat, err := os.Stat(filePath)
if err != nil {
fmt.Printf("error [%v] at os.Stat()", err)
}
if stat.Size() != currentStat.Size() || stat.ModTime() != currentStat.ModTime() {
promptData, err := os.ReadFile(filePath)
if err != nil {
fmt.Printf("error [%v] at os.ReadFile()", err)
}
if len(promptData) > 0 {
promptChannel <- string(promptData)
}
currentStat = stat
}
time.Sleep(500 * time.Millisecond)
}
}
/*
readPromptFromLocalhost reads prompt (user input) from localhost.
*/
func readPromptFromLocalhost(promptChannel chan string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "error reading request body", http.StatusBadRequest)
fmt.Printf("error [%v] reading request body\n", err)
return
}
if len(body) == 0 {
http.Error(w, "prompt empty", http.StatusBadRequest)
return
}
promptChannel <- string(body)
defer r.Body.Close()
fmt.Fprintln(w, "prompt received")
}
}