github.com/circl-dev/go-swagger@v0.31.0/examples/stream-server/elapsed_client.go (about) 1 // +build ignore 2 3 package main 4 5 import ( 6 "bufio" 7 "context" 8 "encoding/json" 9 "io" 10 "log" 11 "os" 12 "sync" 13 "time" 14 15 "github.com/circl-dev/go-swagger/examples/stream-server/client" 16 "github.com/circl-dev/go-swagger/examples/stream-server/client/operations" 17 "github.com/circl-dev/go-swagger/examples/stream-server/models" 18 "github.com/circl-dev/runtime" 19 httptransport "github.com/circl-dev/runtime/client" 20 "github.com/go-openapi/swag" 21 ) 22 23 func main() { 24 25 n := int64(5) 26 if len(os.Args) > 1 { 27 var err error 28 n, err = swag.ConvertInt64(os.Args[1]) 29 if err != nil { 30 log.Fatalln("pass an integer as argument") 31 return 32 } 33 } 34 log.Printf("asking server for countdown timings: %d", n) 35 36 if err := ask(n); err != nil { 37 log.Printf("failure: %v", err) 38 } 39 } 40 41 func ask(n int64) error { 42 customized := httptransport.New("localhost:8000", "/", []string{"http"}) 43 customized.Consumers[runtime.JSONMime] = runtime.ByteStreamConsumer() 44 45 countdowns := client.New(customized, nil) 46 47 reader, writer := io.Pipe() 48 49 scanner := bufio.NewScanner(reader) 50 51 ctx, cancel := context.WithCancel(context.Background()) 52 53 // consumes asynchronously the response buffer 54 var wg sync.WaitGroup 55 56 wg.Add(1) 57 go func(wg *sync.WaitGroup) { 58 defer wg.Done() 59 defer cancel() 60 61 // read response items line by line 62 for scanner.Scan() { 63 // each response item is JSON 64 txt := scanner.Text() 65 log.Printf("received countdown mark - raw: %s", txt) 66 67 var mark models.Mark 68 69 err := json.Unmarshal([]byte(txt), &mark) 70 if err != nil { 71 log.Printf("unmarshal error: %v", err) 72 return 73 } 74 75 log.Printf("received countdown mark - remaining: %d", swag.Int64Value(mark.Remains)) 76 } 77 78 if err := scanner.Err(); err != nil { 79 log.Printf("scanner err: %v", err) 80 } 81 82 log.Println("EOF") 83 }(&wg) 84 85 queryCtx, timedOut := context.WithTimeout(ctx, 7*time.Second) 86 defer timedOut() 87 88 elapsed := operations.NewElapseParamsWithContext(queryCtx).WithLength(n) 89 90 _, err := countdowns.Operations.Elapse(elapsed, writer) 91 92 if err == nil { 93 log.Printf("response complete") 94 } else { 95 log.Printf("got an error") 96 } 97 98 _ = writer.Close() 99 100 wg.Wait() 101 102 return err 103 }