Skip to content

Commit

Permalink
Fix status code when server timeout (#14)
Browse files Browse the repository at this point in the history
* Fix status code when server timeout

Signed-off-by: taniwa <taniwa@yahoo-corp.jp>

* fix response body

Signed-off-by: taniwa <taniwa@yahoo-corp.jp>

fix

---------

Signed-off-by: taniwa <taniwa@yahoo-corp.jp>
  • Loading branch information
t4niwa authored Sep 5, 2023
1 parent 8db0ea2 commit 81521fe
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
6 changes: 5 additions & 1 deletion router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import (
"github.com/kpango/glg"
)

//New returns Routed ServeMux
// New returns Routed ServeMux
func New(cfg config.Config, h handler.Handler) *http.ServeMux {

http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 32
Expand Down Expand Up @@ -76,6 +76,10 @@ func routing(m []string, t time.Duration, h handler.Func) http.Handler {
}
return
case <-ctx.Done():
http.Error(w,
fmt.Sprintf("Error: Handler Time Out by server.timeout\t%s",
http.StatusText(http.StatusServiceUnavailable)),
http.StatusServiceUnavailable)
glg.Errorf("Handler Time Out: %v", time.Since(start))
return
}
Expand Down
41 changes: 40 additions & 1 deletion router/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
Expand Down Expand Up @@ -383,6 +383,45 @@ func Test_routing(t *testing.T) {
},
}
}(),
func() test {
testStr := "test string"
want := 503

timeoutSec := time.Second * 1
waitSec := time.Second * 10

return test{
name: "Check status code is 503 when timeout",
args: args{
m: []string{
http.MethodGet,
},
t: timeoutSec,
h: func(rw http.ResponseWriter, r *http.Request) error {
time.Sleep(waitSec)
_, err := rw.Write([]byte(testStr))
return err
},
},
checkFunc: func(server http.Handler) error {
request := httptest.NewRequest(http.MethodGet, "/", nil)
record := httptest.NewRecorder()
server.ServeHTTP(record, request)
response := record.Result()

defer response.Body.Close()
fmt.Println("response.StatusCode: ", response.StatusCode)

// check status code
got := response.StatusCode
if got != want {
return fmt.Errorf("Status code is invalid: request: %v got: %v want: %v", request, got, want)
}

return nil
},
}
}(),
func() test {
timeoutSec := time.Second * 1
want := io.ErrClosedPipe
Expand Down

0 comments on commit 81521fe

Please sign in to comment.