Skip to content

Commit 81521fe

Browse files
authored
Fix status code when server timeout (#14)
* Fix status code when server timeout Signed-off-by: taniwa <[email protected]> * fix response body Signed-off-by: taniwa <[email protected]> fix --------- Signed-off-by: taniwa <[email protected]>
1 parent 8db0ea2 commit 81521fe

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

router/router.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import (
3030
"github.com/kpango/glg"
3131
)
3232

33-
//New returns Routed ServeMux
33+
// New returns Routed ServeMux
3434
func New(cfg config.Config, h handler.Handler) *http.ServeMux {
3535

3636
http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 32
@@ -76,6 +76,10 @@ func routing(m []string, t time.Duration, h handler.Func) http.Handler {
7676
}
7777
return
7878
case <-ctx.Done():
79+
http.Error(w,
80+
fmt.Sprintf("Error: Handler Time Out by server.timeout\t%s",
81+
http.StatusText(http.StatusServiceUnavailable)),
82+
http.StatusServiceUnavailable)
7983
glg.Errorf("Handler Time Out: %v", time.Since(start))
8084
return
8185
}

router/router_test.go

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
55
you may not use this file except in compliance with the License.
66
You may obtain a copy of the License at
77
8-
http://www.apache.org/licenses/LICENSE-2.0
8+
http://www.apache.org/licenses/LICENSE-2.0
99
1010
Unless required by applicable law or agreed to in writing, software
1111
distributed under the License is distributed on an "AS IS" BASIS,
@@ -383,6 +383,45 @@ func Test_routing(t *testing.T) {
383383
},
384384
}
385385
}(),
386+
func() test {
387+
testStr := "test string"
388+
want := 503
389+
390+
timeoutSec := time.Second * 1
391+
waitSec := time.Second * 10
392+
393+
return test{
394+
name: "Check status code is 503 when timeout",
395+
args: args{
396+
m: []string{
397+
http.MethodGet,
398+
},
399+
t: timeoutSec,
400+
h: func(rw http.ResponseWriter, r *http.Request) error {
401+
time.Sleep(waitSec)
402+
_, err := rw.Write([]byte(testStr))
403+
return err
404+
},
405+
},
406+
checkFunc: func(server http.Handler) error {
407+
request := httptest.NewRequest(http.MethodGet, "/", nil)
408+
record := httptest.NewRecorder()
409+
server.ServeHTTP(record, request)
410+
response := record.Result()
411+
412+
defer response.Body.Close()
413+
fmt.Println("response.StatusCode: ", response.StatusCode)
414+
415+
// check status code
416+
got := response.StatusCode
417+
if got != want {
418+
return fmt.Errorf("Status code is invalid: request: %v got: %v want: %v", request, got, want)
419+
}
420+
421+
return nil
422+
},
423+
}
424+
}(),
386425
func() test {
387426
timeoutSec := time.Second * 1
388427
want := io.ErrClosedPipe

0 commit comments

Comments
 (0)