Skip to content

Commit 3ba7136

Browse files
yahya077yahya.hindioglu
authored andcommitted
less allocation for response
1 parent f25c453 commit 3ba7136

File tree

10 files changed

+53
-110
lines changed

10 files changed

+53
-110
lines changed

elevator/elevator.go

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ type IElevatorEngine interface {
3636
WarmUp() IElevatorEngine
3737
PutBodyParser(roomKey, requestKey string, bodyParser room.IBodyParser) IElevatorEngine
3838
PutQuery(roomKey, requestKey string, authStrategy room.IQuery) IElevatorEngine
39-
PutDTO(roomKey, requestKey string, dto any) IElevatorEngine
4039
GetElapsedTime() float64
4140
}
4241

@@ -61,7 +60,6 @@ func NewElevatorEngine(elevator Elevator) IElevatorEngine {
6160
}
6261
}
6362

64-
// TODO add safety check
6563
func (e *ElevatorEngine) Execute(roomKey, requestKey string) (room.Response, error) {
6664
if roomContainerEntry, ok := e.RoomContainers[roomKey]; ok {
6765
if requestEntry, ok := roomContainerEntry.Requests[requestKey]; ok {
@@ -165,10 +163,6 @@ func (e *ElevatorEngine) CreateRequest(req Request) *room.Request {
165163
room.WithBody(parser),
166164
}
167165

168-
if req.ForceDTO {
169-
optionRequests = append(optionRequests, room.ForceDTO())
170-
}
171-
172166
r := room.NewRequest(
173167
req.Path,
174168
optionRequests...,
@@ -201,18 +195,6 @@ func (e *ElevatorEngine) PutQuery(roomKey, requestKey string, query room.IQuery)
201195
panic(fmt.Sprintf("engine for %s not configured", roomKey))
202196
}
203197

204-
func (e *ElevatorEngine) PutDTO(roomKey, requestKey string, dto any) IElevatorEngine {
205-
if roomContainerEntry, ok := e.RoomContainers[roomKey]; ok {
206-
if requestEntry, ok := roomContainerEntry.Requests[requestKey]; ok {
207-
requestEntry.DTO = dto
208-
return e
209-
}
210-
panic(fmt.Sprintf("engine for %s on %s not configured", roomKey, requestKey))
211-
}
212-
213-
panic(fmt.Sprintf("engine for %s not configured", roomKey))
214-
}
215-
216198
func NewElevator(integrationYmlPath string) Elevator {
217199
ymlFile, err := readYml(integrationYmlPath)
218200

@@ -292,7 +274,6 @@ type Request struct {
292274
ConcurrentKey string `yaml:"concurrentKey"`
293275
Method string `yaml:"method"`
294276
Path string `yaml:"path"`
295-
ForceDTO bool `yaml:"forceDTO"`
296277
Body Body `yaml:"body"`
297278
}
298279

examples/solo_request/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ import (
66
)
77

88
func main() {
9-
response, err := room.NewRequest("https://jsonplaceholder.typicode.com/posts/1", room.ForceDTO()).Send()
9+
response, err := room.NewRequest("https://jsonplaceholder.typicode.com/posts/1").Send()
1010

1111
fmt.Println(err)
1212

13-
fmt.Println("Response:", response.DTO)
13+
fmt.Println("Response:", response.ResponseBody())
1414
}

examples/yml_concurrent_example/integration.yml

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ flat:
1212
concurrentKey: "add"
1313
method: "POST"
1414
path: "todos/add"
15-
forceDTO: true
1615
todo1Room:
1716
connection:
1817
baseUrl: ${BASE_URL}
@@ -25,7 +24,6 @@ flat:
2524
concurrentKey: "add"
2625
method: "POST"
2726
path: "todos/add?delay=3000"
28-
forceDTO: true
2927
todo2Room:
3028
connection:
3129
baseUrl: ${BASE_URL}
@@ -38,4 +36,3 @@ flat:
3836
concurrentKey: "add"
3937
method: "POST"
4038
path: "todos/add"
41-
forceDTO: true

examples/yml_example/integration.yml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ flat:
1212
request:
1313
method: "POST"
1414
path: "auth/login"
15-
forceDTO: true
1615
body:
1716
type: "json"
1817
content:
@@ -24,4 +23,3 @@ flat:
2423
concurrentKey: "add"
2524
method: "POST"
2625
path: "todos/add"
27-
forceDTO: true

examples/yml_example/main.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@ var payload = AddTODORequest{
1818
UserId: 1,
1919
}
2020

21+
type ResponseSchema struct {
22+
Completed bool `json:"completed"`
23+
Id int `json:"id"`
24+
Todo string `json:"todo"`
25+
UserId int `json:"userId"`
26+
}
27+
2128
func main() {
2229
el := elevator.NewElevator("examples/yml_example/integration.yml")
2330
engine := elevator.NewElevatorEngine(el).WarmUp()
@@ -27,6 +34,7 @@ func main() {
2734
Execute("todoRoom", "addTodo")
2835

2936
fmt.Println(err)
37+
3038
fmt.Println("Response OK: ", response.OK())
31-
fmt.Println("Response DTO: ", response.DTO)
39+
fmt.Println("Response DTO: ", response.DTO(&ResponseSchema{}))
3240
}

request.go

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,6 @@ type Request struct {
2626
Query IQuery
2727
BodyParser IBodyParser
2828
contextBuilder IContextBuilder
29-
DTO any
30-
// ForceDTO is a flag to force the parse http response to DTO which is map[string]any
31-
ForceDTO bool
3229
}
3330

3431
// NewRequest creates a new request
@@ -51,10 +48,6 @@ func NewRequest(path string, opts ...OptionRequest) *Request {
5148
r.method = GET
5249
}
5350

54-
if r.ForceDTO && r.DTO == nil {
55-
r.DTO = make(map[string]any)
56-
}
57-
5851
return r
5952
}
6053

@@ -67,7 +60,7 @@ func (r *Request) Send() (Response, error) {
6760
return Response{}, e
6861
}
6962

70-
return NewResponse(response, r.DTO)
63+
return NewResponse(response)
7164
}
7265

7366
func (r *Request) request() *http.Request {
@@ -148,18 +141,6 @@ func WithHeader(header IHeader) OptionRequest {
148141
}
149142
}
150143

151-
func WithDTO(dto any) OptionRequest {
152-
return func(request *Request) {
153-
request.DTO = dto
154-
}
155-
}
156-
157-
func ForceDTO() OptionRequest {
158-
return func(request *Request) {
159-
request.ForceDTO = true
160-
}
161-
}
162-
163144
func WithContextBuilder(contextBuilder IContextBuilder) OptionRequest {
164145
return func(request *Request) {
165146
request.contextBuilder = contextBuilder

response.go

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package room
33
import (
44
"encoding/json"
55
"encoding/xml"
6+
"errors"
67
"github.com/WEG-Technology/room/store"
78
"io"
89
"net/http"
@@ -16,29 +17,24 @@ type Response struct {
1617
Header IHeader
1718
RequestHeader IHeader
1819
RequestBody map[string]any
19-
DTO any
2020
Data []byte
2121
}
2222

23-
func NewResponse(r *http.Response, dto any) (Response, error) {
23+
func NewResponse(r *http.Response) (Response, error) {
2424
response := Response{
2525
StatusCode: r.StatusCode,
2626
Method: r.Request.Method,
2727
RequestBody: map[string]any{},
2828
}.
2929
setHeader(r.Header).
3030
setRequestHeader(r.Request.Header).
31-
setRequestBodyData(r.Request).
31+
setRequestBody(r.Request).
3232
setRequestURI(r.Request)
3333

3434
var err error
3535

3636
response, err = response.setData(r)
3737

38-
if dto != nil {
39-
response, err = response.setDTO(dto)
40-
}
41-
4238
return response, err
4339
}
4440

@@ -70,7 +66,7 @@ func (r Response) setRequestHeader(header http.Header) Response {
7066
return r
7167
}
7268

73-
func (r Response) setRequestBodyData(request *http.Request) Response {
69+
func (r Response) setRequestBody(request *http.Request) Response {
7470
if request.Body != nil {
7571
decoder := json.NewDecoder(request.Body)
7672

@@ -91,19 +87,41 @@ func (r Response) setRequestURI(request *http.Request) Response {
9187
}
9288

9389
func (r Response) setData(response *http.Response) (Response, error) {
94-
var err error
90+
if response.Body != nil {
91+
var err error
92+
93+
r.Data, err = io.ReadAll(response.Body)
94+
95+
return r, err
96+
}
97+
98+
return r, errors.New("responseBody is nil")
99+
}
100+
101+
func (r Response) ResponseBodyOrFail() (map[string]any, error) {
102+
var body map[string]any
95103

96-
r.Data, err = io.ReadAll(response.Body)
104+
err := NewDTOFactory(r.Header.Get(headerKeyAccept)).marshall(r.Data, &body)
97105

98-
return r, err
106+
return body, err
99107
}
100108

101-
func (r Response) setDTO(dto any) (Response, error) {
102-
r.DTO = dto
109+
func (r Response) ResponseBody() map[string]any {
110+
var body map[string]any
103111

104-
err := NewDTOFactory(r.Header.Get(headerKeyAccept)).marshall(r.Data, &r.DTO)
112+
_ = NewDTOFactory(r.Header.Get(headerKeyAccept)).marshall(r.Data, &body)
113+
114+
return body
115+
}
116+
117+
func (r Response) DTO(v any) any {
118+
_ = NewDTOFactory(r.Header.Get(headerKeyAccept)).marshall(r.Data, v)
119+
120+
return v
121+
}
105122

106-
return r, err
123+
func (r Response) DTOorFail(v any) error {
124+
return NewDTOFactory(r.Header.Get(headerKeyAccept)).marshall(r.Data, v)
107125
}
108126

109127
// IDTOFactory declares the interface for creating DTOs.

response_test.go

Lines changed: 3 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -26,25 +26,17 @@ func TestNewResponse(t *testing.T) {
2626
}
2727

2828
// Test case for successful creation of Response
29-
resp, err := NewResponse(httpResp, false)
29+
resp, err := NewResponse(httpResp)
3030
if err != nil {
3131
t.Errorf("NewResponse() returned unexpected error: %v", err)
3232
}
3333
if resp.StatusCode != http.StatusOK {
3434
t.Errorf("NewResponse() returned response with unexpected status code: %d", resp.StatusCode)
3535
}
3636

37-
// Test case for DTO creation when forceDTO is true
38-
resp, err = NewResponse(httpResp, true)
39-
if err != nil {
40-
t.Errorf("NewResponse(forceDTO=true) returned unexpected error: %v", err)
41-
}
42-
if resp.DTO == nil {
43-
t.Error("NewResponse(forceDTO=true) did not create DTO")
44-
}
45-
4637
// Test case for error in NewResponse
47-
resp, err = NewResponse(httpResp, false)
38+
httpResp.Body = nil
39+
resp, err = NewResponse(httpResp)
4840
if err == nil {
4941
t.Error("NewResponse() did not return expected error for HTTP client error")
5042
}
@@ -89,20 +81,6 @@ func TestResponse_SetRequestHeader(t *testing.T) {
8981
}
9082
}
9183

92-
// TestResponse_SetRequestBodyData tests the SetRequestBodyData method of the Response struct.
93-
func TestResponse_SetRequestBodyData(t *testing.T) {
94-
// Test case for setting request body data
95-
reqBody := &strings.Reader{}
96-
httpReq := &http.Request{
97-
Body: io.NopCloser(reqBody),
98-
}
99-
response := Response{}
100-
response = response.setRequestBodyData(httpReq)
101-
if response.RequestBody == nil {
102-
t.Error("Response SetRequestBodyData() did not set the request body data correctly")
103-
}
104-
}
105-
10684
// TestResponse_SetRequestURI tests the SetRequestURI method of the Response struct.
10785
func TestResponse_SetRequestURI(t *testing.T) {
10886
// Test case for setting request URI
@@ -136,21 +114,3 @@ func TestResponse_SetData(t *testing.T) {
136114
t.Error("Response SetData() did not set the response data correctly")
137115
}
138116
}
139-
140-
type TestDTO struct {
141-
Key string `json:"key"`
142-
}
143-
144-
// TestResponse_SetDTO tests the SetDTO method of the Response struct.
145-
func TestResponse_SetDTO(t *testing.T) {
146-
// Test case for setting DTO
147-
response := Response{Header: NewHeader(), Data: []byte(`{"key": "value"}`), DTO: &TestDTO{}}
148-
response, err := response.setDTO(false)
149-
if err != nil {
150-
t.Errorf("Response SetDTO() returned unexpected error: %v", err)
151-
}
152-
153-
if response.DTO == nil {
154-
t.Error("Response SetDTO() did not set the DTO correctly")
155-
}
156-
}

room.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func (r *AuthRoom) Send(request *Request) (Response, error) {
4848
return response, err
4949
}
5050

51-
if token, found := findToken(response.DTO.(map[string]any), r.AuthToken); found {
51+
if token, found := findToken(response.ResponseBody(), r.AuthToken); found {
5252
r.Connector.Header.Add("Authorization", "Bearer "+token)
5353
} else {
5454
return response, errors.New(ErrAuthRoomCanNotFoundKey)
@@ -65,7 +65,7 @@ type IAuth interface {
6565
type AccessTokenAuth struct{}
6666

6767
func (a AccessTokenAuth) Apply(connector *Connector, response Response) {
68-
connector.Header.Add("Authorization", "Bearer "+response.DTO.(map[string]any)["access_token"].(string))
68+
connector.Header.Add("Authorization", "Bearer "+response.ResponseBody()["access_token"].(string))
6969
}
7070

7171
func NewAccessTokenAuth() IAuth {

store/store.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,9 @@ func (s *MapStore) StringAll() string {
6363

6464
parts := make([]string, len(keys))
6565

66-
for i, key := range keys {
67-
value := v.MapIndex(key).Interface()
68-
parts[i] = fmt.Sprintf("%v: %v", key.Interface(), value)
66+
for i := 0; i < len(keys); i++ {
67+
value := v.MapIndex(keys[i]).Interface()
68+
parts[i] = fmt.Sprintf("%v: %v", keys[i].Interface(), value)
6969
}
7070

7171
return strings.Join(parts, ", ")

0 commit comments

Comments
 (0)