-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample_test.go
55 lines (48 loc) · 1.53 KB
/
example_test.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
// Copyright 2017 Péter Szakszon. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mux_test
import (
"fmt"
"github.com/szxp/mux"
"net/http"
)
func Example() {
muxer := mux.NewMuxer()
muxer.HandleFunc("/", indexHandler, "GET")
muxer.HandleFunc("/#", loginHandler, "POST")
muxer.HandleFunc("/users/:username", userHandler)
muxer.NotFound(notFoundHandler)
http.ListenAndServe(":8080", muxer)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
body := []byte(`
<h1>Home</h1>
<p>
<a href="/users/admin">Admin profile page</a> <br/>
<a href="/#">Login page</a>
</p>
<form action="/" method="POST">
<button type="submit">Post to Home URL</button>
</form>
<form action="/nonexisting" method="POST">
<button type="submit">Post to non existing URL</button>
</form>
`)
w.Header().Add("Content-Type", "text/html; charset=utf-8")
w.Header().Add("Content-Length", fmt.Sprintf("%d", len(body)))
w.Write(body)
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Login")
}
func userHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, r.Context().Value(mux.CtxKey("username")))
}
func notFoundHandler(w http.ResponseWriter, r *http.Request, methodMismatch bool) {
if methodMismatch {
http.Error(w, r.Method+" not allowed", http.StatusMethodNotAllowed)
return
}
http.Error(w, "not found", http.StatusNotFound)
}