Last active
November 18, 2017 02:10
-
-
Save gerep/40644b2a6512b3cce31cf596b0fd109c 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
// Execution example: TZ=US/Eastern ./clock2 --port 8000 | |
package main | |
import ( | |
"flag" | |
"io" | |
"log" | |
"net" | |
"os" | |
"time" | |
) | |
func main() { | |
port := flag.String("port", "8000", "port") | |
flag.Parse() | |
listener, err := net.Listen("tcp", "localhost:"+*port) | |
if err != nil { | |
log.Fatal(err) | |
} | |
for { | |
conn, err := listener.Accept() | |
if err != nil { | |
log.Print(err) | |
continue | |
} | |
// Runs the handler as a goroutine to allow simultaneous clients. | |
go handleConn(conn, os.Getenv("TZ")) | |
} | |
} | |
func handleConn(c net.Conn, tz string) { | |
defer c.Close() | |
// Set the time that will be used. | |
loc, err := time.LoadLocation(tz) | |
if err != nil { | |
log.Fatal(err) | |
} | |
for { | |
// Writes to the connection the time based on the timezone, with In(loc). | |
_, err := io.WriteString(c, time.Now().In(loc).Format("15:04:05\n")) | |
if err != nil { | |
return | |
} | |
time.Sleep(1 * time.Second) | |
} | |
} |
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 ( | |
"bufio" | |
"fmt" | |
"io" | |
"log" | |
"net" | |
"os" | |
"strings" | |
"time" | |
) | |
// Zone will store each timezone informed as argument to the binary. | |
type zone struct { | |
name, server string | |
} | |
func main() { | |
zones := []zone{} | |
for _, e := range os.Args[1:] { | |
v := strings.Split(e, "=") | |
zones = append(zones, zone{v[0], v[1]}) | |
} | |
// For each zone, start a net.Dial to receive data from the server. | |
for _, v := range zones { | |
conn, err := net.Dial("tcp", v.server) | |
defer conn.Close() | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Start the copy process as a goroutine to show all available zones. | |
go mustCopy(os.Stdout, conn, v.name) | |
} | |
// Force main to wait. | |
time.Sleep(5 * time.Second) | |
} | |
// Reads the information being sent in the connection via the src parameter | |
// and print to dst the name and hour returned by the server: somewhere: 00:00:00 | |
func mustCopy(dst io.Writer, src io.Reader, n string) { | |
s := bufio.NewScanner(src) | |
for s.Scan() { | |
fmt.Fprintf(dst, "%s: %s\n", n, s.Text()) | |
} | |
if s.Err() != nil { | |
fmt.Printf("error reading from %s: %v", n, s.Err()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment