-
Notifications
You must be signed in to change notification settings - Fork 0
/
transformer.go
67 lines (54 loc) · 1.5 KB
/
transformer.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
package middleware
import (
"bytes"
"encoding/json"
"io"
"mime"
"net/http"
"strconv"
)
// WithTransformer transforms the input.
func WithTransformer() func(http.Handler) http.Handler {
decoder := NewFormDecoder()
innerFn := func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
mime, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
if mime == "application/x-www-form-urlencoded" {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// find the message by name
factory, err := URLMessageType(r.URL)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
message := factory.New().Interface()
// decode the message
if err = decoder.Decode(message, r.Form); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
body := &bytes.Buffer{}
// encode the boyd
if err := json.NewEncoder(body).Encode(message); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
r.Body = io.NopCloser(body)
r.ContentLength = int64(body.Len())
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Content-Length", strconv.Itoa(body.Len()))
}
// execute the handler
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
return innerFn
}