-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
88 lines (75 loc) · 1.98 KB
/
main.go
File metadata and controls
88 lines (75 loc) · 1.98 KB
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
package main
import (
"fmt"
"github.com/markusdosch/gopherlol/commands"
"log"
"net/http"
"net/url"
"reflect"
"strings"
)
var commandsObject = new(commands.Commands)
func handler(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query().Get("q")
arr := strings.SplitN(q, " ", 2)
cmdName := strings.Title(arr[0])
cmdArg := ""
if len(arr) > 1 {
cmdArg = arr[1]
}
if cmdName == "List" || cmdName == "Help" {
commandsType := reflect.TypeOf(&commands.Commands{})
var html strings.Builder
html.WriteString("<h1>gopherlol command list</h1>")
html.WriteString("<ul>")
for i := 0; i < commandsType.NumMethod(); i++ {
method := commandsType.Method(i)
takesArgs := ""
if method.Type.NumIn() == 2 {
takesArgs = ", takes args"
}
html.WriteString(fmt.Sprintf(
"<li><strong>%s</strong>%s</li>",
strings.ToLower(method.Name),
takesArgs,
))
}
html.WriteString("</ul>")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprint(w, html.String())
return
}
cmdMethod := reflect.ValueOf(commandsObject).MethodByName(cmdName)
if cmdMethod == reflect.ValueOf(nil) {
// cmdMethod not found => fall back to google
url := fmt.Sprintf("https://www.google.com/#q=%s", url.QueryEscape(q))
http.Redirect(w, r, url, http.StatusSeeOther)
return
}
url := ""
cmdMethodNumIn := cmdMethod.Type().NumIn()
if cmdMethodNumIn == 0 {
res := cmdMethod.Call([]reflect.Value{})
url = res[0].String()
} else if cmdMethodNumIn == 1 {
in := []reflect.Value{reflect.ValueOf(cmdArg)}
res := cmdMethod.Call(in)
url = res[0].String()
} else {
// cmdMethod was wrongly defined.
// We currently only support cmdMethods with 0 or 1 parameters
http.Error(
w,
http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError,
)
return
}
http.Redirect(w, r, url, http.StatusSeeOther)
return
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}