github.com/machinebox/remoto@v0.1.2-0.20191024144331-eff21a7d321f/examples/files/client/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"log"
     8  	"net/http"
     9  	"os"
    10  	"os/signal"
    11  	"path/filepath"
    12  
    13  	"github.com/machinebox/remoto/examples/files/client/files"
    14  	"github.com/pkg/errors"
    15  )
    16  
    17  func main() {
    18  	if err := run(); err != nil {
    19  		fmt.Fprintf(os.Stderr, "%v\n", err)
    20  		os.Exit(1)
    21  	}
    22  }
    23  
    24  func run() error {
    25  	// see https://medium.com/@matryer/make-ctrl-c-cancel-the-context-context-bd006a8ad6ff
    26  	ctx := context.Background()
    27  	ctx, cancel := context.WithCancel(ctx)
    28  	c := make(chan os.Signal, 1)
    29  	signal.Notify(c, os.Interrupt)
    30  	defer func() {
    31  		signal.Stop(c)
    32  		cancel()
    33  	}()
    34  	go func() {
    35  		select {
    36  		case <-c:
    37  			cancel()
    38  		case <-ctx.Done():
    39  		}
    40  	}()
    41  	if len(os.Args) < 2 {
    42  		return errors.New("usage: client <image-file>")
    43  	}
    44  	inputFile := os.Args[1]
    45  	f, err := os.Open(inputFile)
    46  	if err != nil {
    47  		return err
    48  	}
    49  	defer f.Close()
    50  	images := files.NewImagesClient("http://localhost:8080", http.DefaultClient)
    51  	request := &files.FlipRequest{}
    52  	ctx = request.SetImage(ctx, filepath.Base(inputFile), f)
    53  	resp, err := images.Flip(ctx, request)
    54  	if err != nil {
    55  		return errors.Wrap(err, "images.Flip")
    56  	}
    57  	defer resp.Close()
    58  	outfile := filepath.Join(filepath.Dir(inputFile), "flipped.jpg")
    59  	out, err := os.Create(outfile)
    60  	if err != nil {
    61  		return err
    62  	}
    63  	defer out.Close()
    64  	if _, err := io.Copy(out, resp); err != nil {
    65  		return errors.Wrap(err, "writing file")
    66  	}
    67  	log.Println("flipped image saved to", outfile)
    68  	return nil
    69  }