-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponse.go
99 lines (88 loc) · 2.04 KB
/
response.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
package http
import (
"errors"
"fmt"
"github.com/goal-web/contracts"
"github.com/goal-web/supports/logs"
"go/types"
"net/http"
"os"
)
var (
FileTypeError = errors.New("文件参数类型错误")
)
// HandleResponse 处理控制器函数的响应
func HandleResponse(response interface{}, ctx contracts.HttpRequest) {
if response == nil {
return
}
switch res := response.(type) {
case error:
logs.WithError(ctx.String(http.StatusInternalServerError, res.Error())).Debug("response error")
case string:
logs.WithError(ctx.String(http.StatusOK, res)).Debug("response error")
case fmt.Stringer:
logs.WithError(ctx.String(http.StatusOK, res.String())).Debug("response error")
case contracts.Json:
logs.WithError(ctx.String(http.StatusOK, res.ToJson())).Debug("response error")
case contracts.HttpResponse:
logs.WithError(res.Response(ctx)).Debug("response error")
case types.Nil:
return
default:
logs.WithError(ctx.JSON(200, res)).Debug("response json error")
}
}
type Response struct {
status int
Json interface{}
String string
FilePath string
File *os.File
}
func StringResponse(str string, code ...int) contracts.HttpResponse {
status := 200
if len(code) > 0 {
status = code[0]
}
return Response{
status: status,
String: str,
}
}
func JsonResponse(json interface{}, code ...int) contracts.HttpResponse {
status := 200
if len(code) > 0 {
status = code[0]
}
return Response{
status: status,
Json: json,
}
}
// FileResponse 响应文件
func FileResponse(file interface{}) contracts.HttpResponse {
switch f := file.(type) {
case *os.File:
return Response{File: f}
case string:
return Response{FilePath: f}
default:
panic(FileTypeError)
}
}
func (res Response) Status() int {
return res.status
}
func (res Response) Response(ctx contracts.HttpContext) error {
if res.Json != nil {
return ctx.JSON(res.Status(), res.Json)
}
if res.FilePath != "" {
return ctx.File(res.FilePath)
}
if res.File != nil {
return ctx.File(res.File.Name())
}
return ctx.String(res.Status(), res.String)
}