-
Notifications
You must be signed in to change notification settings - Fork 21
/
main.go
151 lines (127 loc) · 3.72 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
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
139
140
141
142
143
144
145
146
147
148
149
150
151
package main
import (
"flag"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"log"
"github.com/ChimeraCoder/gojson"
)
var (
Listen string
Port int
Template string
Tmpl *template.Template
defaultJson = `{ "example": { "from": { "json": true } } }`
mutty = sync.Mutex{}
)
type Result struct {
Json, Struct string
}
type Handler struct{}
func init() {
log.SetFlags(0)
log.SetPrefix("app=gojson-http")
}
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
begin := time.Now()
defer r.Body.Close()
Tmpl, err := template.ParseFiles(Template)
if err != nil {
log.Fatalf("at=ServeHTTP error=%v", err)
}
log.Printf("at=ServeHTTP method=%s path=%s user-agent=%s took=%v",
r.Method, r.URL.Path, r.Header["User-Agent"], time.Since(begin))
res := Result{
Json: defaultJson,
}
if strings.HasSuffix(r.URL.Path, "json") {
fmt.Fprintln(w, fmt.Sprintf(`{ "example": { "from": { "path": "%s" } } }`, r.URL.String()))
return
}
var src string
if r.Method == "POST" {
val := r.PostFormValue("json")
res.Json = val
} else {
src = r.URL.Query().Get("src")
if src != "" {
res.Json = src
}
}
if strings.HasPrefix(res.Json, "http") {
// redirect wth to src param, if res.Json is path, but src path doesn't exist
if src == "" {
http.Redirect(w, r, r.URL.Path+"?src="+strings.TrimSpace(res.Json), 301)
return
}
// fetch res.Json
resp, err := http.DefaultClient.Get(strings.TrimSpace(res.Json))
if err != nil {
log.Printf("at=ServeHTTP method=%s path=%s user-agent=%s took=%v",
r.Method, r.URL.Path, r.Header["User-Agent"], time.Since(begin))
log.Printf("at=ServeHTTP error=%v", err)
res.Struct = fmt.Sprintf("JSON Parse Error: %v\n", err)
Tmpl.Execute(w, nil)
return
}
read, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Printf("at=ServeHTTP method=%s path=%s user-agent=%s took=%v",
r.Method, r.URL.Path, r.Header["User-Agent"], time.Since(begin))
log.Printf("at=ServeHTTP error=%v", err)
res.Struct = fmt.Sprintf("JSON Fetch Error: %v\n", err)
}
res.Json = string(read)
}
if out, e := gojson.Generate(strings.NewReader(res.Json), gojson.ParseJson, "MyJsonName", "main", []string{"json"}, false, true); e == nil {
res.Struct = string(out)
} else {
log.Printf("at=ServeHTTP method=%s path=%s user-agent=%s took=%v",
r.Method, r.URL.Path, r.Header["User-Agent"], time.Since(begin))
log.Printf("at=ServeHTTP error=%v", e)
res.Struct = fmt.Sprintf("JSON Parse Error: %v\n", e)
}
Tmpl.Execute(w, res)
}
func main() {
// reload tempalate on SIGHUP
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGHUP)
go reloadTemplate(sigc)
flag.IntVar(&Port, "port", 8080, "startup port")
flag.StringVar(&Listen, "listen", "localhost", "listen address")
flag.StringVar(&Template, "template", "index.html", "display template")
flag.Parse()
handler := Handler{}
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", Listen, Port),
Handler: handler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Printf("at=main address=%s", server.Addr)
log.Fatalf("at=main error=%s", server.ListenAndServe())
}
func reloadTemplate(sigc chan os.Signal) {
for _ = range sigc {
log.Print("at=reloadTemplate message=\"reloading template\"")
t, e := template.ParseFiles(Template)
if e != nil {
log.Printf("at=reloadTemplate error=%v", e)
}
mutty.Lock()
Tmpl = t
mutty.Unlock()
log.Println("at=reloadTemplate message=\"reloading template\"")
}
}