-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcontent.go
More file actions
97 lines (78 loc) · 1.79 KB
/
content.go
File metadata and controls
97 lines (78 loc) · 1.79 KB
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
// Copyright 2012 by sdm. All rights reserved.
// license that can be found in the LICENSE file.
package wk
import (
"fmt"
"io"
)
// ContentResult is raw content
type ContentResult struct {
// ContentType
ContentType string
// Data
Data interface{}
}
// Content return *ContentResult
func Content(data interface{}, contentType string) *ContentResult {
return &ContentResult{
Data: data,
ContentType: contentType,
}
}
// Execute write Data to response
func (c *ContentResult) Execute(ctx *HttpContext) error {
if c.ContentType != "" {
if ctype := ctx.ReqHeader("Content-Type"); ctype != "" {
ctx.SetHeader("Content-Type", c.ContentType)
}
}
if w, ok := c.Data.(io.WriterTo); ok {
w.WriteTo(ctx.Resonse)
return nil
}
if r, ok := c.Data.(io.Reader); ok {
io.Copy(ctx.Resonse, r)
return nil
}
if b, ok := c.Data.([]byte); ok {
// Write([]byte) (int, error)
ctx.Resonse.Write(b)
return nil
}
if s, ok := c.Data.(string); ok {
io.WriteString(ctx.Resonse, s)
return nil
}
fmt.Fprintln(ctx.Resonse, c.Data)
return nil
}
// DataResult is wrap of simple type
type DataResult struct {
// Data
Data interface{}
}
// Data return *DataResult
func Data(data interface{}) *DataResult {
return &DataResult{
Data: data,
}
}
// Execute write Data to response
func (c *DataResult) Execute(ctx *HttpContext) error {
_, err := fmt.Fprintln(ctx.Resonse, c.Data)
return err
}
// TextResult is plaintext
type TextResult string
// Text return a *TextResult
func Text(data string) TextResult {
return TextResult(data)
}
// Execute write Data to response
func (t TextResult) Execute(ctx *HttpContext) error {
if ctype := ctx.ReqHeader("Content-Type"); ctype != "" {
ctx.SetHeader("Content-Type", ContentTypeText)
}
_, err := ctx.Resonse.Write([]byte(t))
return err
}