-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource.go
73 lines (58 loc) · 1.36 KB
/
resource.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
package jeen
import (
"context"
"errors"
"net/http"
)
// All resource needed for development
type Resource struct {
// private for internal use
writer http.ResponseWriter
request *http.Request
// request
Request *Request
// writer
Writer *Writer
// cookie
Cookie *Cookie
// request context
Context context.Context
// database sql.DB
Database *Database
// session SCS
Session *Session
// html response with goview
Html *Html
// json response
Json *Json
}
// create new resource
func createResource(rw http.ResponseWriter, r *http.Request, h *HtmlEngine) *Resource {
return &Resource{
// private
request: r,
writer: rw,
Context: r.Context(),
Request: newRequest(r),
Writer: newWriter(rw),
Cookie: newCookie(rw, r),
Html: newHtml(rw, h),
Json: newJson(rw),
}
}
// Set set value to request context, see Get to get it
func (r *Resource) Set(key, val interface{}) {
r.request = r.request.WithContext(context.WithValue(r.Context, key, val))
}
// Get get value from context
func (r *Resource) Get(key interface{}) interface{} {
return r.Context.Value(key)
}
// Redirect redirects the request to a provided URL with status code.
func (r *Resource) Redirect(code int, url string) error {
if code < 300 || code > 308 {
return errors.New("invalid redirect status code")
}
http.Redirect(r.writer, r.request, url, code)
return nil
}