main.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "net/rpc"
  7. "net/url"
  8. "os"
  9. "strings"
  10. "golang.org/x/net/context"
  11. client "github.com/cryptix/exp/todoKitSvc/client"
  12. httpclient "github.com/cryptix/exp/todoKitSvc/client/http"
  13. netrpcclient "github.com/cryptix/exp/todoKitSvc/client/netrpc"
  14. "github.com/cryptix/exp/todoKitSvc/todosvc"
  15. )
  16. func main() {
  17. fs := flag.NewFlagSet("todocli", flag.ExitOnError)
  18. var (
  19. transport = fs.String("transport", "http", "http, netrpc")
  20. httpAddr = fs.String("http.addr", "localhost:8001", "HTTP (JSON) address")
  21. netrpcAddr = fs.String("netrpc.addr", "localhost:8003", "net/rpc address")
  22. )
  23. flag.Usage = fs.Usage
  24. fs.Parse(os.Args[1:])
  25. log.SetFlags(0)
  26. log.SetOutput(os.Stdout)
  27. var e todosvc.Endpoints
  28. switch *transport {
  29. case "http":
  30. if !strings.HasPrefix(*httpAddr, "http") {
  31. *httpAddr = "http://" + *httpAddr
  32. }
  33. u, err := url.Parse(*httpAddr)
  34. if err != nil {
  35. log.Fatalf("url.Parse: %v", err)
  36. }
  37. e = httpclient.NewClient("GET", u.String())
  38. case "netrpc":
  39. client, err := rpc.DialHTTP("tcp", *netrpcAddr)
  40. if err != nil {
  41. log.Fatalf("rpc.DialHTTP: %v", err)
  42. }
  43. e = netrpcclient.NewClient(client)
  44. default:
  45. log.Fatalf("unsupported transport %q", *transport)
  46. }
  47. c := client.NewClient(e)
  48. ctx := context.Background()
  49. args := fs.Args()
  50. if len(args) < 1 {
  51. fmt.Fprintln(os.Stderr, "usage: todocli <add|list> ...")
  52. os.Exit(1)
  53. }
  54. switch args[0] {
  55. case "add":
  56. log.Println("Adding")
  57. id, err := c.Add(ctx, args[1])
  58. check(err)
  59. log.Println("Added as", id)
  60. case "list":
  61. log.Println("Listing")
  62. list, err := c.List(ctx)
  63. check(err)
  64. fmt.Println(list)
  65. default:
  66. log.Fatalf("unsupported command: %s", args[0])
  67. }
  68. }
  69. func check(err error) {
  70. if err != nil {
  71. log.Fatal(err)
  72. }
  73. }