| 1 |
package transport |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/base64" |
| 6 |
"io" |
| 7 |
"io/ioutil" |
| 8 |
|
| 9 |
"github.com/mitch000001/go-hbci/transport" |
| 10 |
|
| 11 |
"golang.org/x/text/encoding" |
| 12 |
) |
| 13 |
|
| 14 |
// UTF8Encoding represents a middleware encoding the request passed to it with |
| 15 |
// the provided UTF8 encoding and decoding the response from the wrapped |
| 16 |
// transport from the provided encoding into UTF8. |
| 17 |
// If the wrapped Transport returns an error, the error will be passed as is |
| 18 |
// without any transformation applied. |
| 19 |
func UTF8Encoding(encoding encoding.Encoding) transport.Middleware { |
| 20 |
return func(t transport.Transport) transport.Transport { |
| 21 |
return transport.Func(func(req *transport.Request) (*transport.Response, error) { |
| 22 |
var buf bytes.Buffer |
| 23 |
encodingWriter := encoding.NewEncoder().Writer(&buf) |
| 24 |
_, err := io.Copy(encodingWriter, req.Body) |
| 25 |
if err != nil { |
| 26 |
return nil, err |
| 27 |
} |
| 28 |
encodedRequest := req |
| 29 |
encodedRequest.Body = ioutil.NopCloser(&buf) |
| 30 |
response, err := t.Do(encodedRequest) |
| 31 |
if err != nil { |
| 32 |
return nil, err |
| 33 |
} |
| 34 |
decodingReader := encoding.NewDecoder().Reader(response.Body) |
| 35 |
decodedResponse := response |
| 36 |
decodedResponse.Body = ioutil.NopCloser(decodingReader) |
| 37 |
return decodedResponse, nil |
| 38 |
}) |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
// Base64Encoding represents a middleware encoding the request passed to it with |
| 43 |
// Base64 encoding and decoding the response from the wrapped transport from |
| 44 |
// Base64. |
| 45 |
// If the wrapped Transport returns an error, the error will be passed as is |
| 46 |
// without any transformation applied. |
| 47 |
func Base64Encoding(encoding *base64.Encoding) transport.Middleware { |
| 48 |
return func(t transport.Transport) transport.Transport { |
| 49 |
return transport.Func(func(req *transport.Request) (*transport.Response, error) { |
| 50 |
var buf bytes.Buffer |
| 51 |
encodingWriter := base64.NewEncoder(encoding, &buf) |
| 52 |
_, err := io.Copy(encodingWriter, req.Body) |
| 53 |
if err != nil { |
| 54 |
return nil, err |
| 55 |
} |
| 56 |
err = encodingWriter.Close() |
| 57 |
if err != nil { |
| 58 |
return nil, err |
| 59 |
} |
| 60 |
encodedRequest := req |
| 61 |
encodedRequest.Body = ioutil.NopCloser(&buf) |
| 62 |
response, err := t.Do(encodedRequest) |
| 63 |
if err != nil { |
| 64 |
return nil, err |
| 65 |
} |
| 66 |
decodingReader := base64.NewDecoder(encoding, response.Body) |
| 67 |
decodedResponse := response |
| 68 |
decodedResponse.Body = ioutil.NopCloser(decodingReader) |
| 69 |
return decodedResponse, nil |
| 70 |
}) |
| 71 |
} |
| 72 |
} |