-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
54 lines (41 loc) · 1.1 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
// Copyright (c) 2020 by meng. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package proxy
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strconv"
)
type Context struct {
Request *http.Request
ResponseWriter http.ResponseWriter
}
// 重置
func (this *Context) Reset(rw http.ResponseWriter, r *http.Request) {
this.ResponseWriter = rw
this.Request = r
}
// 响应字符串
func (this *Context) WriteString(content string) {
_, _ = this.ResponseWriter.Write([]byte(content))
}
func (this *Context) Header(key, value string) {
this.ResponseWriter.Header().Set(key, value)
}
func (this *Context) ServerJson(data interface{}) {
var content []byte
var err error
content, err = json.Marshal(data)
if err != nil {
http.Error(this.ResponseWriter, err.Error(), http.StatusInternalServerError)
return
}
this.Header("Content-Type", "application/json; charset=utf-8")
this.Header("Content-Length", strconv.Itoa(len(content)))
var buf = &bytes.Buffer{}
buf.Write(content)
_, _ = io.Copy(this.ResponseWriter, buf)
}