Преглед на файлове

automatically parse the sleep duration in toml

Tobias Begalke преди 7 години
родител
ревизия
2787193bb0
променени са 1 файла, в които са добавени 16 реда и са изтрити 6 реда
  1. 16 6
      main.go

+ 16 - 6
main.go

@@ -61,12 +61,22 @@ type Config struct {
 	Promiscuous           bool
 	NatsURL               string
 	NatsQueue             string
-	SleepFor              time.Duration
+	SleepFor              duration
 	RequestsFile          string
 	UseXForwardedAsSource bool
 	Quiet                 bool
 }
 
+type duration struct {
+	time.Duration
+}
+
+func (d *duration) UnmarshalText(text []byte) error {
+	var err error
+	d.Duration, err = time.ParseDuration(string(text))
+	return err
+}
+
 func (c Config) print() {
 	fmt.Printf("Live:                  %t\n", c.Live)
 	fmt.Printf("Interface:             %s\n", c.Interface)
@@ -286,7 +296,7 @@ func replayFile() {
 		c.Comma = ' '
 
 		for {
-			if config.SleepFor > time.Nanosecond {
+			if config.SleepFor.Duration > time.Nanosecond {
 				startTs = time.Now()
 			}
 
@@ -311,10 +321,10 @@ func replayFile() {
 			natsEC.Publish(config.NatsQueue, &req)
 
 			count++
-			if config.SleepFor >= time.Nanosecond {
+			if config.SleepFor.Duration >= time.Nanosecond {
 				endTs = time.Now()
-				if endTs.Before(startTs.Add(config.SleepFor)) {
-					time.Sleep(config.SleepFor - endTs.Sub(startTs))
+				if endTs.Before(startTs.Add(config.SleepFor.Duration)) {
+					time.Sleep(config.SleepFor.Duration - endTs.Sub(startTs))
 				}
 			}
 		}
@@ -331,7 +341,7 @@ func loadConfig() {
 	config.Promiscuous = *promiscuous
 	config.NatsURL = *natsURL
 	config.NatsQueue = *natsQueue
-	config.SleepFor = *sleepFor
+	config.SleepFor.Duration = *sleepFor
 	config.RequestsFile = *requestsFile
 	config.UseXForwardedAsSource = *useXForwardedAsSource
 	config.Quiet = *beQuiet