Created
February 18, 2020 16:53
-
-
Save zer0tonin/19eb6cf6e1772cc079c9ae81c07eab75 to your computer and use it in GitHub Desktop.
Dumb mutex stuff
This file contains hidden or 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 ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"sync" | |
"time" | |
) | |
type WorldTimeAPIResponse struct { | |
UTCDateTime string `json:"utc_datetime"` | |
DateTime string `json:"datetime"` | |
TimeZone string `json:"timezone"` | |
} | |
type WorldTimeAPIFetcher struct { | |
state *WorldTimeAPIResponse | |
mutex *sync.Mutex | |
} | |
func NewWorldTimeAPIFetcher() *WorldTimeAPIFetcher { | |
return &WorldTimeAPIFetcher{ | |
mutex: &sync.Mutex{}, | |
} | |
} | |
func (w *WorldTimeAPIFetcher) Fetch() { | |
resp, err := http.Get("http://worldtimeapi.org/api/timezone/Europe/Paris") | |
if err != nil { | |
fmt.Println("An error occured " + err.Error()) | |
return | |
} | |
defer resp.Body.Close() | |
body, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
fmt.Println("An error occured " + err.Error()) | |
return | |
} | |
worldTimeAPIResponse := new(WorldTimeAPIResponse) | |
err = json.Unmarshal(body, worldTimeAPIResponse) | |
if err != nil { | |
fmt.Println("An error occured " + err.Error()) | |
return | |
} | |
w.mutex.Lock() | |
w.state = worldTimeAPIResponse | |
w.mutex.Unlock() | |
} | |
func (w *WorldTimeAPIFetcher) Print() { | |
w.mutex.Lock() | |
if w.state != nil { | |
fmt.Println(w.state.DateTime) | |
} | |
w.mutex.Unlock() | |
} | |
func FetchLoop(w *WorldTimeAPIFetcher) { | |
for true { | |
w.Fetch() | |
time.Sleep(time.Duration(1000000000)) | |
} | |
} | |
func PrintLoop(w *WorldTimeAPIFetcher) { | |
for true { | |
w.Print() | |
time.Sleep(time.Duration(1000000)) | |
} | |
} | |
func main() { | |
w := NewWorldTimeAPIFetcher() | |
go FetchLoop(w) | |
PrintLoop(w) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment