-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathservice.go
107 lines (87 loc) · 2.45 KB
/
service.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 rest
import (
"net/http"
"reflect"
)
/*
Define the service.
Valid tag:
- prefix: The prefix path of http request. All processor's path will prefix with prefix path.
The priority of value is: value in Service, value in tag, default.
To be implement:
- mime: Define the default mime of all processor in this service.
- charset: Define the default charset of all processor in this service.
*/
type Service struct {
*innerService
// Set the service prefix path, it will over right prefix in tag.
Prefix string
// Set the service default mime, it will over right mime in tag.
DefaultMime string
// Set the service default charset, it will over right charset in tag.
DefaultCharset string
// Plugin can access service.Tag to get the tag informations.
Tag reflect.StructTag
}
// Return the http request instance.
func (s Service) Request() *http.Request {
return s.ctx.request
}
// Write response code and header. Same as http.ResponseWriter.WriteHeader(int)
func (s Service) WriteHeader(code int) {
s.ctx.responseWriter.WriteHeader(code)
}
// Get the response header.
func (s Service) Header() http.Header {
return s.ctx.responseWriter.Header()
}
// Error replies to the request with the specified error message and HTTP code.
func (s Service) Error(code int, err error) {
http.Error(s.ctx.responseWriter, err.Error(), code)
s.ctx.isError = true
}
// Redirect to the specified path.
func (s Service) RedirectTo(path string) {
s.Header().Set("Location", path)
s.WriteHeader(http.StatusTemporaryRedirect)
}
func initService(service reflect.Value, tag reflect.StructTag) (string, string, string, error) {
mime := service.FieldByName("DefaultMime").Interface().(string)
if mime == "" {
mime = tag.Get("mime")
}
if mime == "" {
mime = "application/json"
}
charset := service.FieldByName("DefaultCharset").Interface().(string)
if charset == "" {
charset = tag.Get("charset")
}
if charset == "" {
charset = "utf-8"
}
prefix := service.FieldByName("Prefix").Interface().(string)
if prefix == "" {
prefix = tag.Get("prefix")
}
if prefix == "" {
prefix = "/"
}
if prefix[0] != '/' {
prefix = "/" + prefix
}
if l := len(prefix); l > 2 && prefix[l-1] == '/' {
prefix = prefix[:l-1]
}
service.Set(reflect.ValueOf(Service{
innerService: new(innerService),
Prefix: prefix,
DefaultMime: mime,
DefaultCharset: charset,
Tag: tag,
}))
return prefix, mime, charset, nil
}
type innerService struct {
ctx *context
}