forked from globusdigital/soap
/
server.go
296 lines (257 loc) · 8.84 KB
/
server.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package soap
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"net/http"
"reflect"
)
// OperationHandlerFunc runs the actual business logic - request is whatever you constructed in RequestFactoryFunc
type OperationHandlerFunc func(request interface{}, w http.ResponseWriter, httpRequest *http.Request) (response interface{}, err error)
// OperationHandlerFuncWithInfo A modified operational handler function that also passes in an optional information field that can be used to pass in extra information about the request.
// Its type is upto the handler to define.
type OperationHandlerFuncWithInfo func(request interface{}, w http.ResponseWriter, httpRequest *http.Request, handlerInfo interface{}) (response interface{}, err error)
// RequestFactoryFunc constructs a request object for OperationHandlerFunc
type RequestFactoryFunc func() interface{}
type dummyContent struct{}
type operationHandler struct {
requestFactory RequestFactoryFunc
handler OperationHandlerFunc
handlerWithInfo OperationHandlerFuncWithInfo
requestStruct interface{}
handlerInfo interface{}
}
type responseWriter struct {
logFunc func(msg string, keyString_ValueInterface ...interface{})
logLevel int
w http.ResponseWriter
outputStarted bool
}
func (w *responseWriter) log(level int, msg string, args ...interface{}) {
if w.logFunc != nil && level <= w.logLevel {
w.logFunc(msg, args...)
}
}
func (w *responseWriter) Header() http.Header {
return w.w.Header()
}
func (w *responseWriter) Write(b []byte) (int, error) {
w.outputStarted = true
w.log(2, "Response writter", "writing response: ", string(b))
return w.w.Write(b)
}
func (w *responseWriter) WriteHeader(code int) {
w.w.WriteHeader(code)
}
// Server a SOAP server, which can be run standalone or used as a http.HandlerFunc
type Server struct {
//Log func(...interface{}) // do nothing on nil or add your fmt.Print* or log.*
Log func(msg string, keyString_ValueInterface ...interface{})
handlers map[string]map[string]map[string]*operationHandler
Marshaller XMLMarshaller
ContentType string
SoapVersion string
LogLevel int
}
// NewServer construct a new SOAP server
func NewServer() *Server {
return &Server{
handlers: make(map[string]map[string]map[string]*operationHandler),
Marshaller: defaultMarshaller{},
ContentType: SoapContentType11,
SoapVersion: SoapVersion11,
LogLevel: 0,
}
}
func (s *Server) log(level int, msg string, args ...interface{}) {
if s.Log != nil && level <= s.LogLevel {
s.Log(msg, args...)
}
}
func (s *Server) UseSoap11() {
s.SoapVersion = SoapVersion11
s.ContentType = SoapContentType11
}
func (s *Server) UseSoap12() {
s.SoapVersion = SoapVersion12
s.ContentType = SoapContentType12
}
// RegisterHandler register to handle an operation. This function must not be
// called after the server has been started.
func (s *Server) RegisterHandler(path string, action string, messageType string, requestFactory RequestFactoryFunc, operationHandlerFunc OperationHandlerFunc) {
if _, ok := s.handlers[path]; !ok {
s.handlers[path] = make(map[string]map[string]*operationHandler)
}
if _, ok := s.handlers[path][action]; !ok {
s.handlers[path][action] = make(map[string]*operationHandler)
}
s.handlers[path][action][messageType] = &operationHandler{
handler: operationHandlerFunc,
requestFactory: requestFactory,
}
}
// RegisterHandlerWithInfo Register a slightly differenct handler function, to enable auto generation of the Reqest struct from the type.
// also the modiled
// This function must not be called after the server has been started.
func (s *Server) RegisterHandlerWithInfo(path string, action string, messageType string, requestFactory RequestFactoryFunc, operationHandlerFunc OperationHandlerFuncWithInfo, reqStruct interface{}, handlerInfo interface{}) {
if _, ok := s.handlers[path]; !ok {
s.handlers[path] = make(map[string]map[string]*operationHandler)
}
if _, ok := s.handlers[path][action]; !ok {
s.handlers[path][action] = make(map[string]*operationHandler)
}
s.handlers[path][action][messageType] = &operationHandler{
handlerWithInfo: operationHandlerFunc,
requestFactory: requestFactory,
requestStruct: reqStruct,
handlerInfo: handlerInfo,
}
}
func (s *Server) handleError(err error, w http.ResponseWriter) {
// has to write a soap fault
s.log(1, "error", "handling error:", err)
responseEnvelope := &Envelope{
Body: Body{
Content: &Fault{
String: err.Error(),
},
},
}
xmlBytes, xmlErr := s.Marshaller.Marshal(responseEnvelope)
if xmlErr != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "could not marshal soap fault for: %s xmlError: %s\n", err, xmlErr)
return
}
addSOAPHeader(w, len(xmlBytes), s.ContentType)
w.Write(xmlBytes)
}
// WriteHeader first set the content-type header and then writes the header code.
func (s *Server) WriteHeader(w http.ResponseWriter, code int) {
setContentType(w, s.ContentType)
w.WriteHeader(code)
}
func setContentType(w http.ResponseWriter, contentType string) {
w.Header().Set("Content-Type", contentType)
}
func addSOAPHeader(w http.ResponseWriter, contentLength int, contentType string) {
setContentType(w, contentType)
w.Header().Set("Content-Length", fmt.Sprint(contentLength))
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
soapAction := r.Header.Get("SOAPAction")
s.log(1, "Request", "ServeHTTP method:", r.Method, ", path:", r.URL.Path, ", SOAPAction", "\""+soapAction+"\"")
// we have a valid request time to call the handler
w = &responseWriter{
logFunc: s.Log,
logLevel: s.LogLevel,
w: w,
outputStarted: false,
}
switch r.Method {
case "POST":
soapRequestBytes, err := ioutil.ReadAll(r.Body)
// Our structs for Envelope, Header, Body and Fault are tagged with namespace for SOAP 1.1
// Therefore we must adjust namespaces for incoming SOAP 1.2 messages
if s.SoapVersion == SoapVersion12 {
soapRequestBytes = replaceSoap12to11(soapRequestBytes)
}
if err != nil {
s.handleError(fmt.Errorf("could not read POST:: %s", err), w)
return
}
s.log(3, "Request", "request body:", string(soapRequestBytes))
pathHandlers, ok := s.handlers[r.URL.Path]
if !ok {
s.log(1, "Request", "unknown path:", r.URL.Path)
s.handleError(fmt.Errorf("unknown path %q", r.URL.Path), w)
return
}
actionHandlers, ok := pathHandlers[soapAction]
if !ok {
s.log(1, "Request", "unknown action:", soapAction)
s.handleError(fmt.Errorf("unknown action %q", soapAction), w)
return
}
// we need to find out, what is in the body
probeEnvelope := &Envelope{
Body: Body{
Content: &dummyContent{},
},
}
if err := s.Marshaller.Unmarshal(soapRequestBytes, probeEnvelope); err != nil {
s.handleError(fmt.Errorf("could not probe soap body content:: %s", err), w)
return
}
t := probeEnvelope.Body.SOAPBodyContentType
s.log(1, "Request", "found content type", t)
actionHandler, ok := actionHandlers[t]
if !ok {
s.handleError(fmt.Errorf("no action handler for content type: %q", t), w)
return
}
var request interface{}
if actionHandler.requestFactory != nil {
request = actionHandler.requestFactory()
} else {
request = reflect.New(reflect.TypeOf(actionHandler.requestStruct)).Interface()
}
envelope := &Envelope{
Header: Header{},
Body: Body{
Content: request,
},
}
if err := xml.Unmarshal(soapRequestBytes, &envelope); err != nil {
s.handleError(fmt.Errorf("could not unmarshal request:: %s", err), w)
return
}
s.log(2, "Request", "envelope:", s.jsonDump(envelope))
var response interface{}
if actionHandler.handlerWithInfo != nil {
response, err = actionHandler.handlerWithInfo(request, w, r, actionHandler.handlerInfo)
} else {
response, err = actionHandler.handler(request, w, r)
}
if err != nil {
s.log(1, "Request", "action handler threw up", err.Error())
s.handleError(err, w)
return
}
s.log(2, "Response", "msg", s.jsonDump(response))
if !w.(*responseWriter).outputStarted {
responseEnvelope := &Envelope{
Body: Body{
Content: response,
},
}
xmlBytes, err := s.Marshaller.Marshal(responseEnvelope)
// Adjust namespaces for SOAP 1.2
if s.SoapVersion == SoapVersion12 {
xmlBytes = replaceSoap11to12(xmlBytes)
}
if err != nil {
s.handleError(fmt.Errorf("could not marshal response:: %s", err), w)
}
addSOAPHeader(w, len(xmlBytes), s.ContentType)
w.Write(xmlBytes)
} else {
s.log(1, "Respose action handler sent its own output")
}
default:
// this will be a soap fault !?
s.handleError(errors.New("this is a soap service - you have to POST soap requests"), w)
}
}
func (s *Server) jsonDump(v interface{}) string {
if s.Log == nil {
return "not dumping"
}
jsonBytes, err := json.MarshalIndent(v, "", " ")
if err != nil {
return "error in json dump :: " + err.Error()
}
return string(jsonBytes)
}