-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
69 lines (59 loc) · 1.6 KB
/
connection.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
package rapid
import (
"encoding/json"
"fmt"
"html/template"
"net/http"
"github.com/Kiricon/Rapid/templating"
)
// Connection - struct for handling http request and write
type Connection struct {
R *http.Request
W http.ResponseWriter
Params map[string]string
JSON interface{}
server *Server
}
// Send - Return plain text string back to http request
func (c *Connection) Send(message string) {
fmt.Fprintf(c.W, message)
}
// View - Render HTML view without templating
func (c *Connection) View(path string) {
c.Render(path, nil)
}
// Render - Render HTML view with templating
// Templating uses standard library templating
func (c *Connection) Render(path string, object interface{}) {
if c.server.viewPrefix != "" {
path = c.server.viewPrefix + "/" + path
}
fileString := templating.AddPartial(path)
t, _ := template.New("blah").Parse(fileString)
c.W.Header().Set("Content-Type", "text/html; charset=utf-8")
t.Execute(c.W, object)
}
// Redirect - Redirect a request to another rest end point
func (c *Connection) Redirect(path string) {
http.Redirect(c.W, c.R, path, 301)
}
// NotFound - Return 404 message to user
func (c *Connection) NotFound() {
if c.server.notFoundPage != "" {
http.ServeFile(c.W, c.R, c.server.notFoundPage)
} else {
c.W.WriteHeader(http.StatusNotFound)
fmt.Fprintf(c.W, c.server.notFoundMessage)
}
}
// SendJSON - Send json string back to client
func (c *Connection) SendJSON(object interface{}) {
obj := &object
j, err := json.Marshal(obj)
if err != nil {
fmt.Println(err)
return
}
c.W.Header().Set("Content-Type", "application/json")
c.Send(string(j))
}