func main() { goptions.ParseAndFail(&options) log.Printf("Connecting to mongodb on %s...", options.MongoDB) session, err := mgo.Dial(options.MongoDB.String()) if err != nil { log.Fatalf("Could not connect to %s: %s", options.MongoDB, err) } defer session.Close() db := session.DB("") // Use database specified in URL usermgr := &MongoUserManager{db.C("users")} domainmgr := &MongoDomainManager{db.C("domains")} mainrouter := mux.NewRouter() approuter := mainrouter.Host(options.Hostname).Subrouter() authrouter := approuter.PathPrefix("/auth").Subrouter() apirouter := approuter.PathPrefix("/api").Subrouter() setupAuthApps(authrouter, usermgr) setupApiApps(apirouter, domainmgr, usermgr) approuter.PathPrefix("/").Handler(http.FileServer(http.Dir(options.StaticDir))) mainrouter.PathPrefix("/").Handler(&Metapage{domainmgr}) log.Printf("Running webserver...") log.Fatalf("Failed to run webserver: %s", http.ListenAndServe(options.ListenAddress.String(), mainrouter)) }
func main() { log.Infof("starting schema...") options := struct { Driver string `goptions:"-t,--type, obligatory, description='Type of database backend'"` DSN string `goptions:"-d,--database, obligatory, description='DSN of the database backend'"` }{ // No defaults } goptions.ParseAndFail(&options) database := &db.DB{ Driver: options.Driver, DSN: options.DSN, } log.Debugf("connecting to %s database at %s", database.Driver, database.DSN) if err := database.Connect(); err != nil { log.Errorf("failed to connect to %s database at %s: %s", database.Driver, database.DSN, err) } if err := database.Setup(); err != nil { log.Errorf("failed to set up schema in %s database at %s: %s", database.Driver, database.DSN, err) return } log.Infof("deployed schema version %d", db.CurrentSchema) }
func main() { opts := &Options{} goptions.ParseAndFail(opts) // Print version number and exit if the version flag is set if opts.Version { fmt.Printf("gandi-operation v%s\n", shared.VersionNumber) return } // Get gandi client client := shared.NewGandiClient(opts.ConfigPath, opts.Testing) // Create api and operation instances api := api.New(client) operation := cli.New(api) switch opts.Verbs { case "count": operation.Count() case "list": operation.List() case "info": operation.Info(opts.Info.Operation) case "cancel": operation.Cancel(opts.Cancel.Operation) default: goptions.PrintHelp() } }
func main() { xlog.SetOutput(os.Stdout) options := struct { Topic string `goptions:"--topic, description='Topic', obligatory"` Channel string `goptions:"--channel, description='Channel', obligatory"` Lookupd string `goptions:"--lookupd, description='lookupd address', obligatory"` DSN string `goptions:"--dsn, description='MySQL DSN string', obligatory"` }{} goptions.ParseAndFail(&options) sqldb, err := sql.Open("mysql", options.DSN) if err != nil { xlog.Fatalf("sql.Open failed: %v", err) } r, err := nsq.NewReader(options.Topic, options.Channel) if err != nil { xlog.Fatalf("Opening reader for %s/%s failed: %v", options.Topic, options.Channel, err) } r.AddHandler(&Converter{DB: sqldb}) if err := r.ConnectToLookupd(options.Lookupd); err != nil { xlog.Errorf("Connecting to %s failed: %v", options.Lookupd, err) } select {} }
func main() { opts := &Options{} goptions.ParseAndFail(opts) // Print version number and exit if the version flag is set if opts.Version { fmt.Printf("gandi-domain-zone-record v%s\n", shared.VersionNumber) return } // Get gandi client client := shared.NewGandiClient(opts.ConfigPath, opts.Testing) // Create api and zone instances api := api.New(client) record := cli.New(api) switch opts.Verbs { case "count": record.Count(opts.Count.Zone, opts.Count.Version) case "list": record.List(opts.List.Zone, opts.List.Version) case "add": record.Add(opts.Add) case "delete": args := opts.Delete record.Delete(args.Zone, args.Version, args.Record) default: goptions.PrintHelp() } }
func main() { options := Options{} goptions.ParseAndFail(&options) if options.Version { fmt.Printf("github-release v%s\n", VERSION) return } if len(options.Verbs) == 0 { goptions.PrintHelp() return } VERBOSITY = len(options.Verbosity) if cmd, found := commands[options.Verbs]; found { err := cmd(options) if err != nil { if !options.Quiet { fmt.Fprintln(os.Stderr, "error:", err) } os.Exit(1) } } }
func main() { opts := &Options{} goptions.ParseAndFail(opts) // Print version number and exit if the version flag is set if opts.Version { fmt.Printf("gandi-contact v%s\n", shared.VersionNumber) return } // Get gandi client client := shared.NewGandiClient(opts.ConfigPath, opts.Testing) // Create api and cli instances api := api.New(client) contact := cli.New(api) switch opts.Verbs { case "balance": contact.Balance() case "info": contact.Info(opts.Info.Contact) case "create": contact.Create(opts.Create) case "delete": contact.Delete(opts.Delete.Contact) default: goptions.PrintHelp() } }
func init() { goptions.ParseAndFail(&options) options.OutputDir = filepath.Clean(options.OutputDir + "/iowhip_" + Timestamp) cleanupc := make(chan os.Signal) signal.Notify(cleanupc, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGINT) go func() { <-cleanupc cleanup() }() }
func main() { daddr, err := net.ResolveTCPAddr("tcp", "0.0.0.0:8080") if err != nil { log.Fatal(err) } options := struct { CityFiles []string `goptions:"-d, description='Data files to load'"` CountryNames string `goptions:"-c, description='CSV file holding country names'"` CountryShapes string `goptions:"-c, description='CSV file holding country shapes'"` Help goptions.Help `goptions:"-h, --help, description='Show this help'"` ListenAddr *net.TCPAddr `goptions:"-l, --listen, description='Listen address for HTTP server'"` }{ CountryNames: "data/countries_en.csv", CountryShapes: "data/countries.csv.bz2", ListenAddr: daddr, } goptions.ParseAndFail(&options) rt_countries = rtreego.NewTree(2, 10, 20) _, err = load_freegeodb_countries_csv(rt_countries, options.CountryShapes) if err != nil { log.Fatal(err) } countries_exp, err = load_country_names(options.CountryNames) if err != nil { log.Fatal(err) } rt = rtreego.NewTree(2, 25, 50) total_loaded_cities := 0 start_t := time.Now() for _, fname := range options.CityFiles { loaded, err := load_gisgraphy_cities_csv(rt, fname) if err != nil { log.Fatal(err) } total_loaded_cities += loaded } if total_loaded_cities > 0 { log.Println("Loaded", total_loaded_cities, "cities in", time.Now().Sub(start_t)) } log.Println("Starting HTTP server on", options.ListenAddr) http.HandleFunc("/rg/", reverseGeocodingHandler) http.HandleFunc("/gj/", serveGeoJson) http.Handle("/", http.FileServer(http.Dir("html"))) err = http.ListenAndServe(options.ListenAddr.String(), nil) if err != nil { log.Fatal(err) } }
func main() { goptions.ParseAndFail(&options) for _, m := range options.Maps { h := m.Handler http.Handle(m.Path, http.StripPrefix(m.Path, h)) } log.Printf("Starting webserver on %s...", options.Listen) err := http.ListenAndServe(options.Listen, nil) if err != nil { log.Fatalf("Could not start webserver: %s", err) } }
func main() { options := struct { Zone string `goptions:"-z, --zone, description='The zone to use'"` Token string `goptions:"--token, description='The token for the CF API'"` Email string `goptions:"--email, description='The email for the CF API'"` Help goptions.Help `goptions:"-h, --help, description='Show this help'"` goptions.Verbs Add struct { Content string `goptions:"-c, --content, obligatory, description='The content for the record'"` Name string `goptions:"-n, --name, obligatory, description='The name of the record'"` Type string `goptions:"-t, --type, description='The type of the record'"` } `goptions:"add"` Delete struct { Content string `goptions:"-c, --content, obligatory, description='The content for the record'"` SkipConfirmation bool `goptions:"-y, --yes, description='Skip confirmation'"` } `goptions:"delete"` }{ Zone: os.Getenv(CFZone), Email: os.Getenv(CFEmail), Token: os.Getenv(CFToken), } goptions.ParseAndFail(&options) opts := Options{ Email: options.Email, Token: options.Token, Zone: options.Zone, } switch { case options.Verbs == "add": opts.Content = options.Add.Content opts.Name = options.Add.Name opts.Type = options.Add.Type addRecord(&opts) case options.Verbs == "delete": opts.Content = options.Delete.Content opts.SkipConfirm = options.Delete.SkipConfirmation deleteRecords(&opts) } }
func init() { options = Options{ Env: "dev", } goptions.ParseAndFail(&options) if len(options.RootDir) > 0 { rootDir = options.RootDir } else { var err error if rootDir, err = filepath.Abs(fmt.Sprintf("%s/../resources/", filepath.Dir(os.Args[0]))); err != nil { panic(err) } options.RootDir = rootDir } configPath := fmt.Sprintf("%s/config.%s.yml", RootDir(), options.Env) config = new(Config) if cfgBytes, err := ioutil.ReadFile(configPath); err != nil { panic(err) } else { err := yaml.Unmarshal([]byte(cfgBytes), &config) if err != nil { panic(err) } } switch GetConfig().Logger.Writer { case LOGGER_WRITER_STD_OUT: logger = log.NewLogger(log.NewConcurrentWriter(os.Stdout), GetConfig().Logger.Namespace) case LOGGER_WRITER_SYSLOG: writer, _ := syslog.New(syslog.LOG_DEBUG|syslog.LOG_LOCAL0, GetConfig().Logger.Namespace) logger = log.NewLogger(log.NewConcurrentWriter(writer), GetConfig().Logger.Namespace) default: panic(errors.New(fmt.Sprintf("Unknown logger writer %s", GetConfig().Logger.Writer))) } logger.SetLevel(log.LevelAtoi[GetConfig().Logger.Level]) GetLogger().Info("Initializing application", "ver", VERSION) hasher := md5.New() hasher.Write([]byte(time.Now().Format("2006/01/02 - 15:04:05"))) instanceId = hex.EncodeToString(hasher.Sum(nil))[:5] GetLogger().Info("Initialized application", "instance ID", instanceId) }
func main() { goptions.ParseAndFail(&options) // Use current directory by default if options.RootDir == "" { options.RootDir = os.Getenv("PWD") } options.RootDir = strings.TrimRight(options.RootDir, "/") fmt.Printf("%+v\n", options) err := rename(options.RootDir, options.OldPattern, options.NewPattern) if err != nil { fmt.Println(err) } }
// Application entry point func main() { fmt.Printf("\n%s (%s) %s\n\n", APP_TITLE, APP_NAME, APP_VERSION) // Set the default values for the command line options opt = new(Options) opt.Server = DEFAULT_SERVER opt.Format = FORMAT_ALL opt.BatchSize = BATCH_SIZE goptions.ParseAndFail(opt) // Lets make sure that the users input file actually exists if _, err := os.Stat(opt.InputFile); os.IsNotExist(err) { log.Fatal("Input file does not exist") } processInputFile() }
func main() { goptions.ParseAndFail(&options) //fmt.Printf("] %#v\r\n", options) if len(options.Verbs) == 0 { fmt.Printf("%s%s \n built on %s\n\n", progname, progdesc, buildTime) goptions.PrintHelp() os.Exit(2) } VERBOSITY = len(options.Verbosity) configGet(os.Args[0]) if cmd, found := commands[options.Verbs]; found { err := cmd(options) check(err) } }
func main() { goptions.ParseAndFail(&options) if len(options.Verbs) == 0 { goptions.PrintHelp() os.Exit(2) } VERBOSITY = len(options.Verbosity) if cmd, found := commands[options.Verbs]; found { err := cmd(options) if err != nil { if !options.Quiet { fmt.Println("error:", err) } os.Exit(1) } } }
func main() { goptions.ParseAndFail(&options) goriot.SetAPIKey(options.APIKey) session, err := mgo.Dial(options.MongoDB) if err != nil { log.Fatalf("Could not connect to MongoDB: %s", err) } db = session.DB("") r := httptools.NewRegexpSwitch(map[string]http.Handler{ "/([a-z]+)/([0-9]+)/parse": httptools.L{ httptools.SilentHandler(http.HandlerFunc(whitelistHandler)), httptools.L{ httptools.SilentHandler(http.HandlerFunc(parseMatchHistory)), http.HandlerFunc(dumpMatchHistory), }, }, "/([a-z]+)/([0-9]+)": httptools.L{ httptools.SilentHandler(http.HandlerFunc(whitelistHandler)), httptools.MethodSwitch{ "POST": httptools.L{ httptools.SilentHandler(http.HandlerFunc(parseMatchHistory)), http.HandlerFunc(saveMatchHistory), }, "GET": httptools.L{ httptools.SilentHandler(http.HandlerFunc(queryMatchHistory)), http.HandlerFunc(dumpMatchHistory), }, }, }, "/.*": http.FileServer(http.Dir(options.StaticContent)), }) addr := fmt.Sprintf("0.0.0.0:%d", options.Port) log.Printf("Starting webserver on %s...", addr) if err := http.ListenAndServe(addr, r); err != nil { log.Fatalf("Could not start webserver: %s", err) } }
func main() { options := struct { Server string `goptions:"-s, --server, obligatory, description='Server to connect to'"` Password string `goptions:"-p, --password, description='Don\\'t prompt for password'"` Timeout time.Duration `goptions:"-t, --timeout, description='Connection timeout in seconds'"` Help goptions.Help `goptions:"-h, --help, description='Show this help'"` goptions.Verbs Execute struct { Command string `goptions:"--command, mutexgroup='input', description='Command to exectute', obligatory"` Script *os.File `goptions:"--script, mutexgroup='input', description='Script to exectute', rdonly"` } `goptions:"execute"` Delete struct { Path string `goptions:"-n, --name, obligatory, description='Name of the entity to be deleted'"` Force bool `goptions:"-f, --force, description='Force removal'"` } `goptions:"delete"` }{ // Default values goes here Timeout: 10 * time.Second, } goptions.ParseAndFail(&options) }
func main() { log.SetFlags(log.Ltime | log.Lshortfile) goptions.ParseAndFail(&options) //fmt.Printf("] %#v\r\n", options) if len(options.Verbs) == 0 { goptions.PrintHelp() os.Exit(2) } VERBOSITY = len(options.Verbosity) messageIds = make(map[string]bool) messageFetchMode = options.Verbs == "fetch" if cmd, found := commands[options.Verbs]; found { err := cmd(options) check(err) } }
func main() { opts := &Options{} goptions.ParseAndFail(opts) // Print version number and exit if the version flag is set if opts.Version { fmt.Printf("gandi-domain-zone v%s\n", shared.VersionNumber) return } // Get gandi client client := shared.NewGandiClient(opts.ConfigPath, opts.Testing) // Create api and zone instances api := api.New(client) zone := cli.New(api) switch opts.Verbs { case "count": zone.Count() case "list": zone.List() case "info": zone.Info(opts.Info.Zone) case "create": zone.Create(opts.Create.Name) case "delete": zone.Delete(opts.Delete.Zone) case "set": zone.Set(opts.Set.Domain, opts.Set.Zone) default: goptions.PrintHelp() } }
func main() { goptions.ParseAndFail(&options) //fmt.Printf("] %#v\r\n", options) if len(options.Verbs) == 0 { fmt.Printf("%s%s \n built on %s\n\n", progname, progdesc, buildTime) goptions.PrintHelp() os.Exit(2) } VERBOSITY = len(options.Verbosity) if cmd, found := commands[options.Verbs]; found { err := cmd() if err != nil { if !options.Quiet { fmt.Printf("%s error: %v", progname, err) } os.Exit(1) } } }
func main() { goptions.ParseAndFail(&options) session, err := mgo.Dial(options.MongoURL.String()) if err != nil { log.Fatalf("Could not connect to mongodb: %s", err) } options.ConsistencyMode.Apply(session) gfs := session.DB("").GridFS(options.CollectionPrefix) log.Printf("Starting server...") http.Handle("/", sabercat.NewCache(options.CacheTime, http.StripPrefix(options.HttpPrefix, AddPrefix(options.GridfsPrefix, http.FileServer(sabercat.GridDir{ GridFS: gfs, StripSlash: options.StripSlash, }))))) log.Fatalf("ListenAndServe: %s", http.ListenAndServe(options.Address.String(), nil)) }
func main() { goptions.ParseAndFail(&options) defer options.KeyFile.Close() pemBytes, err := ioutil.ReadAll(options.KeyFile) if err != nil { log.Fatalf("Could not read keyfile: %s", err) } token := jwt.NewToken(options.ClientId, storage.DevstorageRead_writeScope, pemBytes) // token.ClaimSet.Aud = aud c := &http.Client{} oauthToken, err := token.Assert(c) if err != nil { log.Fatalf("Could not get OAuth token: %s", err) } c.Transport = &oauth.Transport{ Token: oauthToken, } service, err := storage.New(c) if err != nil { log.Fatalf("Could not use storage API: %s", err) } objs, err := service.Objects.List(options.Bucket).Do() if err != nil { log.Fatalf("Could not list content of bucket %s: %s", options.Bucket, err) } for _, obj := range objs.Items { log.Printf("%s/%s: %s\n", options.Bucket, obj.Name, obj.SelfLink) } data := strings.NewReader("Some Data") newObj, err := service.Objects.Insert(options.Bucket, &storage.Object{}).Name("gcs-test").Media(data).Do() if err != nil { log.Fatalf("Could not create new object: %s", err) } log.Printf("Uploaded to %s", newObj.SelfLink) }
func main() { opts := &Options{} goptions.ParseAndFail(opts) // Print version number and exit if the version flag is set if opts.Version { fmt.Printf("gandi-domain v%s\n", shared.VersionNumber) return } // Get gandi client client := shared.NewGandiClient(opts.ConfigPath, opts.Testing) // Create api and cli instances api := api.New(client) domain := cli.New(api) switch opts.Verbs { case "count": domain.Count() case "list": domain.List() case "info": domain.Info(opts.Info.Domain) case "available": domain.Available(opts.Available.Domain) case "create": args := opts.Create domain.Create(args.Domain, args.Contact, args.Years) default: goptions.PrintHelp() } }
func main() { goptions.ParseAndFail(&options) output, err := os.Create(options.Output) if err != nil { log.Fatalf("Could not open output file %s: %s", options.Output, err) } defer output.Close() data := []byte(DefaultTemplate) if options.Template != nil { data, err = ioutil.ReadAll(options.Template) if err != nil { log.Fatalf("Could not read template file %s: %s", options.Template, err) } } tpl, err := template.New("nginx").Parse(string(data)) if err != nil { log.Fatalf("Could not parse template: %s", err) } containers, err := allContainers(options.Docker) if err != nil { log.Fatalf("Could not gather info about running containers: %s", err) } containers = filterContainers(containers) err = tpl.Execute(output, containers) if err != nil { log.Fatalf("Could not render template: %s", err) } if !options.DontReload { err := exec.Command("nginx", "-s", "reload").Run() if err != nil { log.Fatalf("Could not make nginx reload its configuration: %s", err) } } }
func main() { opts := &Options{} goptions.ParseAndFail(opts) // Print version number and exit if the version flag is set if opts.Version { fmt.Printf("gandi-domain-zone-version v%s\n", shared.VersionNumber) return } // Get gandi client client := shared.NewGandiClient(opts.ConfigPath, opts.Testing) // Create api and zone instances api := api.New(client) version := cli.New(api) switch opts.Verbs { case "count": version.Count(opts.Count.Zone) case "list": version.List(opts.List.Zone) case "new": version.New(opts.New.Zone, opts.New.Version) case "delete": version.Delete(opts.Delete.Zone, opts.Delete.Version) case "set": version.Set(opts.Set.Zone, opts.Set.Version) default: goptions.PrintHelp() } }
func main() { goptions.ParseAndFail(&options) if options.Lxc { log.Fatalf("LXC support not implemented yet") } pa := NewPixelApi(NewLocalContainerCreator()) r := httptools.NewRegexpSwitch(map[string]http.Handler{ "/ws": NewStreamingHandler(pa), "/templates/.*": httptools.L{ httptools.DiscardPathElements(1), templateRenderer{ Dir: options.TemplateDir, Data: TemplateData(), }, }, "/pixels(/.*)?": httptools.L{ httptools.DiscardPathElements(1), pa, }, "/handshake": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "PIXELPIXEL OK") }), "/.*": httptools.L{ http.FileServer(http.Dir(options.StaticDir)), }, }) log.Printf("Starting webserver on %s...", options.Listen) err := http.ListenAndServe(options.Listen, r) if err != nil { log.Fatalf("Could not start webserver: %s", err) } }
func main() { options := struct { Database string `goptions:"-d, --database, obligatory, description='Database to work on'"` CPUProfile string `goptions:"--cpuprofile, description='Record CPU profile for use with pprof.'"` goptions.Help `goptions:"-h, --help, description='Show this help'"` goptions.Verbs Create struct { Type string `goptions:"-t, --type, description='Create database with the specified storage type (diskv, leveldb)'"` } `goptions:"create"` Collections struct{} `goptions:"collections"` Dump struct { Collection string `goptions:"-c, --collection, obligatory, description='Collection to dump'"` } `goptions:"dump"` Insert struct { Collection string `goptions:"-c, --collection, obligatory, description='Collection to work on'"` } `goptions:"insert"` Update struct { Collection string `goptions:"-c, --collection, obligatory, description='Collection to work on'"` Id int64 `goptions:"-i, --id, obligatory, description='ID of entry to update'"` } `goptions:"update"` Delete struct { Collection string `goptions:"-c, --collection, obligatory, description='Collection to work on'"` Id int64 `goptions:"-i, --id, obligatory, description='ID of entry to delete'"` } `goptions:"delete"` Vacuum struct{} `goptions:"vacuum"` AddIndex struct { Collection string `goptions:"-c, --collection, obligatory, description='Collection to work on'"` Field string `goptions:"-f, --field, obligatory, description='Field to create index on'"` } `goptions:"addindex"` RemoveIndex struct { Collection string `goptions:"-c, --collection, obligatory, description='Collection to work on'"` Field string `goptions:"-f, --field, obligatory, description='Field to remove index from'"` } `goptions:"rmindex"` Query struct { Collection string `goptions:"-c, --collection, obligatory, description='Collection to work on'"` Expression goptions.Remainder `goptions:"description='query expression'"` } `goptions:"query"` }{} goptions.ParseAndFail(&options) if options.CPUProfile != "" { f, _ := os.Create(options.CPUProfile) pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() } if options.Verbs == "create" { typ := epos.STORAGE_AUTO switch options.Create.Type { case "leveldb": typ = epos.STORAGE_LEVELDB case "diskv": typ = epos.STORAGE_DISKV default: fmt.Fprintf(os.Stderr, "Error: invalid storage type %s.\n", options.Create.Type) } db, err := epos.OpenDatabase(options.Database, typ) if err != nil { panic(err) } db.Close() return } db, err := epos.OpenDatabase(options.Database, epos.STORAGE_AUTO) if err != nil { panic(err) } defer db.Close() switch options.Verbs { case "query": if len(options.Query.Expression) == 0 { fmt.Fprintf(os.Stderr, "Error: missing query expression") break } coll := db.Coll(options.Query.Collection) cond, err := epos.Expression([]string(options.Query.Expression)[0]) if err != nil { fmt.Fprintf(os.Stderr, "Invalid query expression: %v\n", err) break } result, err := coll.Query(cond) if err != nil { fmt.Fprintf(os.Stderr, "Query failed: %v\n", err) break } dumpData(result) case "dump": coll := db.Coll(options.Dump.Collection) result, _ := coll.QueryAll() dumpData(result) case "insert": decoder := json.NewDecoder(os.Stdin) for { var data interface{} err := decoder.Decode(&data) if err != nil { break } coll := db.Coll(options.Insert.Collection) id, err := coll.Insert(data) if err != nil { fmt.Fprintf(os.Stderr, "Error while inserting item: %v\n", err) break } fmt.Printf("ID = %d\n", id) } case "vacuum": err = db.Vacuum() if err != nil { fmt.Fprintf(os.Stderr, "Error while running vacuum: %v\n", err) os.Exit(1) } case "addindex": coll := db.Coll(options.AddIndex.Collection) if err := coll.AddIndex(options.AddIndex.Field); err != nil { fmt.Fprintf(os.Stderr, "Error while adding index: %v\n", err) } case "rmindex": coll := db.Coll(options.RemoveIndex.Collection) if err := coll.RemoveIndex(options.RemoveIndex.Field); err != nil { fmt.Fprintf(os.Stderr, "Error while removing index: %v\n", err) } case "collections": if colls, err := db.Collections(); err != nil { fmt.Fprintf(os.Stderr, "Error while fetching collections: %v\n", err) } else { for _, collname := range colls { fmt.Printf("%s\n", collname) } } case "update": decoder := json.NewDecoder(os.Stdin) var data interface{} err := decoder.Decode(&data) if err != nil { fmt.Fprintf(os.Stderr, "Error while decoding JSON document: %v\n", err) return } coll := db.Coll(options.Update.Collection) if err := coll.Update(epos.Id(options.Update.Id), data); err != nil { fmt.Fprintf(os.Stderr, "Error while updating item %d: %v\n", options.Update.Id, err) return } fmt.Printf("Item %d updated successfully.\n", options.Update.Id) case "delete": coll := db.Coll(options.Delete.Collection) if err := coll.Delete(epos.Id(options.Delete.Id)); err != nil { fmt.Fprintf(os.Stderr, "Error while deleeting item %d: %v\n", options.Delete.Id, err) return } fmt.Printf("Item %d deleted.\n", options.Delete.Id) default: fmt.Fprintf(os.Stderr, "Error: unknown operation %s\n", options.Verbs) } }
// Main defines the primary handler for transforming an application into a Sparta package. The // serviceName is used to uniquely identify your service within a region and will // be used for subsequent updates. For provisioning, ensure that you've // properly configured AWS credentials for the golang SDK. // See http://docs.aws.amazon.com/sdk-for-go/api/aws/defaults.html#DefaultChainCredentials-constant // for more information. func Main(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API) error { // We need to be able to provision an IAM role that has capabilities to // manage the other sources. That'll give us the role arn to use in the custom // resource execution. options := struct { Noop bool `goptions:"-n, --noop, description='Dry-run behavior only (do not provision stack)'"` LogLevel string `goptions:"-l, --level, description='Log level [panic, fatal, error, warn, info, debug]'"` Help goptions.Help `goptions:"-h, --help, description='Show this help'"` Verb goptions.Verbs Provision struct { S3Bucket string `goptions:"-b,--s3Bucket, description='S3 Bucket to use for Lambda source', obligatory"` } `goptions:"provision"` Delete struct { } `goptions:"delete"` Execute struct { Port int `goptions:"-p,--port, description='Alternative port for HTTP binding (default=9999)'"` SignalParentPID int `goptions:"-s,--signal, description='Process ID to signal with SIGUSR2 once ready'"` } `goptions:"execute"` Describe struct { OutputFile string `goptions:"-o,--out, description='Output file for HTML description', obligatory"` } `goptions:"describe"` Explore struct { Port int `goptions:"-p,--port, description='Alternative port for HTTP binding (default=9999)'"` } `goptions:"explore"` }{ // Default values goes here LogLevel: "info", } goptions.ParseAndFail(&options) logger, err := NewLogger(options.LogLevel) if err != nil { goptions.PrintHelp() os.Exit(1) } logger.WithFields(logrus.Fields{ "Option": options.Verb, "Version": SpartaVersion, }).Info("Welcome to Sparta") switch options.Verb { case "provision": logger.Formatter = new(logrus.TextFormatter) err = Provision(options.Noop, serviceName, serviceDescription, lambdaAWSInfos, api, options.Provision.S3Bucket, nil, logger) case "execute": logger.Formatter = new(logrus.JSONFormatter) err = Execute(lambdaAWSInfos, options.Execute.Port, options.Execute.SignalParentPID, logger) case "delete": logger.Formatter = new(logrus.TextFormatter) err = Delete(serviceName, logger) case "explore": logger.Formatter = new(logrus.TextFormatter) err = Explore(lambdaAWSInfos, options.Explore.Port, logger) case "describe": logger.Formatter = new(logrus.TextFormatter) fileWriter, err := os.Create(options.Describe.OutputFile) if err != nil { return fmt.Errorf("Failed to open %s output. Error: %s", options.Describe.OutputFile, err) } defer fileWriter.Close() err = Describe(serviceName, serviceDescription, lambdaAWSInfos, api, fileWriter, logger) default: goptions.PrintHelp() err = fmt.Errorf("Unsupported subcommand: %s", string(options.Verb)) } if nil != err { logger.Error(err) } return err }
func main() { opts := &Options{} goptions.ParseAndFail(opts) // Print version number and exit if the version flag is set if opts.Version { fmt.Printf("gdrive v%s\n", VersionNumber) return } // Get authorized drive client drive, err := gdrive.New(opts.AppPath, opts.Advanced, true) if err != nil { writeError("An error occurred creating Drive client: %v\n", err) } switch opts.Verbs { case "list": args := opts.List err = cli.List(drive, args.Query, args.TitleFilter, args.MaxResults, args.SharedStatus, args.NoHeader, args.IncludeDocs, args.SizeInBytes) case "info": err = cli.Info(drive, opts.Info.FileId, opts.Info.SizeInBytes) case "folder": args := opts.Folder err = cli.Folder(drive, args.Title, args.ParentId, args.Share) case "upload": args := opts.Upload // Set custom chunksize if given if args.ChunkSize >= (1 << 18) { googleapi.SetChunkSize(args.ChunkSize) } if args.Stdin { err = cli.UploadStdin(drive, os.Stdin, args.Title, args.ParentId, args.Share, args.MimeType, args.Convert) } else { err = cli.Upload(drive, args.File, args.Title, args.ParentId, args.Share, args.MimeType, args.Convert) } case "download": args := opts.Download if args.Pop { err = cli.DownloadLatest(drive, args.Stdout, args.Format, args.Force) } else { err = cli.Download(drive, args.FileId, args.Stdout, false, args.Format, args.Force) } case "delete": err = cli.Delete(drive, opts.Delete.FileId) case "share": err = cli.Share(drive, opts.Share.FileId) case "unshare": err = cli.Unshare(drive, opts.Unshare.FileId) case "url": if opts.Url.Download { fmt.Println(util.DownloadUrl(opts.Url.FileId)) } else { fmt.Println(util.PreviewUrl(opts.Url.FileId)) } case "quota": err = cli.Quota(drive, opts.Quota.SizeInBytes) default: goptions.PrintHelp() } if err != nil { writeError("%s", err) } }