/
http_custom.go
53 lines (44 loc) · 1.22 KB
/
http_custom.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
package svc
// This file provides server-side bindings for the HTTP transport.
// It utilizes the transport/http.Server.
import (
"bytes"
"context"
"io"
"io/ioutil"
"net/http"
)
/*
var customHTTPBefore httptransport.RequestFunc
// MakeHTTPHandler returns a handler that makes a set of endpoints available
// on predefined paths.
func MakeHTTPHandler(endpoints Endpoints) http.Handler {
serverOptions := []httptransport.ServerOption{
httptransport.ServerBefore(headersToContext, customHTTPBefore),
httptransport.ServerErrorEncoder(errorEncoder),
httptransport.ServerAfter(httptransport.SetContentType(contentType)),
*/
func init() {
customHTTPBefore = dumpBodyToContext
}
type HTTPBody struct{}
func dumpBodyToContext(ctx context.Context, r *http.Request) context.Context {
var save []byte
var err error
save, r.Body, err = drainBody(r.Body)
if err != nil {
return ctx
}
ctx = context.WithValue(ctx, HTTPBody{}, save)
return ctx
}
func drainBody(b io.ReadCloser) ([]byte, io.ReadCloser, error) {
var buf bytes.Buffer
if _, err := buf.ReadFrom(b); err != nil {
return nil, b, err
}
if err := b.Close(); err != nil {
return nil, b, err
}
return buf.Bytes(), ioutil.NopCloser(bytes.NewReader(buf.Bytes())), nil
}