-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
51 lines (41 loc) · 1.16 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
package main
import (
"bytes"
"fmt"
"net/http"
"time"
"github.com/MadAppGang/httplog"
"github.com/justinas/alice"
"github.com/justinas/nosurf"
)
func happyHandler() http.Handler {
h := func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("I am happy!"))
}
return http.HandlerFunc(h)
}
func main() {
// setup routes
mux := http.NewServeMux()
// create reusable middleware chain
chain := alice.New(httplog.LoggerWithName("ALICE"), nosurf.NewPure)
mux.Handle("/happy", chain.Then(happyHandler()))
mux.Handle("/not_found", chain.Then(http.NotFoundHandler()))
go func() {
fmt.Println("Server started at port 3333")
err := http.ListenAndServe(":3333", mux)
if err != nil {
fmt.Printf("Server stopped because of error %s\n", err.Error())
}
}()
// let server to start
time.Sleep(time.Second * 2)
// let's make couple of request
_, err := http.Get("http:https://localhost:3333/happy")
if err != nil {
fmt.Printf("Error: %+v", err)
}
_, _ = http.Post("http:https://localhost:3333/happy", "text/plain", bytes.NewBuffer([]byte("I am not ")))
_, _ = http.Get("http:https://localhost:3333/not_found")
fmt.Println("All done, thank you and see you soon 👋")
}