-
Notifications
You must be signed in to change notification settings - Fork 1
/
console.go
138 lines (114 loc) · 2.5 KB
/
console.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// Copyright Piero de Salvia.
// All Rights Reserved
package dynaroutes
//go:generate embed -package dynaroutes -var indexHtml -asset assets/index.html -o Assets.go
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
)
func (r *Router) startConsole(host string, port int) {
portS := strconv.Itoa(port)
server := http.Server{
Addr: host + ":" + portS,
Handler: &consoleHandler{
router: r,
},
}
log.Println("Web console started on ", host, ":", port)
err := server.ListenAndServe()
log.Println(err)
}
func readFile(name string) ([]byte, error) {
goPath := os.Getenv("GOPATH")
filePath := goPath + "/src/github.com/pierods/dynaroutes/assets" + name
f, fErr := os.Open(filePath)
defer f.Close()
if fErr != nil {
return nil, fErr
}
bytes, fErr := ioutil.ReadAll(f)
if fErr != nil {
return nil, fErr
}
return bytes, nil
}
type consoleHandler struct {
router *Router
}
func (ch *consoleHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if strings.HasPrefix(path, "/pre") {
pres := ch.router.preList()
json, err := json.Marshal(pres)
if err != nil {
rw.WriteHeader(500)
fmt.Fprint(rw, err)
return
}
rw.Write(json)
return
}
if strings.HasPrefix(path, "/post") {
posts := ch.router.postList()
json, err := json.Marshal(posts)
if err != nil {
rw.WriteHeader(500)
fmt.Fprint(rw, err)
return
}
rw.Write(json)
return
}
if path == "/" {
path = "/index.html"
}
rw.Header().Set("Content/Type", "text/html")
/*
page, err := readFile(path)
if err != nil {
rw.WriteHeader(404)
fmt.Fprint(rw, err)
}
rw.Write(page)
*/
rw.Write(indexHtml)
}
// FilterItem is exported for JSON
type FilterItem struct {
Name string `json:"name"`
Order int `json:"order"`
Description string `json:"description"`
Code string `json:"code"`
}
func (r *Router) preList() []FilterItem {
var items []FilterItem
for _, pre := range r.preFilters {
item := FilterItem{
Name: pre.Name(),
Order: pre.Order(),
Description: pre.Description(),
Code: r.prefilterCode[pre.Name()],
}
items = append(items, item)
}
return items
}
func (r *Router) postList() []FilterItem {
var items []FilterItem
for _, post := range r.postFilters {
item := FilterItem{
Name: post.Name(),
Order: post.Order(),
Description: post.Description(),
Code: r.postFilterCode[post.Name()],
}
items = append(items, item)
}
return items
}