-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
transport.go
69 lines (57 loc) · 1.97 KB
/
transport.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
// transport.go
//
// Copyright (c) 2018-2023 Junpei Kawamoto
//
// This software is released under the MIT License.
//
// http://opensource.org/licenses/mit-license.php
package pixeldrain
import (
"net/http"
"github.com/go-openapi/runtime"
)
// roundTripper is a http.RoundTripper that forwards a request to the upstream and fixes content type header of the
// corresponding response.
type roundTripper struct {
upstream http.RoundTripper
contentType string
}
var _ http.RoundTripper = (*roundTripper)(nil)
// newRoundTripper creates a roundTripper which wraps a given roundTripper and overwrites the content types of responses.
func newRoundTripper(upstream http.RoundTripper, contentType string) *roundTripper {
return &roundTripper{
upstream: upstream,
contentType: contentType,
}
}
// RoundTrip executes a single HTTP transaction, returning a Response for the provided Request.
func (t *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
res, err := t.upstream.RoundTrip(req)
if err != nil {
return nil, err
}
if res.StatusCode < 300 {
res.Header.Set(runtime.HeaderContentType, t.contentType)
}
return res, nil
}
// transport is a runtime.ClientTransport that modifies the http client of each request and forwards the request to the
// upstream transport.
type transport struct {
upstream runtime.ClientTransport
}
var _ runtime.ClientTransport = (*transport)(nil)
// ContentTypeFixer returns a new ClientTransport that wraps the given ClientTransport to fix the content type issue.
func ContentTypeFixer(upstream runtime.ClientTransport) runtime.ClientTransport {
return &transport{upstream: upstream}
}
// Submit sends the given operation and returns a response.
func (t *transport) Submit(op *runtime.ClientOperation) (interface{}, error) {
if op.Client == nil {
op.Client = &http.Client{
Transport: http.DefaultTransport,
}
}
op.Client.Transport = newRoundTripper(op.Client.Transport, op.ProducesMediaTypes[0])
return t.upstream.Submit(op)
}