diff --git a/kid.go b/kid.go index 7d3cafa..06a4406 100644 --- a/kid.go +++ b/kid.go @@ -1,8 +1,11 @@ package kid import ( + "fmt" + "io" "net/http" "net/url" + "os" "reflect" "sync" @@ -40,6 +43,9 @@ type ( } ) +// Version is the Kid version. +const Version string = "0.1.0" + // New returns a new instance of Kid. func New() *Kid { kid := Kid{ @@ -51,6 +57,7 @@ func New() *Kid { jsonSerializer: serializer.NewJSONSerializer(), xmlSerializer: serializer.NewXMLSerializer(), htmlRenderer: htmlrenderer.Default(false), + debug: true, } kid.pool.New = func() any { @@ -65,6 +72,11 @@ func New() *Kid { // Specifying an address is optional. Default address is :2376. func (k *Kid) Run(address ...string) error { addr := resolveAddress(address) + + k.printDebug(os.Stdout, "Kid version %s\n", Version) + k.printDebug(os.Stdout, "Starting server at %s\n", addr) + k.printDebug(os.Stdout, "Quit the server with CONTROL-C\n") + return http.ListenAndServe(addr, k) } @@ -230,6 +242,13 @@ func (k *Kid) ApplyOptions(opts ...Option) { } } +// printDebug prints logs only in debug mode. +func (k *Kid) printDebug(w io.Writer, format string, values ...any) { + if k.Debug() { + fmt.Fprintf(w, "[DEBUG] "+format, values...) + } +} + // getPath returns request's path. func getPath(u *url.URL) string { if u.RawPath != "" { diff --git a/kid_test.go b/kid_test.go index 29910ff..b89549b 100644 --- a/kid_test.go +++ b/kid_test.go @@ -1,6 +1,7 @@ package kid import ( + "bytes" "fmt" "io" "net/http" @@ -25,6 +26,7 @@ func TestNew(t *testing.T) { assert.True(t, funcsAreEqual(defaultErrorHandler, k.errorHandler)) assert.True(t, funcsAreEqual(defaultNotFoundHandler, k.notFoundHandler)) assert.True(t, funcsAreEqual(defaultMethodNotAllowedHandler, k.methodNotAllowedHandler)) + assert.True(t, k.Debug()) } func TestKid_Use(t *testing.T) { @@ -559,7 +561,6 @@ func TestKid_Static(t *testing.T) { assert.Equal(t, testCase.expectedContent, testCase.res.Body.String()) }) } - } func TestKid_StaticFS(t *testing.T) { @@ -598,7 +599,21 @@ func TestKid_StaticFS(t *testing.T) { assert.Equal(t, testCase.expectedContent, testCase.res.Body.String()) }) } +} + +func TestKid_printDebug(t *testing.T) { + k := New() + + var w bytes.Buffer + + k.printDebug(&w, "hello %s\n", "Kid") + assert.Equal(t, "[DEBUG] hello Kid\n", w.String()) + + w.Reset() + k.debug = false + k.printDebug(&w, "hello %s\n", "Kid") + assert.Empty(t, w.String()) } func TestResolveAddress(t *testing.T) {