| OLD | NEW |
| (Empty) |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 package main | |
| 6 | |
| 7 import ( | |
| 8 "errors" | |
| 9 "flag" | |
| 10 "net/http" | |
| 11 "os" | |
| 12 | |
| 13 "github.com/luci/luci-go/appengine/apigen_examples/dumb_counter/api/dumb
_counter/v1" | |
| 14 log "github.com/luci/luci-go/common/logging" | |
| 15 "github.com/luci/luci-go/common/logging/gologger" | |
| 16 "github.com/luci/luci-go/common/testing/httpmitm" | |
| 17 "golang.org/x/net/context" | |
| 18 ) | |
| 19 | |
| 20 var ( | |
| 21 errOperationFailed = errors.New("operation failed") | |
| 22 | |
| 23 defaultBasePath string | |
| 24 ) | |
| 25 | |
| 26 type application struct { | |
| 27 basePath string | |
| 28 } | |
| 29 | |
| 30 func init() { | |
| 31 // Determine the default base path by instantiating a default client. | |
| 32 svc, _ := dumb_counter.New(http.DefaultClient) | |
| 33 defaultBasePath = svc.BasePath | |
| 34 } | |
| 35 | |
| 36 func (a *application) addToFlagSet(fs *flag.FlagSet) { | |
| 37 fs.StringVar(&a.basePath, "base-path", defaultBasePath, | |
| 38 "The URL to the base service. Leave black for default.") | |
| 39 } | |
| 40 | |
| 41 func (a *application) run(c context.Context) error { | |
| 42 client := http.Client{} | |
| 43 client.Transport = &httpmitm.Transport{ | |
| 44 RoundTripper: http.DefaultTransport, | |
| 45 Callback: func(o httpmitm.Origin, data []byte, err error) { | |
| 46 log.Fields{ | |
| 47 log.ErrorKey: err, | |
| 48 "origin": o, | |
| 49 }.Infof(c, "HTTP:\n%s", string(data)) | |
| 50 }, | |
| 51 } | |
| 52 svc, err := dumb_counter.New(&client) | |
| 53 if err != nil { | |
| 54 log.Fields{ | |
| 55 log.ErrorKey: err, | |
| 56 }.Errorf(c, "Failed to create client.") | |
| 57 return errOperationFailed | |
| 58 } | |
| 59 svc.BasePath = a.basePath | |
| 60 | |
| 61 resp, err := svc.Add("test", &dumb_counter.AddReq{Delta: 1}).Context(c).
Do() | |
| 62 if err != nil { | |
| 63 log.Fields{ | |
| 64 log.ErrorKey: err, | |
| 65 }.Errorf(c, "Failed to perform add operation.") | |
| 66 return errOperationFailed | |
| 67 } | |
| 68 | |
| 69 log.Fields{ | |
| 70 "current": resp.Cur, | |
| 71 "prev": resp.Prev, | |
| 72 }.Infof(c, "Add operation successful!") | |
| 73 return nil | |
| 74 } | |
| 75 | |
| 76 func main() { | |
| 77 a := application{} | |
| 78 lc := log.Config{ | |
| 79 Level: log.Warning, | |
| 80 } | |
| 81 | |
| 82 fs := flag.CommandLine | |
| 83 a.addToFlagSet(fs) | |
| 84 lc.AddFlags(fs) | |
| 85 fs.Parse(os.Args[1:]) | |
| 86 | |
| 87 ctx := context.Background() | |
| 88 ctx = lc.Set(gologger.Use(ctx)) | |
| 89 | |
| 90 if err := a.run(ctx); err != nil { | |
| 91 log.Fields{ | |
| 92 log.ErrorKey: err, | |
| 93 }.Errorf(ctx, "Error during execution.") | |
| 94 os.Exit(1) | |
| 95 } | |
| 96 } | |
| OLD | NEW |