-
Notifications
You must be signed in to change notification settings - Fork 101
/
example.go
68 lines (55 loc) · 1.51 KB
/
example.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/go-zoo/bone"
)
var (
mux = bone.New(Serve, Wrap)
)
func Wrap(mux *bone.Mux) *bone.Mux {
return mux.Prefix("/api")
}
func Serve(mux *bone.Mux) *bone.Mux {
mux.Serve = func(rw http.ResponseWriter, req *http.Request) {
tr := time.Now()
mux.DefaultServe(rw, req)
fmt.Println("Serve request from", req.RemoteAddr, "in", time.Since(tr))
}
return mux
}
func main() {
// Custom 404
mux.NotFoundFunc(Handler404)
// Handle with any http method, Handle takes http.Handler as argument.
mux.Handle("/index", http.HandlerFunc(homeHandler))
mux.Handle("/index/:var/info/:test", http.HandlerFunc(varHandler))
// Get, Post etc... takes http.HandlerFunc as argument.
mux.Post("/home", http.HandlerFunc(homeHandler))
mux.Get("/home/:var", http.HandlerFunc(varHandler))
mux.GetFunc("/test/*", func(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte(req.RequestURI))
})
// Start Listening
log.Fatal(mux.ListenAndServe(":8080"))
}
func homeHandler(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte("WELCOME HOME"))
}
func varHandler(rw http.ResponseWriter, req *http.Request) {
varr := bone.GetValue(req, "var")
test := bone.GetValue(req, "test")
var args = struct {
First string
Second string
}{varr, test}
if err := json.NewEncoder(rw).Encode(&args); err != nil {
panic(err)
}
}
func Handler404(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte("These are not the droids you're looking for ..."))
}