From 81521fec8e7cf080a467ba6fc3581a1e3a6279f5 Mon Sep 17 00:00:00 2001 From: t4niwa <114040262+t4niwa@users.noreply.github.com> Date: Tue, 5 Sep 2023 11:00:39 +0900 Subject: [PATCH] Fix status code when server timeout (#14) * Fix status code when server timeout Signed-off-by: taniwa * fix response body Signed-off-by: taniwa fix --------- Signed-off-by: taniwa --- router/router.go | 6 +++++- router/router_test.go | 41 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/router/router.go b/router/router.go index 9944ba3..b720429 100644 --- a/router/router.go +++ b/router/router.go @@ -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 @@ -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 } diff --git a/router/router_test.go b/router/router_test.go index 053477f..d0dd9a4 100644 --- a/router/router_test.go +++ b/router/router_test.go @@ -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, @@ -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