diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml new file mode 100644 index 0000000..dab08a5 --- /dev/null +++ b/.github/workflows/main.yaml @@ -0,0 +1,54 @@ +name: Go CI + +on: + push: + +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' + + 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 -p 8080:8080 rawanmostafa/httpserver:latest + - name: run gin server + run: docker run -d -p 8083:8083 rawanmostafa/ginserver:latest + - name: test + run: go test -v ./pkg + + diff --git a/README.md b/README.md index 1b571a1..3c19a96 100644 --- a/README.md +++ b/README.md @@ -1 +1,67 @@ -# 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 https://github.com/codescalersinternships/Datetime-client-RawanMostafa.git + ``` + +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 get the flags : [`getFlags`](https://github.com/codescalersinternships/Datetime-client-RawanMostafa/blob/9c3cc7ecf671057648e10d07c550c171b51747a6/cmd/main.go#L29-L41) + + diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..023b93f --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,66 @@ +package main + +import ( + "flag" + "log" + "os" + "time" + + pkg "github.com/codescalersinternships/Datetime-client-RawanMostafa/pkg" +) + +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 baseUrl string + flag.StringVar(&baseUrl, "baseUrl", "", "Specifies the base url") + + var endpoint string + flag.StringVar(&endpoint, "endpoint", "", "Specifies the endpoint") + + flag.Parse() + return baseUrl, endpoint, port +} + +func loadConfigs() (string, string, string) { + + baseUrl, endpoint, port := getFlags() + var found bool + + if baseUrl == "" { + baseUrl, found = os.LookupEnv("DATETIME_BASEURL") + if !found { + baseUrl = defaltBaseUrl + } + } + if endpoint == "" { + endpoint, found = os.LookupEnv("DATETIME_ENDPOINT") + if !found { + endpoint = defaultEndpoint + } + } + if port == "" { + port, found = os.LookupEnv("DATETIME_PORT") + if !found { + port = defaultPort + } + } + return baseUrl, endpoint, port + +} + +func main() { + baseUrl, endpoint, port := loadConfigs() + + c := pkg.NewClient(baseUrl, endpoint, port, "text/plain", time.Second) + timeNow, err := c.GetTime() + if err != nil { + log.Fatal(err) + } + log.Println(timeNow) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..0dcf7e7 --- /dev/null +++ b/go.mod @@ -0,0 +1,36 @@ +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/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/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 + 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..6783ab2 --- /dev/null +++ b/go.sum @@ -0,0 +1,81 @@ +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/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= +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/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= +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/client.go b/pkg/client.go new file mode 100644 index 0000000..2ce3872 --- /dev/null +++ b/pkg/client.go @@ -0,0 +1,104 @@ +// This package implements an http client +package pkg + +import ( + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/cenkalti/backoff/v4" + "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 + port string + contentType string + client http.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, + contentType: contentType, + client: http.Client{Timeout: timeout}, + } +} + +func (c Client) getTime() (*http.Response, error) { + 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", c.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 +} + +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 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 + + expBackoff := backoff.NewExponentialBackOff() + expBackoff.MaxElapsedTime = 30 * time.Second + + retryError := backoff.RetryNotify(func() error { + resp, err = c.getTime() + return err + }, expBackoff, func(err error, d time.Duration) { + slog.Warn("Request failed, Retrying ...") + }) + + if retryError != nil { + 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 + } + body = strings.Trim(body, "\"") + timeNow, err := time.Parse(time.ANSIC, body) + if err != nil { + return time.Time{}, err + } + return timeNow, nil + +} diff --git a/pkg/client_test.go b/pkg/client_test.go new file mode 100644 index 0000000..e6b58e6 --- /dev/null +++ b/pkg/client_test.go @@ -0,0 +1,189 @@ +package pkg + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "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 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) + if err != nil { + t.Errorf("error parsing the time: %v", err) + } + testcases := []struct { + 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", + expectedTime: expectedTime, + expectedError: nil, + }, + { + 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", + expectedTime: expectedTime, + expectedError: nil, + }, + { + 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", + 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, testcase.contentType, time.Second) + timeNow, err := c.GetTime() + + assertEquality(t, testcase.expectedTime, timeNow) + assertEquality(t, testcase.expectedError, err) + + }) + } +} + +func TestGetTimeMock(t *testing.T) { + formattedTime := time.Now().Format(time.ANSIC) + expectedTime, err := time.Parse(time.ANSIC, formattedTime) + if err != nil { + t.Errorf("error parsing the time: %v", err) + } + testcases := []struct { + name string + expectedTime time.Time + expectedError error + contentType string + }{ + { + name: "correct configs, gin, plain text", + contentType: "text/plain", + expectedTime: expectedTime, + expectedError: nil, + }, + { + name: "correct configs, gin, json", + contentType: "application/json", + expectedTime: expectedTime, + expectedError: nil, + }, + { + name: "correct configs, http, plain text", + contentType: "text/plain", + expectedTime: expectedTime, + expectedError: nil, + }, + { + name: "correct configs, http, json", + contentType: "application/json", + expectedTime: expectedTime, + expectedError: nil, + }, + { + 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 { + t.Run(testcase.name, func(t *testing.T) { + mockServer := mockServer(t) + + defer mockServer.Close() + + parts := strings.Split(mockServer.URL, ":") + port := parts[len(parts)-1] + + c := NewClient("http://127.0.0.1", "", port, testcase.contentType, time.Second) + timeNow, err := c.GetTime() + + assertEquality(t, testcase.expectedTime, timeNow) + + assertEquality(t, testcase.expectedError, err) + + }) + } +}