Last active
April 22, 2022 08:30
-
-
Save owulveryck/47f8bcc2dc638de6e1b902a80a363aa2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cmd | |
import ( | |
"encoding/json" | |
"errors" | |
"fmt" | |
"net/http" | |
) | |
type TimeTraveler struct { | |
*http.Client | |
Source string | |
} | |
func NewDefaultTimeTraveler() *TimeTraveler { | |
return &TimeTraveler{ | |
Client: http.DefaultClient, | |
Source: "https://worldtimeapi.org/api/timezone/Europe/Paris", | |
} | |
} | |
func (t *TimeTraveler) GetCurrentTime() (*TimeResponse, error) { | |
res, err := t.Get(t.Source) | |
if err != nil || res == nil { | |
return nil, err | |
} | |
defer res.Body.Close() | |
if res.StatusCode != http.StatusOK { | |
return nil, errors.New(res.Status) | |
} | |
dec := json.NewDecoder(res.Body) | |
var tr TimeResponse | |
err = dec.Decode(&tr) | |
if err != nil { | |
return nil, err | |
} | |
return &tr, nil | |
} | |
func ComputeWeeksLeftBeforeNextYear(t *TimeTraveler) (weeksLeft string, err error) { | |
tr, err := t.GetCurrentTime() | |
if err != nil { | |
return "Read failed", err | |
} | |
return fmt.Sprintf("~ %d weeks left this year", 52-tr.WeekNumber), err | |
} | |
type TimeResponse struct { | |
WeekNumber int `json:"week_number"` | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cmd | |
import ( | |
"encoding/json" | |
"net/http" | |
"net/http/httptest" | |
"testing" | |
) | |
func TestComputeWeeksLeftBeforeNextYear(t *testing.T) { | |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
enc := json.NewEncoder(w) | |
enc.Encode(&TimeResponse{ | |
WeekNumber: 52 - 46, | |
}) | |
})) | |
defer ts.Close() | |
weeksLeft, _ := ComputeWeeksLeftBeforeNextYear(&TimeTraveler{ | |
Client: http.DefaultClient, | |
Source: ts.URL, | |
}) | |
if weeksLeft != "~ 46 weeks left this year" { | |
t.Errorf("\nexpected: [~ 46 weeks left this year]\nreceived: [%s]", weeksLeft) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"main/cmd" | |
"os" | |
) | |
func main() { | |
weeksLeft, err := cmd.ComputeWeeksLeftBeforeNextYear(cmd.NewDefaultTimeTraveler()) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("%s", weeksLeft) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment