Created
March 18, 2019 16:17
-
-
Save kmassada/db87fc6f06c2b9267a18ea8173600c7c to your computer and use it in GitHub Desktop.
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 ( | |
"errors" | |
"flag" | |
"fmt" | |
"strings" | |
"time" | |
) | |
// Example: A user-defined flag type, a slice of durations. | |
type interval []time.Duration | |
// String is the method to format the flag's value, part of the flag.Value interface. | |
// The String method's output will be used in diagnostics. | |
func (i *interval) String() string { | |
return fmt.Sprint(*i) | |
} | |
// Set is the method to set the flag value, part of the flag.Value interface. | |
// Set's argument is a string to be parsed to set the flag. | |
// It's a comma-separated list, so we split it. | |
func (i *interval) Set(value string) error { | |
// If we wanted to allow the flag to be set multiple times, | |
// accumulating values, we would delete this if statement. | |
// That would permit usages such as | |
// -deltaT 10s -deltaT 15s | |
// and other combinations. | |
if len(*i) > 0 { | |
return errors.New("interval flag already set") | |
} | |
for _, dt := range strings.Split(value, ",") { | |
duration, err := time.ParseDuration(dt) | |
if err != nil { | |
return err | |
} | |
*i = append(*i, duration) | |
} | |
return nil | |
} | |
// Calculate the duration by obtaining the min of slice | |
// and the min of the slice, and of course computing their diff | |
func (i *interval) calculateDuration() time.Duration { | |
var max, min time.Duration | |
min = (*i)[0] | |
for _, value := range *i { | |
if max < value { | |
max = value | |
} | |
if min > value { | |
min = value | |
} | |
} | |
return max - min | |
} | |
// Define a flag to accumulate durations. Because it has a special type, | |
// we need to use the Var function and therefore create the flag during | |
// init. | |
var intervalFlag interval | |
func init() { | |
// Tie the command-line flag to the intervalFlag variable and | |
// set a usage message. | |
flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events") | |
} | |
func main() { | |
flag.Parse() | |
fmt.Println(intervalFlag.calculateDuration()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment