소스 검색

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