/
handlers.go
41 lines (34 loc) · 1 KB
/
handlers.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
package main
import (
"fmt"
"net/http"
"time"
"github.com/unrolled/render"
)
type sampleContent struct {
ID string `json:"id"`
Content string `json:"content"`
}
func testHandler(formatter *render.Render) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
formatter.JSON(w, http.StatusOK, sampleContent{ID: "8675309", Content: "Hello from Go!"})
}
}
func cookieWriteHandler(formatter *render.Render) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{Name: "sample", Value: "this is a cookie", Expires: expiration}
http.SetCookie(w, &cookie)
formatter.JSON(w, http.StatusOK, "cookie set")
}
}
func cookieReadHandler(formatter *render.Render) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
cookie, err := req.Cookie("sample")
if err == nil {
fmt.Fprint(w, cookie.Value)
} else {
fmt.Fprintf(w, "failed to read cookie, %v", err)
}
}
}