-
Notifications
You must be signed in to change notification settings - Fork 7
/
context.go
107 lines (93 loc) · 1.93 KB
/
context.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package banjo
import (
"encoding/json"
"fmt"
)
// Context struct
//
// For easy cooperate with Requests & Response in action flow
//
type Context struct {
Request Request
Response Response
}
// JSON function
//
// This func allows you to easy returning a JSON response
// Example usage:
// app.JSON({"foo" : "bar"})
//
// Params:
// - data {map[string]interface{}}
//
// Response:
// - None
//
func (ctx *Context) JSON(data map[string]interface{}) {
logger := CreateLogger()
body, err := json.Marshal(data)
if err != nil {
str := fmt.Sprintf("Error while parsing JSON object:\nError: %v\nData: %s", err, data)
logger.Error(str)
ctx.InternalServerError()
return
}
if ctx.Response.Headers == nil {
ctx.Response.Headers = make(map[string]string)
}
ctx.Response.Headers["Content-Type"] = "application/json; charset=utf-8"
ctx.Response.Body = string(body)
if ctx.Response.Status == 0 {
ctx.Response.Status = 200
}
}
// HTML function
//
// Prepared Headers to return HTML page
//
// Params:
// - data {string} HTML content
//
// Response:
// - None
//
func (ctx *Context) HTML(data string) {
if ctx.Response.Headers == nil {
ctx.Response.Headers = make(map[string]string)
}
ctx.Response.Headers["Content-Type"] = "text/html"
ctx.Response.Body = data
if ctx.Response.Status == 0 {
ctx.Response.Status = 200
}
}
// RedirectTo function
//
// Allows you to redirect to another page
//
// Params:
// - url {string} path to redirect
//
// Response:
// - None
//
func (ctx *Context) RedirectTo(url string) {
if ctx.Response.Headers == nil {
ctx.Response.Headers = make(map[string]string)
}
ctx.Response.Headers["Location"] = url
ctx.Response.Status = 301
}
// InternalServerError function
//
// Modify Context struct with 500 Status error & Internal Server Error body
//
// Params:
// - None
//
// Response:
// - None
func (ctx *Context) InternalServerError() {
ctx.Response.Status = 500
ctx.Response.Body = "Internal Server Error"
}