From 0fdc417945fb87aef9c496afab209ac05480c249 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Tue, 17 Sep 2024 15:03:27 +0300 Subject: [PATCH 01/30] feat: simple http client --- go.mod | 3 +++ main.go | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 go.mod create mode 100644 main.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..03b94aa --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/codescalersinternships/Datetime-client-RawanMostafa + +go 1.23.1 diff --git a/main.go b/main.go new file mode 100644 index 0000000..685d81f --- /dev/null +++ b/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "io" + "log" + "net/http" +) + +func main() { + c := http.Client{} + resp, err := c.Get("http://localhost:8080/datetime") + if err != nil { + log.Fatalf("Error in sending request: %v", err) + return + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatalf("Error in reading request body: %v", err) + return + } + fmt.Println(string(body)) +} From fc70fe48b5e3535f6522418f76f251bf2f53e9c5 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Tue, 17 Sep 2024 15:28:43 +0300 Subject: [PATCH 02/30] fix: edit file structure --- main.go => cmd/httpclient/main.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) rename main.go => cmd/httpclient/main.go (84%) diff --git a/main.go b/cmd/httpclient/main.go similarity index 84% rename from main.go rename to cmd/httpclient/main.go index 685d81f..05c8beb 100644 --- a/main.go +++ b/cmd/httpclient/main.go @@ -5,10 +5,11 @@ import ( "io" "log" "net/http" + "time" ) func main() { - c := http.Client{} + c := http.Client{Timeout: time.Duration(1) * time.Second} resp, err := c.Get("http://localhost:8080/datetime") if err != nil { log.Fatalf("Error in sending request: %v", err) From 06f35540922a898fea60e2da1b0a8fc43963f1d9 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Wed, 18 Sep 2024 12:59:45 +0300 Subject: [PATCH 03/30] fix: edit project structure and code organization --- cmd/ginclient/main.go | 20 +++++++++++ cmd/httpclient/main.go | 21 +++++------- go.mod | 30 ++++++++++++++++ go.sum | 77 ++++++++++++++++++++++++++++++++++++++++++ pkg/callers.go | 30 ++++++++++++++++ 5 files changed, 165 insertions(+), 13 deletions(-) create mode 100644 cmd/ginclient/main.go create mode 100644 go.sum create mode 100644 pkg/callers.go diff --git a/cmd/ginclient/main.go b/cmd/ginclient/main.go new file mode 100644 index 0000000..7f3d683 --- /dev/null +++ b/cmd/ginclient/main.go @@ -0,0 +1,20 @@ +package main + +import ( + "log" + + pkg "github.com/codescalersinternships/Datetime-client-RawanMostafa/pkg" +) + +func main() { + c := pkg.CreateClient() + resp, err := pkg.SendRequest(c, "8083") + if err != nil { + log.Fatal(err) + } + body, err := pkg.ReadBody(resp) + if err != nil { + log.Fatal(err) + } + log.Println(body) +} diff --git a/cmd/httpclient/main.go b/cmd/httpclient/main.go index 05c8beb..0c61ab0 100644 --- a/cmd/httpclient/main.go +++ b/cmd/httpclient/main.go @@ -1,25 +1,20 @@ package main import ( - "fmt" - "io" "log" - "net/http" - "time" + + pkg "github.com/codescalersinternships/Datetime-client-RawanMostafa/pkg" ) func main() { - c := http.Client{Timeout: time.Duration(1) * time.Second} - resp, err := c.Get("http://localhost:8080/datetime") + c := pkg.CreateClient() + resp, err := pkg.SendRequest(c, "8080") if err != nil { - log.Fatalf("Error in sending request: %v", err) - return + log.Fatal(err) } - defer resp.Body.Close() - body, err := io.ReadAll(resp.Body) + body, err := pkg.ReadBody(resp) if err != nil { - log.Fatalf("Error in reading request body: %v", err) - return + log.Fatal(err) } - fmt.Println(string(body)) + log.Println(body) } diff --git a/go.mod b/go.mod index 03b94aa..60c497a 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,33 @@ module github.com/codescalersinternships/Datetime-client-RawanMostafa go 1.23.1 + +require ( + github.com/bytedance/sonic v1.12.2 // indirect + github.com/bytedance/sonic/loader v0.2.0 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.5 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.10.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.22.1 // indirect + github.com/goccy/go-json v0.10.3 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.8 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.10.0 // indirect + golang.org/x/crypto v0.27.0 // indirect + golang.org/x/net v0.29.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.18.0 // indirect + google.golang.org/protobuf v1.34.2 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..1de6a82 --- /dev/null +++ b/go.sum @@ -0,0 +1,77 @@ +github.com/bytedance/sonic v1.12.2 h1:oaMFuRTpMHYLpCntGca65YWt5ny+wAceDERTkT2L9lg= +github.com/bytedance/sonic v1.12.2/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP1iU4kWM= +github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.5 h1:J7wGKdGu33ocBOhGy0z653k/lFKLFDPJMG8Gql0kxn4= +github.com/gabriel-vasile/mimetype v1.4.5/go.mod h1:ibHel+/kbxn9x2407k1izTA1S81ku1z/DlgOW2QE0M4= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.22.1 h1:40JcKH+bBNGFczGuoBYgX4I6m/i27HYW8P9FDk5PbgA= +github.com/go-playground/validator/v10 v10.22.1/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM= +github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8= +golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= +golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/pkg/callers.go b/pkg/callers.go new file mode 100644 index 0000000..0febef1 --- /dev/null +++ b/pkg/callers.go @@ -0,0 +1,30 @@ +package pkg + +import ( + "fmt" + "io" + "net/http" + "time" +) + +func CreateClient() http.Client { + return http.Client{Timeout: time.Duration(1) * time.Second} +} + +func ReadBody(resp *http.Response) (string, error) { + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("error in reading request body: %v", err) + + } + return string(body), nil +} + +func SendRequest(c http.Client, port string) (*http.Response, error) { + resp, err := c.Get("http://localhost:" + port + "/datetime") + if err != nil { + return nil, fmt.Errorf("error in sending request: %v", err) + } + return resp, nil +} From 98c792add02548a2b087aad456756a4d60df1154 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Wed, 18 Sep 2024 15:50:47 +0300 Subject: [PATCH 04/30] fix: project structure --- cmd/ginclient/main.go | 20 -------------------- cmd/{httpclient => }/main.go | 0 2 files changed, 20 deletions(-) delete mode 100644 cmd/ginclient/main.go rename cmd/{httpclient => }/main.go (100%) diff --git a/cmd/ginclient/main.go b/cmd/ginclient/main.go deleted file mode 100644 index 7f3d683..0000000 --- a/cmd/ginclient/main.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "log" - - pkg "github.com/codescalersinternships/Datetime-client-RawanMostafa/pkg" -) - -func main() { - c := pkg.CreateClient() - resp, err := pkg.SendRequest(c, "8083") - if err != nil { - log.Fatal(err) - } - body, err := pkg.ReadBody(resp) - if err != nil { - log.Fatal(err) - } - log.Println(body) -} diff --git a/cmd/httpclient/main.go b/cmd/main.go similarity index 100% rename from cmd/httpclient/main.go rename to cmd/main.go From dab676cd8f624e9251854a3ecc13523b9c8db6fe Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Wed, 18 Sep 2024 16:35:05 +0300 Subject: [PATCH 05/30] feat: Adding configurable url,port,endpoint using flags --- cmd/main.go | 16 +++++++++++++++- pkg/callers.go | 4 ++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 0c61ab0..b56671e 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -1,14 +1,28 @@ package main import ( + "flag" + "fmt" "log" pkg "github.com/codescalersinternships/Datetime-client-RawanMostafa/pkg" ) func main() { + + var port int + flag.IntVar(&port, "port", 0, "Specifies the port") + + var url string + flag.StringVar(&url, "url", "", "Specifies the base url") + + var endpoint string + flag.StringVar(&endpoint, "endpoint", "", "Specifies the endpoint") + + flag.Parse() + c := pkg.CreateClient() - resp, err := pkg.SendRequest(c, "8080") + resp, err := pkg.SendRequest(c, url, endpoint, fmt.Sprint(port)) if err != nil { log.Fatal(err) } diff --git a/pkg/callers.go b/pkg/callers.go index 0febef1..5271e55 100644 --- a/pkg/callers.go +++ b/pkg/callers.go @@ -21,8 +21,8 @@ func ReadBody(resp *http.Response) (string, error) { return string(body), nil } -func SendRequest(c http.Client, port string) (*http.Response, error) { - resp, err := c.Get("http://localhost:" + port + "/datetime") +func SendRequest(c http.Client, baseUrl string, endpoint string, port string) (*http.Response, error) { + resp, err := c.Get(baseUrl + ":" + port + endpoint) if err != nil { return nil, fmt.Errorf("error in sending request: %v", err) } From e007cde5ba13388961e47c652a0a53d5390694f4 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Thu, 19 Sep 2024 12:20:32 +0300 Subject: [PATCH 06/30] feat: add env var configurations --- .github/workflows/main.yaml | 44 +++++++++++++++++++++++++++++++++++++ cmd/main.go | 31 +++++++++++++++++++++----- pkg/callers.go | 19 ++++++++++++++-- 3 files changed, 87 insertions(+), 7 deletions(-) create mode 100644 .github/workflows/main.yaml diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml new file mode 100644 index 0000000..63258b1 --- /dev/null +++ b/.github/workflows/main.yaml @@ -0,0 +1,44 @@ +name: Go CI + +on: + push: + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: '1.23.1' + - name: Build + run: go build -v ./... + + + golangci: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: stable + - name: golangci-lint + uses: golangci/golangci-lint-action@v6 + with: + version: v1.60 + - name: Go Format + uses: Jerome1337/gofmt-action@v1.0.5 + with: + gofmt-path: './src' + gofmt-flags: '-l -d' + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: stable + - name: Test with the Go CLI + run: go test -v ./pkg diff --git a/cmd/main.go b/cmd/main.go index b56671e..247dd1d 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,16 +2,30 @@ package main import ( "flag" - "fmt" "log" + "os" pkg "github.com/codescalersinternships/Datetime-client-RawanMostafa/pkg" ) -func main() { +func setEnv(url string, endpoint string, port string) { + err := os.Setenv("DATETIME_URL", url) + if err != nil { + log.Fatalf("Error in setting url env var: %v", err) + } + err = os.Setenv("DATETIME_ENDPOINT", endpoint) + if err != nil { + log.Fatalf("Error in setting endpoint env var: %v", err) + } + err = os.Setenv("DATETIME_PORT", port) + if err != nil { + log.Fatalf("Error in setting port env var: %v", err) + } +} - var port int - flag.IntVar(&port, "port", 0, "Specifies the port") +func getFlags() (string, string, string) { + var port string + flag.StringVar(&port, "port", "", "Specifies the port") var url string flag.StringVar(&url, "url", "", "Specifies the base url") @@ -20,9 +34,16 @@ func main() { flag.StringVar(&endpoint, "endpoint", "", "Specifies the endpoint") flag.Parse() + return url, endpoint, port +} +func main() { + + url, endpoint, port := getFlags() + + setEnv(url, endpoint, port) c := pkg.CreateClient() - resp, err := pkg.SendRequest(c, url, endpoint, fmt.Sprint(port)) + resp, err := pkg.SendRequest(c) if err != nil { log.Fatal(err) } diff --git a/pkg/callers.go b/pkg/callers.go index 5271e55..6096b65 100644 --- a/pkg/callers.go +++ b/pkg/callers.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "net/http" + "os" "time" ) @@ -21,8 +22,22 @@ func ReadBody(resp *http.Response) (string, error) { return string(body), nil } -func SendRequest(c http.Client, baseUrl string, endpoint string, port string) (*http.Response, error) { - resp, err := c.Get(baseUrl + ":" + port + endpoint) +func SendRequest(c http.Client) (*http.Response, error) { + url := os.Getenv("DATETIME_URL") + endpoint := os.Getenv("DATETIME_ENDPOINT") + port := os.Getenv("DATETIME_PORT") + + if url == "" { + url = "http://localhost" + } + if endpoint == "" { + endpoint = "/datetime" + } + if port == "" { + port = "8083" + } + + resp, err := c.Get(url + ":" + port + endpoint) if err != nil { return nil, fmt.Errorf("error in sending request: %v", err) } From 8f3d9f30ee317f4a7d7991f629c05f5e4a3dedcd Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Thu, 19 Sep 2024 13:20:05 +0300 Subject: [PATCH 07/30] fix: edit code organization and dependencies --- cmd/main.go | 69 ++++++++++++++++++++++++++++++---------------- pkg/callers.go | 45 ------------------------------ pkg/client.go | 42 ++++++++++++++++++++++++++++ pkg/client_test.go | 7 +++++ 4 files changed, 95 insertions(+), 68 deletions(-) delete mode 100644 pkg/callers.go create mode 100644 pkg/client.go create mode 100644 pkg/client_test.go diff --git a/cmd/main.go b/cmd/main.go index 247dd1d..8988deb 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -4,50 +4,73 @@ import ( "flag" "log" "os" + "time" pkg "github.com/codescalersinternships/Datetime-client-RawanMostafa/pkg" ) -func setEnv(url string, endpoint string, port string) { - err := os.Setenv("DATETIME_URL", url) - if err != nil { - log.Fatalf("Error in setting url env var: %v", err) - } - err = os.Setenv("DATETIME_ENDPOINT", endpoint) - if err != nil { - log.Fatalf("Error in setting endpoint env var: %v", err) - } - err = os.Setenv("DATETIME_PORT", port) - if err != nil { - log.Fatalf("Error in setting port env var: %v", err) - } -} +const defaltBaseUrl = "http://localhost" +const defaultEndpoint = "/datetime" +const defaultPort = "8083" func getFlags() (string, string, string) { var port string flag.StringVar(&port, "port", "", "Specifies the port") - var url string - flag.StringVar(&url, "url", "", "Specifies the base url") + var baseUrl string + flag.StringVar(&baseUrl, "baseUrl", "", "Specifies the base url") var endpoint string flag.StringVar(&endpoint, "endpoint", "", "Specifies the endpoint") flag.Parse() - return url, endpoint, port + return baseUrl, endpoint, port } -func main() { - url, endpoint, port := getFlags() +func decideConfigs() (string, string, string) { + + baseUrl, endpoint, port := getFlags() + + if baseUrl == "" { + envBaseUrl, found := os.LookupEnv("DATETIME_BASEURL") - setEnv(url, endpoint, port) + if found { + baseUrl = envBaseUrl + } else { + baseUrl = defaltBaseUrl + } + } + if endpoint == "" { + envEndpoint, found := os.LookupEnv("DATETIME_ENDPOINT") + + if found { + endpoint = envEndpoint + } else { + endpoint = defaultEndpoint + } + } + if port == "" { + envPort, found := os.LookupEnv("DATETIME_PORT") + + if found { + port = envPort + } else { + port = defaultPort + } + } + return baseUrl, endpoint, port + +} + +func main() { + baseUrl, endpoint, port := decideConfigs() - c := pkg.CreateClient() - resp, err := pkg.SendRequest(c) + c := pkg.NewClient(baseUrl, endpoint, port, time.Second) + resp, err := c.SendRequest() if err != nil { log.Fatal(err) } - body, err := pkg.ReadBody(resp) + body, err := c.ReadBody(resp) if err != nil { log.Fatal(err) } diff --git a/pkg/callers.go b/pkg/callers.go deleted file mode 100644 index 6096b65..0000000 --- a/pkg/callers.go +++ /dev/null @@ -1,45 +0,0 @@ -package pkg - -import ( - "fmt" - "io" - "net/http" - "os" - "time" -) - -func CreateClient() http.Client { - return http.Client{Timeout: time.Duration(1) * time.Second} -} - -func ReadBody(resp *http.Response) (string, error) { - defer resp.Body.Close() - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", fmt.Errorf("error in reading request body: %v", err) - - } - return string(body), nil -} - -func SendRequest(c http.Client) (*http.Response, error) { - url := os.Getenv("DATETIME_URL") - endpoint := os.Getenv("DATETIME_ENDPOINT") - port := os.Getenv("DATETIME_PORT") - - if url == "" { - url = "http://localhost" - } - if endpoint == "" { - endpoint = "/datetime" - } - if port == "" { - port = "8083" - } - - resp, err := c.Get(url + ":" + port + endpoint) - if err != nil { - return nil, fmt.Errorf("error in sending request: %v", err) - } - return resp, nil -} diff --git a/pkg/client.go b/pkg/client.go new file mode 100644 index 0000000..f70e8ed --- /dev/null +++ b/pkg/client.go @@ -0,0 +1,42 @@ +package pkg + +import ( + "fmt" + "io" + "net/http" + "time" +) + +type Client struct { + baseUrl string + endpoint string + port string + client http.Client +} + +func NewClient(baseUrl string, endpoint string, port string, timeout time.Duration) Client { + return Client{ + baseUrl: baseUrl, + endpoint: endpoint, + port: port, + client: http.Client{Timeout: timeout}, + } +} + +func (c Client) ReadBody(resp *http.Response) (string, error) { + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("error in reading request body: %v", err) + + } + return string(body), nil +} + +func (c Client) SendRequest() (*http.Response, error) { + resp, err := c.client.Get(c.baseUrl + ":" + c.port + c.endpoint) + if err != nil { + return nil, fmt.Errorf("error in sending request: %v", err) + } + return resp, nil +} diff --git a/pkg/client_test.go b/pkg/client_test.go new file mode 100644 index 0000000..7bdac7b --- /dev/null +++ b/pkg/client_test.go @@ -0,0 +1,7 @@ +package pkg +import ( + "testing" +) +func TestSendRequest(t *testing.T) { + +} \ No newline at end of file From 6ec3abd1612fb2cc157876b3ced4b1069b906196 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Thu, 19 Sep 2024 14:53:04 +0300 Subject: [PATCH 08/30] test: sendRequest test --- cmd/main.go | 17 ++++++- pkg/client.go | 16 ++---- pkg/client_test.go | 121 +++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 138 insertions(+), 16 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 8988deb..76d330d 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,7 +2,10 @@ package main import ( "flag" + "fmt" + "io" "log" + "net/http" "os" "time" @@ -13,6 +16,16 @@ const defaltBaseUrl = "http://localhost" const defaultEndpoint = "/datetime" const defaultPort = "8083" +func readBody(resp *http.Response) (string, error) { + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("error in reading request body: %v", err) + + } + return string(body), nil +} + func getFlags() (string, string, string) { var port string flag.StringVar(&port, "port", "", "Specifies the port") @@ -66,11 +79,11 @@ func main() { baseUrl, endpoint, port := decideConfigs() c := pkg.NewClient(baseUrl, endpoint, port, time.Second) - resp, err := c.SendRequest() + resp, err := c.SendRequest("text/plain") if err != nil { log.Fatal(err) } - body, err := c.ReadBody(resp) + body, err := readBody(resp) if err != nil { log.Fatal(err) } diff --git a/pkg/client.go b/pkg/client.go index f70e8ed..75d8bc5 100644 --- a/pkg/client.go +++ b/pkg/client.go @@ -2,7 +2,6 @@ package pkg import ( "fmt" - "io" "net/http" "time" ) @@ -23,18 +22,13 @@ func NewClient(baseUrl string, endpoint string, port string, timeout time.Durati } } -func (c Client) ReadBody(resp *http.Response) (string, error) { - defer resp.Body.Close() - body, err := io.ReadAll(resp.Body) +func (c Client) SendRequest(contentType string) (*http.Response, error) { + req, err := http.NewRequest("GET", c.baseUrl+":"+c.port+c.endpoint, nil) if err != nil { - return "", fmt.Errorf("error in reading request body: %v", err) - + return nil, err } - return string(body), nil -} - -func (c Client) SendRequest() (*http.Response, error) { - resp, err := c.client.Get(c.baseUrl + ":" + c.port + c.endpoint) + req.Header.Add("content-type", contentType) + resp, err := c.client.Do(req) if err != nil { return nil, fmt.Errorf("error in sending request: %v", err) } diff --git a/pkg/client_test.go b/pkg/client_test.go index 7bdac7b..6e83f0f 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -1,7 +1,122 @@ -package pkg +package pkg + import ( + "encoding/json" + "fmt" + "io" + "net/http" + "reflect" "testing" + "time" ) + +func assertEquality(t *testing.T, obj1 any, obj2 any) { + t.Helper() + if reflect.TypeOf(obj1) != reflect.TypeOf(obj2) { + t.Errorf("Error! type mismatch, wanted: %t got: %t", reflect.TypeOf(obj1), reflect.TypeOf(obj2)) + } + if !reflect.DeepEqual(obj1, obj2) { + t.Errorf("Error! values mismatch, wanted: %v got: %v", obj1, obj2) + } +} + +func readBody(t *testing.T, resp *http.Response) ([]byte, error) { + t.Helper() + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return make([]byte, 0), fmt.Errorf("error in reading request body: %v", err) + + } + return body, nil +} + func TestSendRequest(t *testing.T) { - -} \ No newline at end of file + formattedTime := time.Now().Format("2024/09/19 12:57:04") + timeJson, err := json.Marshal(formattedTime) + if err != nil { + t.Errorf("error converting to json: %v", err) + } + testcases := []struct { + name string + baseUrl string + endpoint string + port string + timeout time.Duration + expected any + contentType string + statusCode int + }{ + { + name: "correct configs, gin, plain text", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "text/plain", + timeout: time.Second, + expected: formattedTime, + statusCode: http.StatusOK, + }, + { + name: "correct configs, gin, json", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8080", + contentType: "application/json", + timeout: time.Second, + expected: timeJson, + statusCode: http.StatusOK, + }, + { + name: "correct configs, http, plain text", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8080", + contentType: "text/plain", + timeout: time.Second, + expected: formattedTime, + statusCode: http.StatusOK, + }, + { + name: "correct configs, http, json", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "application/json", + timeout: time.Second, + expected: timeJson, + statusCode: http.StatusOK, + }, + { + name: "unsupported content type", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "text/javascript; charset=utf-8", + timeout: time.Second, + expected: http.StatusText(http.StatusUnsupportedMediaType), + statusCode: http.StatusUnsupportedMediaType, + }, + } + for _, testcase := range testcases { + t.Run(testcase.name, func(t *testing.T) { + c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) + resp, err := c.SendRequest(testcase.contentType) + if err != nil { + t.Error(err) + } + resBody, err := readBody(t, resp) + if err != nil { + t.Error(err) + } + + if testcase.contentType == "application/json" { + assertEquality(t, testcase.expected, resBody) + } else { + assertEquality(t, testcase.expected, string(resBody)) + } + assertEquality(t, testcase.statusCode, resp.StatusCode) + + }) + } +} From 9c3cc7ecf671057648e10d07c550c171b51747a6 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Fri, 20 Sep 2024 23:34:42 +0300 Subject: [PATCH 09/30] feat: retry mechanism using backoff --- cmd/main.go | 2 +- go.mod | 1 + go.sum | 2 ++ pkg/client.go | 22 +++++++++++++++++++++- pkg/client_test.go | 12 ++++-------- 5 files changed, 29 insertions(+), 10 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 76d330d..8723b1c 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -79,7 +79,7 @@ func main() { baseUrl, endpoint, port := decideConfigs() c := pkg.NewClient(baseUrl, endpoint, port, time.Second) - resp, err := c.SendRequest("text/plain") + resp, err := c.RetrySendRequest("text/plain") if err != nil { log.Fatal(err) } diff --git a/go.mod b/go.mod index 60c497a..7975159 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.23.1 require ( github.com/bytedance/sonic v1.12.2 // indirect github.com/bytedance/sonic/loader v0.2.0 // indirect + github.com/cenkalti/backoff/v4 v4.3.0 github.com/cloudwego/base64x v0.1.4 // indirect github.com/cloudwego/iasm v0.2.0 // indirect github.com/gabriel-vasile/mimetype v1.4.5 // indirect diff --git a/go.sum b/go.sum index 1de6a82..b14c306 100644 --- a/go.sum +++ b/go.sum @@ -3,6 +3,8 @@ github.com/bytedance/sonic v1.12.2/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKz github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP1iU4kWM= github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= diff --git a/pkg/client.go b/pkg/client.go index 75d8bc5..bd61663 100644 --- a/pkg/client.go +++ b/pkg/client.go @@ -4,6 +4,8 @@ import ( "fmt" "net/http" "time" + + "github.com/cenkalti/backoff/v4" ) type Client struct { @@ -22,7 +24,7 @@ func NewClient(baseUrl string, endpoint string, port string, timeout time.Durati } } -func (c Client) SendRequest(contentType string) (*http.Response, error) { +func (c Client) sendRequest(contentType string) (*http.Response, error) { req, err := http.NewRequest("GET", c.baseUrl+":"+c.port+c.endpoint, nil) if err != nil { return nil, err @@ -34,3 +36,21 @@ func (c Client) SendRequest(contentType string) (*http.Response, error) { } return resp, nil } + +func (c Client) RetrySendRequest(contentType string) (*http.Response, error) { + var resp *http.Response + var err error + + retryError := backoff.RetryNotify(func() error { + resp, err = c.sendRequest(contentType) + return err + }, backoff.NewExponentialBackOff(), func(err error, d time.Duration) { + fmt.Print("Retry Happenned") + }) + + if retryError != nil { + return resp, fmt.Errorf("failed to make the request after retries: %v", err) + } else { + return resp, nil + } +} diff --git a/pkg/client_test.go b/pkg/client_test.go index 6e83f0f..79ce755 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -31,7 +31,9 @@ func readBody(t *testing.T, resp *http.Response) ([]byte, error) { return body, nil } -func TestSendRequest(t *testing.T) { + + +func TestRetrySendRequest(t *testing.T) { formattedTime := time.Now().Format("2024/09/19 12:57:04") timeJson, err := json.Marshal(formattedTime) if err != nil { @@ -42,7 +44,6 @@ func TestSendRequest(t *testing.T) { baseUrl string endpoint string port string - timeout time.Duration expected any contentType string statusCode int @@ -53,7 +54,6 @@ func TestSendRequest(t *testing.T) { endpoint: "/datetime", port: "8083", contentType: "text/plain", - timeout: time.Second, expected: formattedTime, statusCode: http.StatusOK, }, @@ -63,7 +63,6 @@ func TestSendRequest(t *testing.T) { endpoint: "/datetime", port: "8080", contentType: "application/json", - timeout: time.Second, expected: timeJson, statusCode: http.StatusOK, }, @@ -73,7 +72,6 @@ func TestSendRequest(t *testing.T) { endpoint: "/datetime", port: "8080", contentType: "text/plain", - timeout: time.Second, expected: formattedTime, statusCode: http.StatusOK, }, @@ -83,7 +81,6 @@ func TestSendRequest(t *testing.T) { endpoint: "/datetime", port: "8083", contentType: "application/json", - timeout: time.Second, expected: timeJson, statusCode: http.StatusOK, }, @@ -93,7 +90,6 @@ func TestSendRequest(t *testing.T) { endpoint: "/datetime", port: "8083", contentType: "text/javascript; charset=utf-8", - timeout: time.Second, expected: http.StatusText(http.StatusUnsupportedMediaType), statusCode: http.StatusUnsupportedMediaType, }, @@ -101,7 +97,7 @@ func TestSendRequest(t *testing.T) { for _, testcase := range testcases { t.Run(testcase.name, func(t *testing.T) { c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) - resp, err := c.SendRequest(testcase.contentType) + resp, err := c.RetrySendRequest(testcase.contentType) if err != nil { t.Error(err) } From 995f1a5c25857c4217aa4d0b8789c78432d4b2ba Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sat, 21 Sep 2024 00:16:56 +0300 Subject: [PATCH 10/30] feat: Testing the client using a mock server --- pkg/client.go | 7 ++- pkg/client_test.go | 103 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 106 insertions(+), 4 deletions(-) diff --git a/pkg/client.go b/pkg/client.go index bd61663..dbc29c8 100644 --- a/pkg/client.go +++ b/pkg/client.go @@ -41,11 +41,14 @@ func (c Client) RetrySendRequest(contentType string) (*http.Response, error) { var resp *http.Response var err error + expBackoff := backoff.NewExponentialBackOff() + expBackoff.MaxElapsedTime = 10 * time.Second + retryError := backoff.RetryNotify(func() error { resp, err = c.sendRequest(contentType) return err - }, backoff.NewExponentialBackOff(), func(err error, d time.Duration) { - fmt.Print("Retry Happenned") + }, expBackoff, func(err error, d time.Duration) { + fmt.Println("Retry Happenned") }) if retryError != nil { diff --git a/pkg/client_test.go b/pkg/client_test.go index 79ce755..8f41d3c 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -4,8 +4,11 @@ import ( "encoding/json" "fmt" "io" + "log" "net/http" + "net/http/httptest" "reflect" + "strings" "testing" "time" ) @@ -31,8 +34,6 @@ func readBody(t *testing.T, resp *http.Response) ([]byte, error) { return body, nil } - - func TestRetrySendRequest(t *testing.T) { formattedTime := time.Now().Format("2024/09/19 12:57:04") timeJson, err := json.Marshal(formattedTime) @@ -96,6 +97,7 @@ func TestRetrySendRequest(t *testing.T) { } for _, testcase := range testcases { t.Run(testcase.name, func(t *testing.T) { + c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) resp, err := c.RetrySendRequest(testcase.contentType) if err != nil { @@ -116,3 +118,100 @@ func TestRetrySendRequest(t *testing.T) { }) } } + +func TestWithMockServer(t *testing.T) { + formattedTime := time.Now().Format("2024/09/19 12:57:04") + timeJson, err := json.Marshal(formattedTime) + if err != nil { + t.Errorf("error converting to json: %v", err) + } + testcases := []struct { + name string + expected any + contentType string + statusCode int + }{ + { + name: "correct configs, gin, plain text", + contentType: "text/plain", + expected: formattedTime, + statusCode: http.StatusOK, + }, + { + name: "correct configs, gin, json", + contentType: "application/json", + expected: timeJson, + statusCode: http.StatusOK, + }, + { + name: "correct configs, http, plain text", + contentType: "text/plain", + expected: formattedTime, + statusCode: http.StatusOK, + }, + { + name: "correct configs, http, json", + contentType: "application/json", + expected: timeJson, + statusCode: http.StatusOK, + }, + { + name: "unsupported content type", + contentType: "text/javascript; charset=utf-8", + expected: http.StatusText(http.StatusUnsupportedMediaType) + "\n", + statusCode: http.StatusUnsupportedMediaType, + }, + } + for _, testcase := range testcases { + t.Run(testcase.name, func(t *testing.T) { + mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + currentTime := time.Now() + formattedTime := currentTime.Format("2024/09/19 12:57:04") + + if strings.Contains(r.Header.Get("content-type"), "text/plain") { + + w.Header().Set("Content-Type", "text/plain") + fmt.Fprint(w, formattedTime) + + } else if strings.Contains(r.Header.Get("content-type"), "application/json") { + + w.Header().Set("Content-Type", "application/json") + + timeJson, err := json.Marshal(formattedTime) + if err != nil { + log.Fatalf("error converting to json: %v", err) + } + _, err = w.Write(timeJson) + if err != nil { + log.Fatalf("error writing data to response: %v", err) + } + } else { + http.Error(w, http.StatusText(http.StatusUnsupportedMediaType), http.StatusUnsupportedMediaType) + } + })) + + defer mockServer.Close() + + parts := strings.Split(mockServer.URL, ":") + port := parts[len(parts)-1] + + c := NewClient("http://127.0.0.1", "", port, time.Second) + resp, err := c.RetrySendRequest(testcase.contentType) + if err != nil { + t.Error(err) + } + resBody, err := readBody(t, resp) + if err != nil { + t.Error(err) + } + + if testcase.contentType == "application/json" { + assertEquality(t, testcase.expected, resBody) + } else { + assertEquality(t, testcase.expected, string(resBody)) + } + assertEquality(t, testcase.statusCode, resp.StatusCode) + + }) + } +} From 5e8fef37c6eb19eeaa82e64ad35dd89f9b80f329 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sat, 21 Sep 2024 00:54:26 +0300 Subject: [PATCH 11/30] feat: logging using slog --- go.mod | 4 +++- go.sum | 2 ++ pkg/client.go | 17 ++++++++++++++--- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 7975159..0dcf7e7 100644 --- a/go.mod +++ b/go.mod @@ -2,10 +2,11 @@ module github.com/codescalersinternships/Datetime-client-RawanMostafa go 1.23.1 +require github.com/cenkalti/backoff/v4 v4.3.0 + require ( github.com/bytedance/sonic v1.12.2 // indirect github.com/bytedance/sonic/loader v0.2.0 // indirect - github.com/cenkalti/backoff/v4 v4.3.0 github.com/cloudwego/base64x v0.1.4 // indirect github.com/cloudwego/iasm v0.2.0 // indirect github.com/gabriel-vasile/mimetype v1.4.5 // indirect @@ -26,6 +27,7 @@ require ( github.com/ugorji/go/codec v1.2.12 // indirect golang.org/x/arch v0.10.0 // indirect golang.org/x/crypto v0.27.0 // indirect + golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 // indirect golang.org/x/net v0.29.0 // indirect golang.org/x/sys v0.25.0 // indirect golang.org/x/text v0.18.0 // indirect diff --git a/go.sum b/go.sum index b14c306..6783ab2 100644 --- a/go.sum +++ b/go.sum @@ -61,6 +61,8 @@ golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8= golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk= +golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY= golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/pkg/client.go b/pkg/client.go index dbc29c8..aeb6281 100644 --- a/pkg/client.go +++ b/pkg/client.go @@ -6,6 +6,7 @@ import ( "time" "github.com/cenkalti/backoff/v4" + "golang.org/x/exp/slog" ) type Client struct { @@ -16,6 +17,7 @@ type Client struct { } func NewClient(baseUrl string, endpoint string, port string, timeout time.Duration) Client { + slog.Info("New Client created! \n") return Client{ baseUrl: baseUrl, endpoint: endpoint, @@ -25,15 +27,23 @@ func NewClient(baseUrl string, endpoint string, port string, timeout time.Durati } func (c Client) sendRequest(contentType string) (*http.Response, error) { - req, err := http.NewRequest("GET", c.baseUrl+":"+c.port+c.endpoint, nil) + url := c.baseUrl + ":" + c.port + c.endpoint + + req, err := http.NewRequest("GET", url, nil) if err != nil { + slog.Error("couldn't create the request with url: %s", url) return nil, err } + req.Header.Add("content-type", contentType) resp, err := c.client.Do(req) + if err != nil { + slog.Error("couldn't send the request with url: %s", url) return nil, fmt.Errorf("error in sending request: %v", err) } + slog.Info("your request has been sent successfully!") + return resp, nil } @@ -43,15 +53,16 @@ func (c Client) RetrySendRequest(contentType string) (*http.Response, error) { expBackoff := backoff.NewExponentialBackOff() expBackoff.MaxElapsedTime = 10 * time.Second - + retryError := backoff.RetryNotify(func() error { resp, err = c.sendRequest(contentType) return err }, expBackoff, func(err error, d time.Duration) { - fmt.Println("Retry Happenned") + slog.Warn("Request failed, Retrying ...") }) if retryError != nil { + slog.Error("failed to make the request after retries: %v", err) return resp, fmt.Errorf("failed to make the request after retries: %v", err) } else { return resp, nil From aaf18217632d4f12b5db8fcd79c801bef4df3152 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sat, 21 Sep 2024 01:15:11 +0300 Subject: [PATCH 12/30] fix : time format --- pkg/client_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/client_test.go b/pkg/client_test.go index 8f41d3c..1cefcd5 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -35,7 +35,7 @@ func readBody(t *testing.T, resp *http.Response) ([]byte, error) { } func TestRetrySendRequest(t *testing.T) { - formattedTime := time.Now().Format("2024/09/19 12:57:04") + formattedTime := time.Now().Format(time.ANSIC) timeJson, err := json.Marshal(formattedTime) if err != nil { t.Errorf("error converting to json: %v", err) @@ -120,7 +120,7 @@ func TestRetrySendRequest(t *testing.T) { } func TestWithMockServer(t *testing.T) { - formattedTime := time.Now().Format("2024/09/19 12:57:04") + formattedTime := time.Now().Format(time.ANSIC) timeJson, err := json.Marshal(formattedTime) if err != nil { t.Errorf("error converting to json: %v", err) @@ -166,7 +166,7 @@ func TestWithMockServer(t *testing.T) { t.Run(testcase.name, func(t *testing.T) { mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { currentTime := time.Now() - formattedTime := currentTime.Format("2024/09/19 12:57:04") + formattedTime := currentTime.Format(time.ANSIC) if strings.Contains(r.Header.Get("content-type"), "text/plain") { From aad0fb17bd3bbd27001230e2772ad16d8efa2436 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sat, 21 Sep 2024 22:29:00 +0300 Subject: [PATCH 13/30] doc: API documentation for client functions --- pkg/client.go | 12 +++++-- pkg/client_test.go | 85 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 2 deletions(-) diff --git a/pkg/client.go b/pkg/client.go index aeb6281..1027f0b 100644 --- a/pkg/client.go +++ b/pkg/client.go @@ -1,3 +1,4 @@ +// This package implements an http client package pkg import ( @@ -9,6 +10,7 @@ import ( "golang.org/x/exp/slog" ) +// Client holds the configurations of the http client as well as the actual http.Client object type Client struct { baseUrl string endpoint string @@ -16,6 +18,7 @@ type Client struct { client http.Client } +// NewClient takes the baseUrl, endpoint, port and timeout and returns a Client object func NewClient(baseUrl string, endpoint string, port string, timeout time.Duration) Client { slog.Info("New Client created! \n") return Client{ @@ -26,7 +29,9 @@ func NewClient(baseUrl string, endpoint string, port string, timeout time.Durati } } -func (c Client) sendRequest(contentType string) (*http.Response, error) { +// SendRequest takes the wanted content type as a string, creates the request +// and adds the content-type header then send the request and returns the response and an error if exists +func (c Client) SendRequest(contentType string) (*http.Response, error) { url := c.baseUrl + ":" + c.port + c.endpoint req, err := http.NewRequest("GET", url, nil) @@ -47,6 +52,9 @@ func (c Client) sendRequest(contentType string) (*http.Response, error) { return resp, nil } +// RetrySendRequest takes the wanted content type as a string, creates and sends the request and uses the retry mechanism +// for maximum of 10 seconds before the request fails +// it then returns the response and an error if it failed to send for 10 seconds func (c Client) RetrySendRequest(contentType string) (*http.Response, error) { var resp *http.Response var err error @@ -55,7 +63,7 @@ func (c Client) RetrySendRequest(contentType string) (*http.Response, error) { expBackoff.MaxElapsedTime = 10 * time.Second retryError := backoff.RetryNotify(func() error { - resp, err = c.sendRequest(contentType) + resp, err = c.SendRequest(contentType) return err }, expBackoff, func(err error, d time.Duration) { slog.Warn("Request failed, Retrying ...") diff --git a/pkg/client_test.go b/pkg/client_test.go index 1cefcd5..c4ce39e 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -119,6 +119,91 @@ func TestRetrySendRequest(t *testing.T) { } } +func TestSendRequest(t *testing.T) { + formattedTime := time.Now().Format(time.ANSIC) + timeJson, err := json.Marshal(formattedTime) + if err != nil { + t.Errorf("error converting to json: %v", err) + } + testcases := []struct { + name string + baseUrl string + endpoint string + port string + expected any + contentType string + statusCode int + }{ + { + name: "correct configs, gin, plain text", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "text/plain", + expected: formattedTime, + statusCode: http.StatusOK, + }, + { + name: "correct configs, gin, json", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8080", + contentType: "application/json", + expected: timeJson, + statusCode: http.StatusOK, + }, + { + name: "correct configs, http, plain text", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8080", + contentType: "text/plain", + expected: formattedTime, + statusCode: http.StatusOK, + }, + { + name: "correct configs, http, json", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "application/json", + expected: timeJson, + statusCode: http.StatusOK, + }, + { + name: "unsupported content type", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "text/javascript; charset=utf-8", + expected: http.StatusText(http.StatusUnsupportedMediaType), + statusCode: http.StatusUnsupportedMediaType, + }, + } + for _, testcase := range testcases { + t.Run(testcase.name, func(t *testing.T) { + + c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) + resp, err := c.SendRequest(testcase.contentType) + if err != nil { + t.Error(err) + } + resBody, err := readBody(t, resp) + if err != nil { + t.Error(err) + } + + if testcase.contentType == "application/json" { + assertEquality(t, testcase.expected, resBody) + } else { + assertEquality(t, testcase.expected, string(resBody)) + } + assertEquality(t, testcase.statusCode, resp.StatusCode) + + }) + } +} + func TestWithMockServer(t *testing.T) { formattedTime := time.Now().Format(time.ANSIC) timeJson, err := json.Marshal(formattedTime) From b2eb27ee23b430548ed6d3827d113e5b7df42bf7 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 01:15:52 +0300 Subject: [PATCH 14/30] doc: User documentation --- README.md | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1b571a1..8d9656b 100644 --- a/README.md +++ b/README.md @@ -1 +1,68 @@ -# Datetime-client-RawanMostafa \ No newline at end of file +# Datetime Client + +This repository implements an http datetime client that accepts the response of a datetime server + +## Table of Contents + +- [Installation](#installation) +- [Usage](#usage) + + +## Installation + +1. Clone the repository + + ```bash + git clone github.com/codescalersinternships/Datetime-client-RawanMostafa/pkg + ``` + +2. Install the dependencies + ```bash + go mod download + ``` + +## Usage + + You can configure our client using different ways: + +### 1. Using flags + + ```bash + go run cmd/main.go [flags] + ``` +#### Flags: + - baseUrl=BASEURL + - port=PORT + - endpoint=ENDPOINT + +### 2. Using environment variables +This is used in case of no passed flags + + ```bash + export VARNAME="my value" + go run cmd/main.go + ``` +#### Environment variables: + - DATETIME_BASEURL + - DATETIME_PORT + - DATETIME_ENDPOINT + +### 2. Using the default configurations +Our application provides default configurations in case no flags are provided and environment variables aren't set + + ```bash + go run cmd/main.go + ``` +#### Default configs: + ```go + const defaltBaseUrl = "http://localhost" + const defaultEndpoint = "/datetime" + const defaultPort = "8083" + ``` + +#### Extra Utilities + - Check this function to get environment variables : [`decideConfigs`](https://github.com/codescalersinternships/Datetime-client-RawanMostafa/blob/9c3cc7ecf671057648e10d07c550c171b51747a6/cmd/main.go#L43-L76) + - Check this function to read the returned response body : [`readBody`](https://github.com/codescalersinternships/Datetime-client-RawanMostafa/blob/9c3cc7ecf671057648e10d07c550c171b51747a6/cmd/main.go#L19-L28) + - Check this function to get the flags : [`getFlags`](https://github.com/codescalersinternships/Datetime-client-RawanMostafa/blob/9c3cc7ecf671057648e10d07c550c171b51747a6/cmd/main.go#L29-L41) + + From 9c36bc02cc2faf2a679a87561172538e2135b7b5 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 01:51:59 +0300 Subject: [PATCH 15/30] trial commit --- pkg/client_test.go | 324 ++++++++++++++++++++++----------------------- 1 file changed, 162 insertions(+), 162 deletions(-) diff --git a/pkg/client_test.go b/pkg/client_test.go index c4ce39e..fbc93a3 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -34,175 +34,175 @@ func readBody(t *testing.T, resp *http.Response) ([]byte, error) { return body, nil } -func TestRetrySendRequest(t *testing.T) { - formattedTime := time.Now().Format(time.ANSIC) - timeJson, err := json.Marshal(formattedTime) - if err != nil { - t.Errorf("error converting to json: %v", err) - } - testcases := []struct { - name string - baseUrl string - endpoint string - port string - expected any - contentType string - statusCode int - }{ - { - name: "correct configs, gin, plain text", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "text/plain", - expected: formattedTime, - statusCode: http.StatusOK, - }, - { - name: "correct configs, gin, json", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8080", - contentType: "application/json", - expected: timeJson, - statusCode: http.StatusOK, - }, - { - name: "correct configs, http, plain text", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8080", - contentType: "text/plain", - expected: formattedTime, - statusCode: http.StatusOK, - }, - { - name: "correct configs, http, json", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "application/json", - expected: timeJson, - statusCode: http.StatusOK, - }, - { - name: "unsupported content type", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "text/javascript; charset=utf-8", - expected: http.StatusText(http.StatusUnsupportedMediaType), - statusCode: http.StatusUnsupportedMediaType, - }, - } - for _, testcase := range testcases { - t.Run(testcase.name, func(t *testing.T) { +// func TestRetrySendRequest(t *testing.T) { +// formattedTime := time.Now().Format(time.ANSIC) +// timeJson, err := json.Marshal(formattedTime) +// if err != nil { +// t.Errorf("error converting to json: %v", err) +// } +// testcases := []struct { +// name string +// baseUrl string +// endpoint string +// port string +// expected any +// contentType string +// statusCode int +// }{ +// { +// name: "correct configs, gin, plain text", +// baseUrl: "http://localhost", +// endpoint: "/datetime", +// port: "8083", +// contentType: "text/plain", +// expected: formattedTime, +// statusCode: http.StatusOK, +// }, +// { +// name: "correct configs, gin, json", +// baseUrl: "http://localhost", +// endpoint: "/datetime", +// port: "8080", +// contentType: "application/json", +// expected: timeJson, +// statusCode: http.StatusOK, +// }, +// { +// name: "correct configs, http, plain text", +// baseUrl: "http://localhost", +// endpoint: "/datetime", +// port: "8080", +// contentType: "text/plain", +// expected: formattedTime, +// statusCode: http.StatusOK, +// }, +// { +// name: "correct configs, http, json", +// baseUrl: "http://localhost", +// endpoint: "/datetime", +// port: "8083", +// contentType: "application/json", +// expected: timeJson, +// statusCode: http.StatusOK, +// }, +// { +// name: "unsupported content type", +// baseUrl: "http://localhost", +// endpoint: "/datetime", +// port: "8083", +// contentType: "text/javascript; charset=utf-8", +// expected: http.StatusText(http.StatusUnsupportedMediaType), +// statusCode: http.StatusUnsupportedMediaType, +// }, +// } +// for _, testcase := range testcases { +// t.Run(testcase.name, func(t *testing.T) { - c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) - resp, err := c.RetrySendRequest(testcase.contentType) - if err != nil { - t.Error(err) - } - resBody, err := readBody(t, resp) - if err != nil { - t.Error(err) - } +// c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) +// resp, err := c.RetrySendRequest(testcase.contentType) +// if err != nil { +// t.Error(err) +// } +// resBody, err := readBody(t, resp) +// if err != nil { +// t.Error(err) +// } - if testcase.contentType == "application/json" { - assertEquality(t, testcase.expected, resBody) - } else { - assertEquality(t, testcase.expected, string(resBody)) - } - assertEquality(t, testcase.statusCode, resp.StatusCode) +// if testcase.contentType == "application/json" { +// assertEquality(t, testcase.expected, resBody) +// } else { +// assertEquality(t, testcase.expected, string(resBody)) +// } +// assertEquality(t, testcase.statusCode, resp.StatusCode) - }) - } -} +// }) +// } +// } -func TestSendRequest(t *testing.T) { - formattedTime := time.Now().Format(time.ANSIC) - timeJson, err := json.Marshal(formattedTime) - if err != nil { - t.Errorf("error converting to json: %v", err) - } - testcases := []struct { - name string - baseUrl string - endpoint string - port string - expected any - contentType string - statusCode int - }{ - { - name: "correct configs, gin, plain text", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "text/plain", - expected: formattedTime, - statusCode: http.StatusOK, - }, - { - name: "correct configs, gin, json", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8080", - contentType: "application/json", - expected: timeJson, - statusCode: http.StatusOK, - }, - { - name: "correct configs, http, plain text", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8080", - contentType: "text/plain", - expected: formattedTime, - statusCode: http.StatusOK, - }, - { - name: "correct configs, http, json", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "application/json", - expected: timeJson, - statusCode: http.StatusOK, - }, - { - name: "unsupported content type", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "text/javascript; charset=utf-8", - expected: http.StatusText(http.StatusUnsupportedMediaType), - statusCode: http.StatusUnsupportedMediaType, - }, - } - for _, testcase := range testcases { - t.Run(testcase.name, func(t *testing.T) { +// func TestSendRequest(t *testing.T) { +// formattedTime := time.Now().Format(time.ANSIC) +// timeJson, err := json.Marshal(formattedTime) +// if err != nil { +// t.Errorf("error converting to json: %v", err) +// } +// testcases := []struct { +// name string +// baseUrl string +// endpoint string +// port string +// expected any +// contentType string +// statusCode int +// }{ +// { +// name: "correct configs, gin, plain text", +// baseUrl: "http://localhost", +// endpoint: "/datetime", +// port: "8083", +// contentType: "text/plain", +// expected: formattedTime, +// statusCode: http.StatusOK, +// }, +// { +// name: "correct configs, gin, json", +// baseUrl: "http://localhost", +// endpoint: "/datetime", +// port: "8080", +// contentType: "application/json", +// expected: timeJson, +// statusCode: http.StatusOK, +// }, +// { +// name: "correct configs, http, plain text", +// baseUrl: "http://localhost", +// endpoint: "/datetime", +// port: "8080", +// contentType: "text/plain", +// expected: formattedTime, +// statusCode: http.StatusOK, +// }, +// { +// name: "correct configs, http, json", +// baseUrl: "http://localhost", +// endpoint: "/datetime", +// port: "8083", +// contentType: "application/json", +// expected: timeJson, +// statusCode: http.StatusOK, +// }, +// { +// name: "unsupported content type", +// baseUrl: "http://localhost", +// endpoint: "/datetime", +// port: "8083", +// contentType: "text/javascript; charset=utf-8", +// expected: http.StatusText(http.StatusUnsupportedMediaType), +// statusCode: http.StatusUnsupportedMediaType, +// }, +// } +// for _, testcase := range testcases { +// t.Run(testcase.name, func(t *testing.T) { - c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) - resp, err := c.SendRequest(testcase.contentType) - if err != nil { - t.Error(err) - } - resBody, err := readBody(t, resp) - if err != nil { - t.Error(err) - } +// c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) +// resp, err := c.SendRequest(testcase.contentType) +// if err != nil { +// t.Error(err) +// } +// resBody, err := readBody(t, resp) +// if err != nil { +// t.Error(err) +// } - if testcase.contentType == "application/json" { - assertEquality(t, testcase.expected, resBody) - } else { - assertEquality(t, testcase.expected, string(resBody)) - } - assertEquality(t, testcase.statusCode, resp.StatusCode) +// if testcase.contentType == "application/json" { +// assertEquality(t, testcase.expected, resBody) +// } else { +// assertEquality(t, testcase.expected, string(resBody)) +// } +// assertEquality(t, testcase.statusCode, resp.StatusCode) - }) - } -} +// }) +// } +// } func TestWithMockServer(t *testing.T) { formattedTime := time.Now().Format(time.ANSIC) From 8677d13ccdf51c92618a2b2b6f8ca8611c0cf928 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 10:51:50 +0300 Subject: [PATCH 16/30] chore: pulling the docker image --- .github/workflows/main.yaml | 13 ++ pkg/client_test.go | 325 ++++++++++++++++++------------------ 2 files changed, 175 insertions(+), 163 deletions(-) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 63258b1..f4fcd8b 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -33,6 +33,19 @@ jobs: with: gofmt-path: './src' gofmt-flags: '-l -d' + + pull-run-images: + runs-on: ubuntu-latest + steps: + - name: pull http server + run: docker pull rawanmostafa/httpserver:latest + - name: pull gin server + run: docker pull rawanmostafa/ginserver:latest + - name: run http server + run: docker run -p 8080:8080 rawanmostafa/httpserver:latest + - name: run gin server + run: docker run -p 8083:8083 rawanmostafa/ginserver:latest + test: runs-on: ubuntu-latest steps: diff --git a/pkg/client_test.go b/pkg/client_test.go index fbc93a3..2a7d7df 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -33,176 +33,175 @@ func readBody(t *testing.T, resp *http.Response) ([]byte, error) { } return body, nil } +func TestRetrySendRequest(t *testing.T) { + formattedTime := time.Now().Format(time.ANSIC) + timeJson, err := json.Marshal(formattedTime) + if err != nil { + t.Errorf("error converting to json: %v", err) + } + testcases := []struct { + name string + baseUrl string + endpoint string + port string + expected any + contentType string + statusCode int + }{ + { + name: "correct configs, gin, plain text", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "text/plain", + expected: formattedTime, + statusCode: http.StatusOK, + }, + { + name: "correct configs, gin, json", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8080", + contentType: "application/json", + expected: timeJson, + statusCode: http.StatusOK, + }, + { + name: "correct configs, http, plain text", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8080", + contentType: "text/plain", + expected: formattedTime, + statusCode: http.StatusOK, + }, + { + name: "correct configs, http, json", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "application/json", + expected: timeJson, + statusCode: http.StatusOK, + }, + { + name: "unsupported content type", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "text/javascript; charset=utf-8", + expected: http.StatusText(http.StatusUnsupportedMediaType), + statusCode: http.StatusUnsupportedMediaType, + }, + } + for _, testcase := range testcases { + t.Run(testcase.name, func(t *testing.T) { -// func TestRetrySendRequest(t *testing.T) { -// formattedTime := time.Now().Format(time.ANSIC) -// timeJson, err := json.Marshal(formattedTime) -// if err != nil { -// t.Errorf("error converting to json: %v", err) -// } -// testcases := []struct { -// name string -// baseUrl string -// endpoint string -// port string -// expected any -// contentType string -// statusCode int -// }{ -// { -// name: "correct configs, gin, plain text", -// baseUrl: "http://localhost", -// endpoint: "/datetime", -// port: "8083", -// contentType: "text/plain", -// expected: formattedTime, -// statusCode: http.StatusOK, -// }, -// { -// name: "correct configs, gin, json", -// baseUrl: "http://localhost", -// endpoint: "/datetime", -// port: "8080", -// contentType: "application/json", -// expected: timeJson, -// statusCode: http.StatusOK, -// }, -// { -// name: "correct configs, http, plain text", -// baseUrl: "http://localhost", -// endpoint: "/datetime", -// port: "8080", -// contentType: "text/plain", -// expected: formattedTime, -// statusCode: http.StatusOK, -// }, -// { -// name: "correct configs, http, json", -// baseUrl: "http://localhost", -// endpoint: "/datetime", -// port: "8083", -// contentType: "application/json", -// expected: timeJson, -// statusCode: http.StatusOK, -// }, -// { -// name: "unsupported content type", -// baseUrl: "http://localhost", -// endpoint: "/datetime", -// port: "8083", -// contentType: "text/javascript; charset=utf-8", -// expected: http.StatusText(http.StatusUnsupportedMediaType), -// statusCode: http.StatusUnsupportedMediaType, -// }, -// } -// for _, testcase := range testcases { -// t.Run(testcase.name, func(t *testing.T) { - -// c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) -// resp, err := c.RetrySendRequest(testcase.contentType) -// if err != nil { -// t.Error(err) -// } -// resBody, err := readBody(t, resp) -// if err != nil { -// t.Error(err) -// } + c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) + resp, err := c.RetrySendRequest(testcase.contentType) + if err != nil { + t.Error(err) + } + resBody, err := readBody(t, resp) + if err != nil { + t.Error(err) + } -// if testcase.contentType == "application/json" { -// assertEquality(t, testcase.expected, resBody) -// } else { -// assertEquality(t, testcase.expected, string(resBody)) -// } -// assertEquality(t, testcase.statusCode, resp.StatusCode) + if testcase.contentType == "application/json" { + assertEquality(t, testcase.expected, resBody) + } else { + assertEquality(t, testcase.expected, string(resBody)) + } + assertEquality(t, testcase.statusCode, resp.StatusCode) -// }) -// } -// } + }) + } +} -// func TestSendRequest(t *testing.T) { -// formattedTime := time.Now().Format(time.ANSIC) -// timeJson, err := json.Marshal(formattedTime) -// if err != nil { -// t.Errorf("error converting to json: %v", err) -// } -// testcases := []struct { -// name string -// baseUrl string -// endpoint string -// port string -// expected any -// contentType string -// statusCode int -// }{ -// { -// name: "correct configs, gin, plain text", -// baseUrl: "http://localhost", -// endpoint: "/datetime", -// port: "8083", -// contentType: "text/plain", -// expected: formattedTime, -// statusCode: http.StatusOK, -// }, -// { -// name: "correct configs, gin, json", -// baseUrl: "http://localhost", -// endpoint: "/datetime", -// port: "8080", -// contentType: "application/json", -// expected: timeJson, -// statusCode: http.StatusOK, -// }, -// { -// name: "correct configs, http, plain text", -// baseUrl: "http://localhost", -// endpoint: "/datetime", -// port: "8080", -// contentType: "text/plain", -// expected: formattedTime, -// statusCode: http.StatusOK, -// }, -// { -// name: "correct configs, http, json", -// baseUrl: "http://localhost", -// endpoint: "/datetime", -// port: "8083", -// contentType: "application/json", -// expected: timeJson, -// statusCode: http.StatusOK, -// }, -// { -// name: "unsupported content type", -// baseUrl: "http://localhost", -// endpoint: "/datetime", -// port: "8083", -// contentType: "text/javascript; charset=utf-8", -// expected: http.StatusText(http.StatusUnsupportedMediaType), -// statusCode: http.StatusUnsupportedMediaType, -// }, -// } -// for _, testcase := range testcases { -// t.Run(testcase.name, func(t *testing.T) { +func TestSendRequest(t *testing.T) { + formattedTime := time.Now().Format(time.ANSIC) + timeJson, err := json.Marshal(formattedTime) + if err != nil { + t.Errorf("error converting to json: %v", err) + } + testcases := []struct { + name string + baseUrl string + endpoint string + port string + expected any + contentType string + statusCode int + }{ + { + name: "correct configs, gin, plain text", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "text/plain", + expected: formattedTime, + statusCode: http.StatusOK, + }, + { + name: "correct configs, gin, json", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8080", + contentType: "application/json", + expected: timeJson, + statusCode: http.StatusOK, + }, + { + name: "correct configs, http, plain text", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8080", + contentType: "text/plain", + expected: formattedTime, + statusCode: http.StatusOK, + }, + { + name: "correct configs, http, json", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "application/json", + expected: timeJson, + statusCode: http.StatusOK, + }, + { + name: "unsupported content type", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "text/javascript; charset=utf-8", + expected: http.StatusText(http.StatusUnsupportedMediaType), + statusCode: http.StatusUnsupportedMediaType, + }, + } + for _, testcase := range testcases { + t.Run(testcase.name, func(t *testing.T) { -// c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) -// resp, err := c.SendRequest(testcase.contentType) -// if err != nil { -// t.Error(err) -// } -// resBody, err := readBody(t, resp) -// if err != nil { -// t.Error(err) -// } + c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) + resp, err := c.SendRequest(testcase.contentType) + if err != nil { + t.Error(err) + } + resBody, err := readBody(t, resp) + if err != nil { + t.Error(err) + } -// if testcase.contentType == "application/json" { -// assertEquality(t, testcase.expected, resBody) -// } else { -// assertEquality(t, testcase.expected, string(resBody)) -// } -// assertEquality(t, testcase.statusCode, resp.StatusCode) + if testcase.contentType == "application/json" { + assertEquality(t, testcase.expected, resBody) + } else { + assertEquality(t, testcase.expected, string(resBody)) + } + assertEquality(t, testcase.statusCode, resp.StatusCode) -// }) -// } -// } + }) + } +} func TestWithMockServer(t *testing.T) { formattedTime := time.Now().Format(time.ANSIC) From 7c7aa4593979d064bc9cb55cbc8fe8b2e36d6ce8 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 11:00:02 +0300 Subject: [PATCH 17/30] chore: making the processes background processes --- .github/workflows/main.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index f4fcd8b..4e22c96 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -42,12 +42,13 @@ jobs: - name: pull gin server run: docker pull rawanmostafa/ginserver:latest - name: run http server - run: docker run -p 8080:8080 rawanmostafa/httpserver:latest + run: docker run -d -p 8080:8080 rawanmostafa/httpserver:latest - name: run gin server - run: docker run -p 8083:8083 rawanmostafa/ginserver:latest - + run: docker run -d -p 8083:8083 rawanmostafa/ginserver:latest + test: runs-on: ubuntu-latest + needs: pull-run-images steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 From bd41c6cbf650fffb76b754cdaff280a37e8da136 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 11:04:05 +0300 Subject: [PATCH 18/30] fix: edit testcases baseUrl --- pkg/client_test.go | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/pkg/client_test.go b/pkg/client_test.go index 2a7d7df..b9224c5 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -50,7 +50,7 @@ func TestRetrySendRequest(t *testing.T) { }{ { name: "correct configs, gin, plain text", - baseUrl: "http://localhost", + baseUrl: "http://ginserver", endpoint: "/datetime", port: "8083", contentType: "text/plain", @@ -59,7 +59,7 @@ func TestRetrySendRequest(t *testing.T) { }, { name: "correct configs, gin, json", - baseUrl: "http://localhost", + baseUrl: "http://ginserver", endpoint: "/datetime", port: "8080", contentType: "application/json", @@ -68,7 +68,7 @@ func TestRetrySendRequest(t *testing.T) { }, { name: "correct configs, http, plain text", - baseUrl: "http://localhost", + baseUrl: "http://httpserver", endpoint: "/datetime", port: "8080", contentType: "text/plain", @@ -77,7 +77,7 @@ func TestRetrySendRequest(t *testing.T) { }, { name: "correct configs, http, json", - baseUrl: "http://localhost", + baseUrl: "http://httpserver", endpoint: "/datetime", port: "8083", contentType: "application/json", @@ -86,7 +86,7 @@ func TestRetrySendRequest(t *testing.T) { }, { name: "unsupported content type", - baseUrl: "http://localhost", + baseUrl: "http://ginserver", endpoint: "/datetime", port: "8083", contentType: "text/javascript; charset=utf-8", @@ -135,7 +135,7 @@ func TestSendRequest(t *testing.T) { }{ { name: "correct configs, gin, plain text", - baseUrl: "http://localhost", + baseUrl: "http://ginserver", endpoint: "/datetime", port: "8083", contentType: "text/plain", @@ -144,7 +144,7 @@ func TestSendRequest(t *testing.T) { }, { name: "correct configs, gin, json", - baseUrl: "http://localhost", + baseUrl: "http://ginserver", endpoint: "/datetime", port: "8080", contentType: "application/json", @@ -153,7 +153,7 @@ func TestSendRequest(t *testing.T) { }, { name: "correct configs, http, plain text", - baseUrl: "http://localhost", + baseUrl: "http://httpserver", endpoint: "/datetime", port: "8080", contentType: "text/plain", @@ -162,7 +162,7 @@ func TestSendRequest(t *testing.T) { }, { name: "correct configs, http, json", - baseUrl: "http://localhost", + baseUrl: "http://httpserver", endpoint: "/datetime", port: "8083", contentType: "application/json", @@ -171,7 +171,7 @@ func TestSendRequest(t *testing.T) { }, { name: "unsupported content type", - baseUrl: "http://localhost", + baseUrl: "http://ginserver", endpoint: "/datetime", port: "8083", contentType: "text/javascript; charset=utf-8", From 7bb2149bb087b6531f5c6a9458cf79f7559e899d Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 11:19:11 +0300 Subject: [PATCH 19/30] fix: edit docker running command --- .github/workflows/main.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 4e22c96..f16a7c4 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -42,9 +42,9 @@ jobs: - name: pull gin server run: docker pull rawanmostafa/ginserver:latest - name: run http server - run: docker run -d -p 8080:8080 rawanmostafa/httpserver:latest + run: docker run -d --name httpserver -p 8080:8080 rawanmostafa/httpserver:latest - name: run gin server - run: docker run -d -p 8083:8083 rawanmostafa/ginserver:latest + run: docker run -d --name ginserver -p 8083:8083 rawanmostafa/ginserver:latest test: runs-on: ubuntu-latest From e61a479235e4e51484068824f190981a36c215f7 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 11:20:48 +0300 Subject: [PATCH 20/30] fix: edit test urls --- pkg/client_test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pkg/client_test.go b/pkg/client_test.go index b9224c5..e389b5c 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -135,7 +135,7 @@ func TestSendRequest(t *testing.T) { }{ { name: "correct configs, gin, plain text", - baseUrl: "http://ginserver", + baseUrl: "http://localhost", endpoint: "/datetime", port: "8083", contentType: "text/plain", @@ -144,7 +144,7 @@ func TestSendRequest(t *testing.T) { }, { name: "correct configs, gin, json", - baseUrl: "http://ginserver", + baseUrl: "http://localhost", endpoint: "/datetime", port: "8080", contentType: "application/json", @@ -153,7 +153,7 @@ func TestSendRequest(t *testing.T) { }, { name: "correct configs, http, plain text", - baseUrl: "http://httpserver", + baseUrl: "http://localhost", endpoint: "/datetime", port: "8080", contentType: "text/plain", @@ -162,7 +162,7 @@ func TestSendRequest(t *testing.T) { }, { name: "correct configs, http, json", - baseUrl: "http://httpserver", + baseUrl: "http://localhost", endpoint: "/datetime", port: "8083", contentType: "application/json", @@ -171,7 +171,7 @@ func TestSendRequest(t *testing.T) { }, { name: "unsupported content type", - baseUrl: "http://ginserver", + baseUrl: "http://localhost", endpoint: "/datetime", port: "8083", contentType: "text/javascript; charset=utf-8", From 775c9731f1a14d9e7c4e5114d68f0e321f30efd2 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 11:24:42 +0300 Subject: [PATCH 21/30] fix: edit test urls --- pkg/client_test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pkg/client_test.go b/pkg/client_test.go index e389b5c..2a7d7df 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -50,7 +50,7 @@ func TestRetrySendRequest(t *testing.T) { }{ { name: "correct configs, gin, plain text", - baseUrl: "http://ginserver", + baseUrl: "http://localhost", endpoint: "/datetime", port: "8083", contentType: "text/plain", @@ -59,7 +59,7 @@ func TestRetrySendRequest(t *testing.T) { }, { name: "correct configs, gin, json", - baseUrl: "http://ginserver", + baseUrl: "http://localhost", endpoint: "/datetime", port: "8080", contentType: "application/json", @@ -68,7 +68,7 @@ func TestRetrySendRequest(t *testing.T) { }, { name: "correct configs, http, plain text", - baseUrl: "http://httpserver", + baseUrl: "http://localhost", endpoint: "/datetime", port: "8080", contentType: "text/plain", @@ -77,7 +77,7 @@ func TestRetrySendRequest(t *testing.T) { }, { name: "correct configs, http, json", - baseUrl: "http://httpserver", + baseUrl: "http://localhost", endpoint: "/datetime", port: "8083", contentType: "application/json", @@ -86,7 +86,7 @@ func TestRetrySendRequest(t *testing.T) { }, { name: "unsupported content type", - baseUrl: "http://ginserver", + baseUrl: "http://localhost", endpoint: "/datetime", port: "8083", contentType: "text/javascript; charset=utf-8", From 5370b1db2a015e5ca439a5d04a0165ee11306ea8 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 11:32:01 +0300 Subject: [PATCH 22/30] chore: fix github workflow --- .github/workflows/main.yaml | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index f16a7c4..93e491d 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -34,25 +34,22 @@ jobs: gofmt-path: './src' gofmt-flags: '-l -d' - pull-run-images: + pull-run-test: runs-on: ubuntu-latest steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: stable - name: pull http server run: docker pull rawanmostafa/httpserver:latest - name: pull gin server run: docker pull rawanmostafa/ginserver:latest - name: run http server - run: docker run -d --name httpserver -p 8080:8080 rawanmostafa/httpserver:latest + run: docker run -d -p 8080:8080 rawanmostafa/httpserver:latest - name: run gin server - run: docker run -d --name ginserver -p 8083:8083 rawanmostafa/ginserver:latest - - test: - runs-on: ubuntu-latest - needs: pull-run-images - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 - with: - go-version: stable - - name: Test with the Go CLI + run: docker run -d -p 8083:8083 rawanmostafa/ginserver:latest + - name: test run: go test -v ./pkg + + From d5b4fd275cbfb1f256b95327dbe4dd75503dcf8e Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 16:43:32 +0300 Subject: [PATCH 23/30] fix: code dependencies, making GetTime() return time and error and isolating http logic to the client --- cmd/main.go | 23 +++---------------- pkg/client.go | 61 +++++++++++++++++++++++++++++++++------------------ 2 files changed, 43 insertions(+), 41 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 8723b1c..26019ff 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,10 +2,7 @@ package main import ( "flag" - "fmt" - "io" "log" - "net/http" "os" "time" @@ -16,16 +13,6 @@ const defaltBaseUrl = "http://localhost" const defaultEndpoint = "/datetime" const defaultPort = "8083" -func readBody(resp *http.Response) (string, error) { - defer resp.Body.Close() - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", fmt.Errorf("error in reading request body: %v", err) - - } - return string(body), nil -} - func getFlags() (string, string, string) { var port string flag.StringVar(&port, "port", "", "Specifies the port") @@ -78,14 +65,10 @@ func decideConfigs() (string, string, string) { func main() { baseUrl, endpoint, port := decideConfigs() - c := pkg.NewClient(baseUrl, endpoint, port, time.Second) - resp, err := c.RetrySendRequest("text/plain") - if err != nil { - log.Fatal(err) - } - body, err := readBody(resp) + c := pkg.NewClient(baseUrl, endpoint, port, "text/plain", time.Second) + timeNow, err := c.GetTime() if err != nil { log.Fatal(err) } - log.Println(body) + log.Println(timeNow) } diff --git a/pkg/client.go b/pkg/client.go index 1027f0b..481dc13 100644 --- a/pkg/client.go +++ b/pkg/client.go @@ -3,6 +3,7 @@ package pkg import ( "fmt" + "io" "net/http" "time" @@ -12,26 +13,26 @@ import ( // Client holds the configurations of the http client as well as the actual http.Client object type Client struct { - baseUrl string - endpoint string - port string - client http.Client + baseUrl string + endpoint string + port string + contentType string + client http.Client } -// NewClient takes the baseUrl, endpoint, port and timeout and returns a Client object -func NewClient(baseUrl string, endpoint string, port string, timeout time.Duration) Client { +// NewClient takes the baseUrl, endpoint, port, content-type and timeout and returns a Client object +func NewClient(baseUrl string, endpoint string, port string, contentType string, timeout time.Duration) Client { slog.Info("New Client created! \n") return Client{ - baseUrl: baseUrl, - endpoint: endpoint, - port: port, - client: http.Client{Timeout: timeout}, + baseUrl: baseUrl, + endpoint: endpoint, + port: port, + contentType: contentType, + client: http.Client{Timeout: timeout}, } } -// SendRequest takes the wanted content type as a string, creates the request -// and adds the content-type header then send the request and returns the response and an error if exists -func (c Client) SendRequest(contentType string) (*http.Response, error) { +func (c Client) getTime() (*http.Response, error) { url := c.baseUrl + ":" + c.port + c.endpoint req, err := http.NewRequest("GET", url, nil) @@ -40,7 +41,7 @@ func (c Client) SendRequest(contentType string) (*http.Response, error) { return nil, err } - req.Header.Add("content-type", contentType) + req.Header.Add("content-type", c.contentType) resp, err := c.client.Do(req) if err != nil { @@ -52,10 +53,20 @@ func (c Client) SendRequest(contentType string) (*http.Response, error) { return resp, nil } -// RetrySendRequest takes the wanted content type as a string, creates and sends the request and uses the retry mechanism +func readBody(resp *http.Response) (string, error) { + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("error in reading request body: %v", err) + + } + return string(body), nil +} + +// GetTime creates and sends the request and uses the retry mechanism // for maximum of 10 seconds before the request fails -// it then returns the response and an error if it failed to send for 10 seconds -func (c Client) RetrySendRequest(contentType string) (*http.Response, error) { +// it then returns the time and an error if it failed to send for 10 seconds +func (c Client) GetTime() (time.Time, error) { var resp *http.Response var err error @@ -63,7 +74,7 @@ func (c Client) RetrySendRequest(contentType string) (*http.Response, error) { expBackoff.MaxElapsedTime = 10 * time.Second retryError := backoff.RetryNotify(func() error { - resp, err = c.SendRequest(contentType) + resp, err = c.getTime() return err }, expBackoff, func(err error, d time.Duration) { slog.Warn("Request failed, Retrying ...") @@ -71,8 +82,16 @@ func (c Client) RetrySendRequest(contentType string) (*http.Response, error) { if retryError != nil { slog.Error("failed to make the request after retries: %v", err) - return resp, fmt.Errorf("failed to make the request after retries: %v", err) - } else { - return resp, nil + return time.Time{}, fmt.Errorf("failed to make the request after retries: %v", err) } + body, err := readBody(resp) + if err != nil { + return time.Time{}, err + } + timeNow, err := time.Parse(time.ANSIC, body) + if err != nil { + return time.Time{}, err + } + return timeNow, nil + } From b263040d4d28dfa4f2ca6b51ba6ebfaed0f96e1b Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Sun, 22 Sep 2024 17:29:40 +0300 Subject: [PATCH 24/30] test: fixing the tests after applying the dependency edits --- pkg/client.go | 5 + pkg/client_test.go | 279 +++++++++++++-------------------------------- 2 files changed, 86 insertions(+), 198 deletions(-) diff --git a/pkg/client.go b/pkg/client.go index 481dc13..86744e5 100644 --- a/pkg/client.go +++ b/pkg/client.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "net/http" + "strings" "time" "github.com/cenkalti/backoff/v4" @@ -88,6 +89,10 @@ func (c Client) GetTime() (time.Time, error) { if err != nil { return time.Time{}, err } + if resp.StatusCode == http.StatusUnsupportedMediaType { + return time.Time{}, fmt.Errorf("%s", http.StatusText(http.StatusUnsupportedMediaType)) + } + body = strings.Trim(body, "\"") timeNow, err := time.Parse(time.ANSIC, body) if err != nil { return time.Time{}, err diff --git a/pkg/client_test.go b/pkg/client_test.go index 2a7d7df..14dd315 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -3,7 +3,6 @@ package pkg import ( "encoding/json" "fmt" - "io" "log" "net/http" "net/http/httptest" @@ -23,227 +22,121 @@ func assertEquality(t *testing.T, obj1 any, obj2 any) { } } -func readBody(t *testing.T, resp *http.Response) ([]byte, error) { - t.Helper() - defer resp.Body.Close() - body, err := io.ReadAll(resp.Body) - if err != nil { - return make([]byte, 0), fmt.Errorf("error in reading request body: %v", err) - - } - return body, nil -} -func TestRetrySendRequest(t *testing.T) { +func TestGetTime(t *testing.T) { formattedTime := time.Now().Format(time.ANSIC) - timeJson, err := json.Marshal(formattedTime) + expectedTime, err := time.Parse(time.ANSIC, formattedTime) if err != nil { - t.Errorf("error converting to json: %v", err) + t.Errorf("error parsing the time: %v", err) } testcases := []struct { - name string - baseUrl string - endpoint string - port string - expected any - contentType string - statusCode int + name string + baseUrl string + endpoint string + port string + expectedTime time.Time + expectedError error + contentType string }{ { - name: "correct configs, gin, plain text", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "text/plain", - expected: formattedTime, - statusCode: http.StatusOK, + name: "correct configs, gin, plain text", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "text/plain", + expectedTime: expectedTime, + expectedError: nil, }, { - name: "correct configs, gin, json", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8080", - contentType: "application/json", - expected: timeJson, - statusCode: http.StatusOK, + name: "correct configs, gin, json", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8080", + contentType: "application/json", + expectedTime: expectedTime, + expectedError: nil, }, { - name: "correct configs, http, plain text", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8080", - contentType: "text/plain", - expected: formattedTime, - statusCode: http.StatusOK, + name: "correct configs, http, plain text", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8080", + contentType: "text/plain", + expectedTime: expectedTime, + expectedError: nil, }, { - name: "correct configs, http, json", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "application/json", - expected: timeJson, - statusCode: http.StatusOK, + name: "correct configs, http, json", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "application/json", + expectedTime: expectedTime, + expectedError: nil, }, { - name: "unsupported content type", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "text/javascript; charset=utf-8", - expected: http.StatusText(http.StatusUnsupportedMediaType), - statusCode: http.StatusUnsupportedMediaType, + name: "unsupported content type", + baseUrl: "http://localhost", + endpoint: "/datetime", + port: "8083", + contentType: "text/javascript; charset=utf-8", + expectedTime: time.Time{}, + expectedError: fmt.Errorf("%s", http.StatusText(http.StatusUnsupportedMediaType)), }, } for _, testcase := range testcases { t.Run(testcase.name, func(t *testing.T) { - c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) - resp, err := c.RetrySendRequest(testcase.contentType) - if err != nil { - t.Error(err) - } - resBody, err := readBody(t, resp) - if err != nil { - t.Error(err) - } + c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, testcase.contentType, time.Second) + timeNow, err := c.GetTime() - if testcase.contentType == "application/json" { - assertEquality(t, testcase.expected, resBody) - } else { - assertEquality(t, testcase.expected, string(resBody)) - } - assertEquality(t, testcase.statusCode, resp.StatusCode) + assertEquality(t, testcase.expectedTime, timeNow) + assertEquality(t, testcase.expectedError, err) }) } } -func TestSendRequest(t *testing.T) { +func TestGetTimeMock(t *testing.T) { formattedTime := time.Now().Format(time.ANSIC) - timeJson, err := json.Marshal(formattedTime) + expectedTime, err := time.Parse(time.ANSIC, formattedTime) if err != nil { - t.Errorf("error converting to json: %v", err) + t.Errorf("error parsing the time: %v", err) } testcases := []struct { - name string - baseUrl string - endpoint string - port string - expected any - contentType string - statusCode int + name string + expectedTime time.Time + expectedError error + contentType string }{ { - name: "correct configs, gin, plain text", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "text/plain", - expected: formattedTime, - statusCode: http.StatusOK, + name: "correct configs, gin, plain text", + contentType: "text/plain", + expectedTime: expectedTime, + expectedError: nil, }, { - name: "correct configs, gin, json", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8080", - contentType: "application/json", - expected: timeJson, - statusCode: http.StatusOK, + name: "correct configs, gin, json", + contentType: "application/json", + expectedTime: expectedTime, + expectedError: nil, }, { - name: "correct configs, http, plain text", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8080", - contentType: "text/plain", - expected: formattedTime, - statusCode: http.StatusOK, + name: "correct configs, http, plain text", + contentType: "text/plain", + expectedTime: expectedTime, + expectedError: nil, }, { - name: "correct configs, http, json", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "application/json", - expected: timeJson, - statusCode: http.StatusOK, + name: "correct configs, http, json", + contentType: "application/json", + expectedTime: expectedTime, + expectedError: nil, }, { - name: "unsupported content type", - baseUrl: "http://localhost", - endpoint: "/datetime", - port: "8083", - contentType: "text/javascript; charset=utf-8", - expected: http.StatusText(http.StatusUnsupportedMediaType), - statusCode: http.StatusUnsupportedMediaType, - }, - } - for _, testcase := range testcases { - t.Run(testcase.name, func(t *testing.T) { - - c := NewClient(testcase.baseUrl, testcase.endpoint, testcase.port, time.Second) - resp, err := c.SendRequest(testcase.contentType) - if err != nil { - t.Error(err) - } - resBody, err := readBody(t, resp) - if err != nil { - t.Error(err) - } - - if testcase.contentType == "application/json" { - assertEquality(t, testcase.expected, resBody) - } else { - assertEquality(t, testcase.expected, string(resBody)) - } - assertEquality(t, testcase.statusCode, resp.StatusCode) - - }) - } -} - -func TestWithMockServer(t *testing.T) { - formattedTime := time.Now().Format(time.ANSIC) - timeJson, err := json.Marshal(formattedTime) - if err != nil { - t.Errorf("error converting to json: %v", err) - } - testcases := []struct { - name string - expected any - contentType string - statusCode int - }{ - { - name: "correct configs, gin, plain text", - contentType: "text/plain", - expected: formattedTime, - statusCode: http.StatusOK, - }, - { - name: "correct configs, gin, json", - contentType: "application/json", - expected: timeJson, - statusCode: http.StatusOK, - }, - { - name: "correct configs, http, plain text", - contentType: "text/plain", - expected: formattedTime, - statusCode: http.StatusOK, - }, - { - name: "correct configs, http, json", - contentType: "application/json", - expected: timeJson, - statusCode: http.StatusOK, - }, - { - name: "unsupported content type", - contentType: "text/javascript; charset=utf-8", - expected: http.StatusText(http.StatusUnsupportedMediaType) + "\n", - statusCode: http.StatusUnsupportedMediaType, + name: "unsupported content type", + contentType: "text/javascript; charset=utf-8", + expectedTime: time.Time{}, + expectedError: fmt.Errorf("%s", http.StatusText(http.StatusUnsupportedMediaType)), }, } for _, testcase := range testcases { @@ -279,22 +172,12 @@ func TestWithMockServer(t *testing.T) { parts := strings.Split(mockServer.URL, ":") port := parts[len(parts)-1] - c := NewClient("http://127.0.0.1", "", port, time.Second) - resp, err := c.RetrySendRequest(testcase.contentType) - if err != nil { - t.Error(err) - } - resBody, err := readBody(t, resp) - if err != nil { - t.Error(err) - } + c := NewClient("http://127.0.0.1", "", port, testcase.contentType, time.Second) + timeNow, err := c.GetTime() + + assertEquality(t, testcase.expectedTime, timeNow) - if testcase.contentType == "application/json" { - assertEquality(t, testcase.expected, resBody) - } else { - assertEquality(t, testcase.expected, string(resBody)) - } - assertEquality(t, testcase.statusCode, resp.StatusCode) + assertEquality(t, testcase.expectedError, err) }) } From 010f5029185c77adb12239ffe2d270d7586331d2 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Mon, 23 Sep 2024 16:17:53 +0300 Subject: [PATCH 25/30] doc: fix the repo cloning link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8d9656b..a2e1ee9 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ This repository implements an http datetime client that accepts the response of 1. Clone the repository ```bash - git clone github.com/codescalersinternships/Datetime-client-RawanMostafa/pkg + git clone https://github.com/codescalersinternships/Datetime-client-RawanMostafa.git ``` 2. Install the dependencies From 3b426fad889397f739368791a8919f55a9a5b3b3 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Mon, 23 Sep 2024 16:22:02 +0300 Subject: [PATCH 26/30] doc: matching the user socumentation with the new code dependency changes --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index a2e1ee9..3c19a96 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,6 @@ Our application provides default configurations in case no flags are provided an #### Extra Utilities - Check this function to get environment variables : [`decideConfigs`](https://github.com/codescalersinternships/Datetime-client-RawanMostafa/blob/9c3cc7ecf671057648e10d07c550c171b51747a6/cmd/main.go#L43-L76) - - Check this function to read the returned response body : [`readBody`](https://github.com/codescalersinternships/Datetime-client-RawanMostafa/blob/9c3cc7ecf671057648e10d07c550c171b51747a6/cmd/main.go#L19-L28) - Check this function to get the flags : [`getFlags`](https://github.com/codescalersinternships/Datetime-client-RawanMostafa/blob/9c3cc7ecf671057648e10d07c550c171b51747a6/cmd/main.go#L29-L41) From 843870c8a86a6d21f9c1adf6d3174e3b9cb4213f Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Mon, 23 Sep 2024 17:15:04 +0300 Subject: [PATCH 27/30] chore: removing running on pull request --- .github/workflows/main.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 93e491d..dab08a5 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -2,7 +2,6 @@ name: Go CI on: push: - pull_request: jobs: build: From 21463a156f79fd6dcda06a0b3a3b793104dfb931 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Tue, 1 Oct 2024 23:53:41 +0300 Subject: [PATCH 28/30] fix: applying review comments: changing decideConfigs to loadConfigs, removing some if elses, checking on status code before reading the body --- cmd/main.go | 26 +++++++++----------------- pkg/client.go | 8 +++++--- 2 files changed, 14 insertions(+), 20 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 26019ff..023b93f 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -27,34 +27,26 @@ func getFlags() (string, string, string) { return baseUrl, endpoint, port } -func decideConfigs() (string, string, string) { +func loadConfigs() (string, string, string) { baseUrl, endpoint, port := getFlags() + var found bool if baseUrl == "" { - envBaseUrl, found := os.LookupEnv("DATETIME_BASEURL") - - if found { - baseUrl = envBaseUrl - } else { + baseUrl, found = os.LookupEnv("DATETIME_BASEURL") + if !found { baseUrl = defaltBaseUrl } } if endpoint == "" { - envEndpoint, found := os.LookupEnv("DATETIME_ENDPOINT") - - if found { - endpoint = envEndpoint - } else { + endpoint, found = os.LookupEnv("DATETIME_ENDPOINT") + if !found { endpoint = defaultEndpoint } } if port == "" { - envPort, found := os.LookupEnv("DATETIME_PORT") - - if found { - port = envPort - } else { + port, found = os.LookupEnv("DATETIME_PORT") + if !found { port = defaultPort } } @@ -63,7 +55,7 @@ func decideConfigs() (string, string, string) { } func main() { - baseUrl, endpoint, port := decideConfigs() + baseUrl, endpoint, port := loadConfigs() c := pkg.NewClient(baseUrl, endpoint, port, "text/plain", time.Second) timeNow, err := c.GetTime() diff --git a/pkg/client.go b/pkg/client.go index 86744e5..15518fd 100644 --- a/pkg/client.go +++ b/pkg/client.go @@ -85,13 +85,15 @@ func (c Client) GetTime() (time.Time, error) { slog.Error("failed to make the request after retries: %v", err) return time.Time{}, fmt.Errorf("failed to make the request after retries: %v", err) } + + if resp.StatusCode == http.StatusUnsupportedMediaType { + return time.Time{}, fmt.Errorf("%s", http.StatusText(http.StatusUnsupportedMediaType)) + } + body, err := readBody(resp) if err != nil { return time.Time{}, err } - if resp.StatusCode == http.StatusUnsupportedMediaType { - return time.Time{}, fmt.Errorf("%s", http.StatusText(http.StatusUnsupportedMediaType)) - } body = strings.Trim(body, "\"") timeNow, err := time.Parse(time.ANSIC, body) if err != nil { From c68bf125a0fe5b39dcd353a5b523ab0b3d92782d Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Wed, 2 Oct 2024 00:04:06 +0300 Subject: [PATCH 29/30] fix: edit test so that mock server creation is in a separate helper function --- pkg/client_test.go | 55 +++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/pkg/client_test.go b/pkg/client_test.go index 14dd315..e6b58e6 100644 --- a/pkg/client_test.go +++ b/pkg/client_test.go @@ -22,6 +22,35 @@ func assertEquality(t *testing.T, obj1 any, obj2 any) { } } +func mockServer(t *testing.T) *httptest.Server { + t.Helper() + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + currentTime := time.Now() + formattedTime := currentTime.Format(time.ANSIC) + + if strings.Contains(r.Header.Get("content-type"), "text/plain") { + + w.Header().Set("Content-Type", "text/plain") + fmt.Fprint(w, formattedTime) + + } else if strings.Contains(r.Header.Get("content-type"), "application/json") { + + w.Header().Set("Content-Type", "application/json") + + timeJson, err := json.Marshal(formattedTime) + if err != nil { + log.Fatalf("error converting to json: %v", err) + } + _, err = w.Write(timeJson) + if err != nil { + log.Fatalf("error writing data to response: %v", err) + } + } else { + http.Error(w, http.StatusText(http.StatusUnsupportedMediaType), http.StatusUnsupportedMediaType) + } + })) +} + func TestGetTime(t *testing.T) { formattedTime := time.Now().Format(time.ANSIC) expectedTime, err := time.Parse(time.ANSIC, formattedTime) @@ -141,31 +170,7 @@ func TestGetTimeMock(t *testing.T) { } for _, testcase := range testcases { t.Run(testcase.name, func(t *testing.T) { - mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - currentTime := time.Now() - formattedTime := currentTime.Format(time.ANSIC) - - if strings.Contains(r.Header.Get("content-type"), "text/plain") { - - w.Header().Set("Content-Type", "text/plain") - fmt.Fprint(w, formattedTime) - - } else if strings.Contains(r.Header.Get("content-type"), "application/json") { - - w.Header().Set("Content-Type", "application/json") - - timeJson, err := json.Marshal(formattedTime) - if err != nil { - log.Fatalf("error converting to json: %v", err) - } - _, err = w.Write(timeJson) - if err != nil { - log.Fatalf("error writing data to response: %v", err) - } - } else { - http.Error(w, http.StatusText(http.StatusUnsupportedMediaType), http.StatusUnsupportedMediaType) - } - })) + mockServer := mockServer(t) defer mockServer.Close() From 1eaf3f37c92ab7bdaf858b28532322982638b9b2 Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Wed, 2 Oct 2024 00:05:11 +0300 Subject: [PATCH 30/30] fix: review comment: increasing the MaxElapsedTime for retrial --- pkg/client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/client.go b/pkg/client.go index 15518fd..2ce3872 100644 --- a/pkg/client.go +++ b/pkg/client.go @@ -72,7 +72,7 @@ func (c Client) GetTime() (time.Time, error) { var err error expBackoff := backoff.NewExponentialBackOff() - expBackoff.MaxElapsedTime = 10 * time.Second + expBackoff.MaxElapsedTime = 30 * time.Second retryError := backoff.RetryNotify(func() error { resp, err = c.getTime()