コード例 #1
0
ファイル: main.go プロジェクト: GeenPeil/teken
func main() {

	flags := &server.Options{}

	parser := goflags.NewParser(flags, goflags.HelpFlag|goflags.PrintErrors)

	// parse flags
	args, err := parser.Parse()
	if err != nil {
		// assert the err to be a flags.Error
		flagError, ok := err.(*goflags.Error)
		if !ok {
			// not a flags error
			os.Exit(1)
		}
		if flagError.Type == goflags.ErrHelp {
			// exitcode 0 when user asked for help
			os.Exit(0)
		}
		if flagError.Type == goflags.ErrUnknownFlag {
			fmt.Println("run with --help to view available options")
		}
		os.Exit(1)
	}

	// error on left-over arguments
	if len(args) > 0 {
		fmt.Printf("unexpected arguments: %s\n", args)
		os.Exit(0)
	}

	s := server.New(flags)
	s.Run(nil)
}
コード例 #2
0
ファイル: main.go プロジェクト: jak-atx/vic
func main() {
	swaggerSpec, err := spec.New(restapi.SwaggerJSON, "")
	if err != nil {
		log.Fatalln(err)
	}

	api := operations.NewPetstoreAPI(swaggerSpec)
	server := restapi.NewServer(api)
	defer server.Shutdown()

	parser := flags.NewParser(server, flags.Default)
	parser.ShortDescription = `Swagger Petstore`
	parser.LongDescription = `This is a sample server Petstore server.

[Learn about Swagger](http://swagger.wordnik.com) or join the IRC channel '#swagger' on irc.freenode.net.

For this sample, you can use the api key 'special-key' to test the authorization filters
`

	for _, optsGroup := range api.CommandLineOptionsGroups {
		parser.AddGroup(optsGroup.ShortDescription, optsGroup.LongDescription, optsGroup.Options)
	}

	if _, err := parser.Parse(); err != nil {
		log.Fatalln(err)
	}

	if err := server.Serve(); err != nil {
		log.Fatalln(err)
	}
}
コード例 #3
0
ファイル: attach.go プロジェクト: juito/hyper
func (cli *HyperClient) HyperCmdAttach(args ...string) error {
	var parser = gflag.NewParser(nil, gflag.Default)
	parser.Usage = "attach CONTAINER\n\nAttach to the tty of a specified container in a pod"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) == 0 {
		return fmt.Errorf("Can not accept the 'attach' command without Container ID!")
	}
	var (
		podId       = args[0]
		containerId = args[0]
		tty         bool
	)

	if strings.Contains(podId, "pod-") {
		pod, err := cli.client.GetPodInfo(podId)
		if err != nil {
			return err
		}

		if len(pod.Spec.Containers) == 0 {
			return fmt.Errorf("failed to get container from %s", podId)
		}

		c := pod.Spec.Containers[0]

		containerId = c.ContainerID
		tty = c.Tty
	} else {
		c, err := cli.client.GetContainerInfo(containerId)
		if err != nil {
			return err
		}

		podId = c.PodID
		containerId = c.Container.ContainerID
		tty = c.Container.Tty
	}

	if tty {
		oldState, err := term.SetRawTerminal(cli.inFd)
		if err != nil {
			return err
		}
		defer term.RestoreTerminal(cli.inFd, oldState)
		cli.monitorTtySize(containerId, "")
	}

	if err := cli.client.Attach(containerId, tty, cli.in, cli.out, cli.err); err != nil {
		return err
	}

	return cli.client.GetExitCode(containerId, "")
}
コード例 #4
0
ファイル: pull.go プロジェクト: huangqg/hyper
func (cli *HyperClient) HyperCmdPull(args ...string) error {
	// we need to get the image name which will be used to create a container
	if len(args) == 0 {
		return fmt.Errorf("\"pull\" requires a minimum of 1 argument, please provide the image name.")
	}
	var parser = gflag.NewParser(nil, gflag.Default)
	parser.Usage = "pull IMAGE\n\npull an image from a Docker registry server"
	args, err := parser.Parse()
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	imageName := args[1]
	v := url.Values{}
	v.Set("imageName", imageName)
	err = cli.stream("POST", "/image/create?"+v.Encode(), nil, nil, nil)
	if err != nil {
		return err
	}

	return nil
}
コード例 #5
0
ファイル: flags.go プロジェクト: Jimdo/periodicnoise
func parseFlags() ([]string, error) {
	p := flags.NewParser(&opts, flags.Default)

	// display nice usage message
	p.Usage = "[OPTIONS]... COMMAND\n\nSafely wrap execution of COMMAND in e.g. a cron job"

	args, err := p.Parse()
	if err != nil {
		// --help is not an error
		if e, ok := err.(*flags.Error); ok && e.Type == flags.ErrHelp {
			return nil, nil
		}
		return nil, err
	}

	if len(args) < 1 {
		return nil, &FlagConstraintError{Constraint: "no command to execute"}
	}

	if err := validateOptionConstraints(); err != nil {
		return nil, err
	}

	return args, nil
}
コード例 #6
0
ファイル: main.go プロジェクト: r38y/go-camo
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	// command line flags
	var opts struct {
		BindAddress string `long:"listen" short:"l" default:"0.0.0.0:8000" description:"Address:Port to bind to for HTTP"`
	}

	// parse said flags
	parser := flags.NewParser(&opts, flags.Default)
	parser.Usage = "[OPTIONS] DIR"
	args, err := parser.Parse()
	if err != nil {
		if e, ok := err.(*flags.Error); ok {
			if e.Type == flags.ErrHelp {
				os.Exit(0)
			}
		}
		os.Exit(1)
	}

	var dirname string
	alen := len(args)
	switch {
	case alen < 1:
		dirname = "."
	case alen == 1:
		dirname = args[0]
	case alen > 1:
		log.Fatal("Too many arguments")
	}

	panic(http.ListenAndServe(opts.BindAddress, http.FileServer(http.Dir(dirname))))
}
コード例 #7
0
ファイル: githubpubkey.go プロジェクト: ngc224/githubpubkey
func main() {

	parser := flags.NewParser(&opts, flags.Default)
	parser.Name = "githubpubkey"
	parser.Usage = "[-h] [-v] username"

	args, err := parser.Parse()

	if err != nil {
		os.Exit(0)
	}

	if opts.Version {
		fmt.Print("Version " + version)
		os.Exit(0)
	}

	if len(args) == 0 {
		parser.WriteHelp(os.Stdout)
		fmt.Print("\n")
		os.Exit(0)
	}

	var wg sync.WaitGroup

	for _, username := range args {
		wg.Add(1)
		go func(username string) {
			keyPrint("https://github.com/" + username + ".keys")
			wg.Done()
		}(username)
	}

	wg.Wait()
}
コード例 #8
0
ファイル: main.go プロジェクト: vmware/vic
func main() {
	swaggerSpec, err := spec.New(restapi.SwaggerJSON, "")
	if err != nil {
		log.Fatalln(err)
	}

	api := operations.NewTaskTrackerAPI(swaggerSpec)
	server := restapi.NewServer(api)
	defer server.Shutdown()

	parser := flags.NewParser(server, flags.Default)
	parser.ShortDescription = `Issue Tracker API`
	parser.LongDescription = `This application implements a very simple issue tracker.
It's implemented as an API which is described by this swagger spec document.

The go-swagger project uses this specification to test the code generation.
This document contains all possible values for a swagger definition.
This means that it exercises the framework relatively well.
`

	for _, optsGroup := range api.CommandLineOptionsGroups {
		parser.AddGroup(optsGroup.ShortDescription, optsGroup.LongDescription, optsGroup.Options)
	}

	if _, err := parser.Parse(); err != nil {
		log.Fatalln(err)
	}

	if err := server.Serve(); err != nil {
		log.Fatalln(err)
	}
}
コード例 #9
0
ファイル: main.go プロジェクト: Rompei/lgb
// コマンドライン引数チェック用関数
func checkArgs() *options.Options {
	var opts options.Options
	parser := flags.NewParser(&opts, flags.Default)
	parser.Name = "lgb"
	parser.Usage = "[OPTIONS]"
	_, err := parser.Parse()
	if err != nil {
		os.Exit(1)
	}

	if opts.ConsumerKey == "" || opts.ConsumerSecret == "" || opts.AccessToken == "" || opts.AccessTokenSecret == "" {
		parser.WriteHelp(os.Stdout)
		os.Exit(1)
	}

	if opts.Width < 1 || opts.Height < 1 {
		parser.WriteHelp(os.Stdout)
		os.Exit(1)
	}

	if opts.AliveRate < 1 || opts.AliveRate > 100 || opts.MutRate < 0 || opts.MutRate > 100 || opts.Generation < 0 {
		parser.WriteHelp(os.Stdout)
		os.Exit(1)
	}

	return &opts
}
コード例 #10
0
ファイル: main.go プロジェクト: jak-atx/vic
func main() {
	swaggerSpec, err := spec.New(restapi.SwaggerJSON, "")
	if err != nil {
		log.Fatalln(err)
	}

	api := operations.NewTodoListAPI(swaggerSpec)
	server := restapi.NewServer(api)
	defer server.Shutdown()

	parser := flags.NewParser(server, flags.Default)
	parser.ShortDescription = `Simple To Do List API`
	parser.LongDescription = swaggerSpec.Spec().Info.Description

	for _, optsGroup := range api.CommandLineOptionsGroups {
		parser.AddGroup(optsGroup.ShortDescription, optsGroup.LongDescription, optsGroup.Options)
	}

	if _, err := parser.Parse(); err != nil {
		log.Fatalln(err)
	}

	if err := server.Serve(); err != nil {
		log.Fatalln(err)
	}
}
コード例 #11
0
ファイル: load.go プロジェクト: juito/hyper
func (cli *HyperClient) HyperCmdLoad(args ...string) error {
	var opts struct {
		Input string `short:"i" long:"input" value-name:"\"\"" description:"Read from a tar archive file, instead of STDIN"`
	}

	var parser = gflag.NewParser(&opts, gflag.Default|gflag.IgnoreUnknown)
	parser.Usage = "load [OPTIONS]\n\nLoad a image from STDIN or tar archive file"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	var input io.Reader = cli.in
	if opts.Input != "" {
		file, err := os.Open(opts.Input)
		if err != nil {
			return err
		}
		defer file.Close()
		input = file
	}
	output, ctype, err := cli.client.Load(input)
	if err != nil {
		return err
	}
	return cli.readStreamOutput(output, ctype, false, cli.out, cli.err)
}
コード例 #12
0
ファイル: load.go プロジェクト: ZJU-SEL/hyper
func (cli *HyperClient) HyperCmdLoad(args ...string) error {
	var opts struct {
		Input string `short:"i" long:"input" value-name:"\"\"" description:"Read from a tar archive file, instead of STDIN"`
	}

	var parser = gflag.NewParser(&opts, gflag.Default|gflag.IgnoreUnknown)
	parser.Usage = "load [OPTIONS]\n\nLoad a image from STDIN or tar archive file"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	var input io.Reader = cli.in
	if opts.Input != "" {
		file, err := os.Open(opts.Input)
		if err != nil {
			return err
		}
		defer file.Close()
		input = file
	}

	headers := map[string][]string{"Content-Type": {"application/x-tar"}}
	return cli.stream("POST", "/image/load", input, cli.out, headers)
}
コード例 #13
0
ファイル: stop.go プロジェクト: carriercomm/hyper
func (cli *HyperClient) HyperCmdStop(args ...string) error {

	var opts struct {
		//		Novm        bool     `long:"onlypod" default:"false" value-name:"false" description:"Stop a Pod, but left the VM running"`
	}
	var parser = gflag.NewParser(&opts, gflag.Default)
	parser.Usage = "stop POD_ID\n\nstop a running pod"
	args, err := parser.Parse()
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) == 1 {
		return fmt.Errorf("\"stop\" requires a minimum of 1 argument, please provide POD ID.\n")
	}

	podID := args[1]
	stopVm := "yes"
	if false {
		stopVm = "no"
	}
	code, cause, err := cli.StopPod(podID, stopVm)
	if err != nil {
		return err
	}
	if code != types.E_POD_STOPPED && code != types.E_VM_SHUTDOWN {
		return fmt.Errorf("Error code is %d, cause is %s", code, cause)
	}
	fmt.Printf("Success to shutdown the POD: %s!\n", podID)
	return nil
}
コード例 #14
0
ファイル: pod.go プロジェクト: m1911/hyper
// We need to process the POD json data with the given file
func (cli *HyperClient) HyperCmdPod(args ...string) error {
	t1 := time.Now()
	var parser = gflag.NewParser(nil, gflag.Default)
	parser.Usage = "pod POD_FILE\n\nCreate a pod, initialize a pod and run it"
	args, err := parser.Parse()
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) < 2 {
		return fmt.Errorf("\"pod\" requires a minimum of 1 argument, please provide POD spec file.\n")
	}
	jsonFile := args[1]
	if _, err := os.Stat(jsonFile); err != nil {
		return err
	}

	jsonbody, err := ioutil.ReadFile(jsonFile)
	if err != nil {
		return err
	}
	podId, err := cli.RunPod(string(jsonbody), false)
	if err != nil {
		return err
	}
	fmt.Fprintf(cli.out, "POD id is %s\n", podId)
	t2 := time.Now()
	fmt.Fprintf(cli.out, "Time to run a POD is %d ms\n", (t2.UnixNano()-t1.UnixNano())/1000000)

	return nil
}
コード例 #15
0
ファイル: unpause.go プロジェクト: ZJU-SEL/hyper
func (cli *HyperClient) HyperCmdUnpause(args ...string) error {
	var parser = gflag.NewParser(nil, gflag.Default|gflag.IgnoreUnknown)
	parser.Usage = "unpause Pod\n\nUnpause the pod"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) == 0 {
		return fmt.Errorf("Can not accept the 'unpause' command without Pod ID!")
	}

	v := url.Values{}
	v.Set("podId", args[0])

	body, _, err := readBody(cli.call("POST", "/pod/unpause?"+v.Encode(), nil, nil))
	if err != nil {
		return err
	}
	out := engine.NewOutput()
	if _, err = out.AddEnv(); err != nil {
		return err
	}

	if _, err := out.Write(body); err != nil {
		return err
	}
	out.Close()
	return nil
}
コード例 #16
0
ファイル: main.go プロジェクト: Cl0udPhish/go-swagger
func main() {
	swaggerSpec, err := loads.Analyzed(restapi.SwaggerJSON, "")
	if err != nil {
		log.Fatalln(err)
	}

	api := operations.NewAttendListAPI(swaggerSpec)
	server := restapi.NewServer(api)
	defer server.Shutdown()

	parser := flags.NewParser(server, flags.Default)
	parser.ShortDescription = `AttendList`
	parser.LongDescription = `AttendList service.
`

	server.ConfigureFlags()
	for _, optsGroup := range api.CommandLineOptionsGroups {
		parser.AddGroup(optsGroup.ShortDescription, optsGroup.LongDescription, optsGroup.Options)
	}

	if _, err := parser.Parse(); err != nil {
		os.Exit(1)
	}

	server.ConfigureAPI()

	if err := server.Serve(); err != nil {
		log.Fatalln(err)
	}
}
コード例 #17
0
ファイル: logs.go プロジェクト: juito/hyper
func (cli *HyperClient) HyperCmdLogs(args ...string) error {
	var opts struct {
		Follow bool   `short:"f" long:"follow" default:"false" default-mask:"-" description:"Follow log output"`
		Since  string `long:"since" value-name:"\"\"" description:"Show logs since timestamp"`
		Times  bool   `short:"t" long:"timestamps" default:"false" default-mask:"-" description:"Show timestamps"`
		Tail   string `long:"tail" value-name:"\"all\"" description:"Number of lines to show from the end of the logs"`
	}

	var parser = gflag.NewParser(&opts, gflag.Default|gflag.IgnoreUnknown)
	parser.Usage = "logs CONTAINER [OPTIONS...]\n\nFetch the logs of a container"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}

	if len(args) == 0 {
		return fmt.Errorf("%s ERROR: Can not accept the 'logs' command without argument!\n", os.Args[0])
	}

	c, err := cli.client.GetContainerInfo(args[0])
	if err != nil {
		return err
	}

	output, ctype, err := cli.client.ContainerLogs(args[0], opts.Since, opts.Times, opts.Follow, true, true, opts.Tail)
	if err != nil {
		return err
	}
	return cli.readStreamOutput(output, ctype, c.Container.Tty, cli.out, cli.err)
}
コード例 #18
0
ファイル: main.go プロジェクト: yuya-takeyama/numstat
func main() {
	parser := flags.NewParser(&opts, flags.Default^flags.PrintErrors)
	parser.Name = AppName
	parser.Usage = "[OPTIONS] FILES..."

	args, err := parser.Parse()
	if err != nil {
		fmt.Fprint(os.Stderr, err)
		return
	}

	r, err := argf.From(args)
	if err != nil {
		panic(err)
	}

	if opts.isAllDisabled() {
		opts.enableAll()
	}

	err = numstat(r, os.Stdout, os.Stderr, opts)
	if err != nil {
		panic(err)
	}
}
コード例 #19
0
ファイル: logout.go プロジェクト: juito/hyper
// CmdLogout logs a user out from a Docker registry.
//
// If no server is specified, the user will be logged out from the registry's index server.
//
// Usage: hyperctl logout [SERVER]
func (cli *HyperClient) HyperCmdLogout(args ...string) error {
	var parser = gflag.NewParser(nil, gflag.Default)
	parser.Usage = "logout [SERVER]\n\nLog out from a Docker registry, if no server is\nspecified \"" + registry.IndexServer + "\" is the default."
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	serverAddress := registry.IndexServer
	if len(args) > 0 {
		serverAddress = args[0]
	}

	if _, ok := cli.configFile.AuthConfigs[serverAddress]; !ok {
		fmt.Fprintf(cli.out, "Not logged in to %s\n", serverAddress)
	} else {
		fmt.Fprintf(cli.out, "Remove login credentials for %s\n", serverAddress)
		delete(cli.configFile.AuthConfigs, serverAddress)

		if err := cli.configFile.Save(); err != nil {
			return fmt.Errorf("Failed to save docker config: %v", err)
		}
	}
	return nil
}
コード例 #20
0
ファイル: flags.go プロジェクト: GeertJohan/aerospike-udf-go
func setupFlags() {
	// setup parser with our flags and custom options
	flagsParser := goflags.NewParser(&flags, goflags.HelpFlag|goflags.PrintErrors)

	// parse command line arguments
	args, err := flagsParser.Parse()
	if err != nil {
		// assert the err to be a flags.Error
		flagError, ok := err.(*goflags.Error)
		if !ok {
			// not a flags error
			os.Exit(1)
		}
		if flagError.Type == goflags.ErrHelp {
			// exitcode 0 when user asked for help
			os.Exit(0)
		}
		if flagError.Type == goflags.ErrUnknownFlag {
			fmt.Println("run with --help to view available options")
		}
		os.Exit(1)
	}

	// error on left-over arguments
	if len(args) > 0 {
		fmt.Printf("unexpected arguments: %s\n", args)
		os.Exit(0)
	}
}
コード例 #21
0
ファイル: main.go プロジェクト: MStoykov/go-swagger
func main() {
	swaggerSpec, err := spec.New(SwaggerJSON, "")
	if err != nil {
		log.Fatalln(err)
	}

	parser := flags.NewParser(&opts, flags.Default)
	parser.ShortDescription = swaggerSpec.Spec().Info.Title
	parser.LongDescription = swaggerSpec.Spec().Info.Description

	if _, err := parser.Parse(); err != nil {
		os.Exit(1)
	}

	api := operations.NewTodoListAPI(swaggerSpec)
	handler := configureAPI(api)

	httpServer := &graceful.Server{Server: new(http.Server)}
	httpServer.Handler = handler

	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port))
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("serving todo list at http://%s\n", listener.Addr())
	if err := httpServer.Serve(tcpKeepAliveListener{listener.(*net.TCPListener)}); err != nil {
		log.Fatalln(err)
	}

}
コード例 #22
0
ファイル: push.go プロジェクト: juito/hyper
// CmdPush pushes an image or repository to the registry.
//
// Usage: hyperctl push NAME[:TAG]
func (cli *HyperClient) HyperCmdPush(args ...string) error {
	var parser = gflag.NewParser(nil, gflag.Default)
	parser.Usage = "push NAME[:TAG]\n\nPush an image to a Docker registry server"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	// we need to get the image name which will be used to create a container
	if len(args) == 0 {
		return fmt.Errorf("\"push\" requires a minimum of 1 argument, please provide the image name.")
	}
	name := args[0]

	ref, err := reference.ParseNamed(name)
	if err != nil {
		return err
	}

	var tag string
	switch x := ref.(type) {
	case reference.Canonical:
		return fmt.Errorf("cannot push a digest reference")
	case reference.NamedTagged:
		tag = x.Tag()
	}

	// Resolve the Repository name from fqn to RepositoryInfo
	repoInfo, err := registry.ParseRepositoryInfo(ref)
	if err != nil {
		return err
	}
	// Resolve the Auth config relevant for this server
	authConfig := registry.ResolveAuthConfig(cli.configFile.AuthConfigs, repoInfo.Index)
	// If we're not using a custom registry, we know the restrictions
	// applied to repository names and can warn the user in advance.
	// Custom repositories can have different rules, and we must also
	// allow pushing by image ID.
	if repoInfo.Official {
		username := authConfig.Username
		if username == "" {
			username = "******"
		}
		return fmt.Errorf("You cannot push a \"root\" repository. Please rename your repository to <user>/<repo> (ex: %s/%s)", username, ref.Name())
	}

	push := func(auth types.AuthConfig) (io.ReadCloser, string, int, error) {
		return cli.client.Push(tag, repoInfo.String(), auth)
	}

	body, ctype, _, err := cli.requestWithLogin(repoInfo.Index, push, "push")
	if err != nil {
		return err
	}

	return cli.readStreamOutput(body, ctype, cli.isTerminalOut, cli.out, cli.err)
}
コード例 #23
0
ファイル: create.go プロジェクト: m1911/hyper
func (cli *HyperClient) HyperCmdCreate(args ...string) error {
	if len(args) == 0 {
		return fmt.Errorf("\"create\" requires a minimum of 1 argument, please provide POD spec file.\n")
	}
	var opts struct {
		Yaml bool `short:"y" long:"yaml" default:"false" default-mask:"-" description:"create a pod based on Yaml file"`
	}
	var parser = gflag.NewParser(&opts, gflag.Default)
	parser.Usage = "create [OPTIONS] POD_FILE\n\nCreate a pod into 'pending' status, but without running it"
	args, err := parser.Parse()
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	jsonFile := args[1]

	jsonbody, err := cli.JsonFromFile(jsonFile, opts.Yaml, false)
	if err != nil {
		return err
	}

	podId, err := cli.CreatePod(jsonbody, false)
	if err != nil {
		return err
	}
	fmt.Printf("Pod ID is %s\n", podId)
	return nil
}
コード例 #24
0
ファイル: main.go プロジェクト: jak-atx/vic
func main() {
	swaggerSpec, err := spec.New(restapi.SwaggerJSON, "")
	if err != nil {
		log.Fatalln(err)
	}

	api := operations.NewTodoListAPI(swaggerSpec)
	server := restapi.NewServer(api)
	defer server.Shutdown()

	parser := flags.NewParser(server, flags.Default)
	parser.ShortDescription = `A To Do list application`
	parser.LongDescription = `The product of a tutorial on goswagger.io`

	for _, optsGroup := range api.CommandLineOptionsGroups {
		parser.AddGroup(optsGroup.ShortDescription, optsGroup.LongDescription, optsGroup.Options)
	}

	if _, err := parser.Parse(); err != nil {
		log.Fatalln(err)
	}

	if err := server.Serve(); err != nil {
		log.Fatalln(err)
	}
}
コード例 #25
0
func main() {

	parser := flags.NewParser(&opts, flags.Default)
	args, err := parser.Parse()
	if err != nil {
		os.Exit(1)
	}

	parser.Name = "pt"
	parser.Usage = "[OPTIONS] PATTERN [PATH]"

	if !terminal.IsTerminal(os.Stdout) {
		opts.NoColor = true
		opts.NoGroup = true
	}

	if len(args) == 0 {
		parser.WriteHelp(os.Stdout)
		os.Exit(1)
	}

	var root = "."
	if len(args) == 2 {
		root = args[1]
	}

	searcher := search.Searcher{root, args[0], &opts}
	searcher.Search()
}
コード例 #26
0
ファイル: rm.go プロジェクト: ZJU-SEL/hyper
func (cli *HyperClient) HyperCmdRm(args ...string) error {
	var parser = gflag.NewParser(nil, gflag.Default)
	parser.Usage = "rm POD [POD...]\n\nRemove one or more pods"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) == 0 {
		return fmt.Errorf("\"rm\" requires a minimum of 1 argument, please provide POD ID.\n")
	}
	pods := args
	for _, id := range pods {
		err := cli.RmPod(id)
		if err == nil {
			fmt.Fprintf(cli.out, "Pod(%s) is successful to be deleted!\n", id)
		} else {
			fmt.Fprintf(cli.out, "%v\n", err)
		}
	}
	return nil
}
コード例 #27
0
ファイル: main.go プロジェクト: MStoykov/go-swagger
func main() {
	swaggerSpec, err := spec.New(SwaggerJSON, "")
	if err != nil {
		log.Fatalln(err)
	}

	parser := flags.NewParser(&opts, flags.Default)
	parser.ShortDescription = swaggerSpec.Spec().Info.Title
	parser.LongDescription = swaggerSpec.Spec().Info.Description

	if _, err := parser.Parse(); err != nil {
		os.Exit(1)
	}

	api := operations.NewSimpleToDoListAPI(swaggerSpec)
	handler := configureAPI(api)

	httpServer := &graceful.Server{Server: new(http.Server)}
	httpServer.Handler = handler

	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port))
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("serving simple to do list at http://%s\n", listener.Addr())
	go func() {
		if err := httpServer.Serve(tcpKeepAliveListener{listener.(*net.TCPListener)}); err != nil {
			log.Fatalln(err)
		}
	}()

	httpsServer := &graceful.Server{Server: new(http.Server)}
	httpsServer.Handler = handler
	httpsServer.TLSConfig = new(tls.Config)
	httpsServer.TLSConfig.NextProtos = []string{"http/1.1"}
	// https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet#Rule_-_Only_Support_Strong_Protocols
	httpsServer.TLSConfig.MinVersion = tls.VersionTLS11
	httpsServer.TLSConfig.Certificates = make([]tls.Certificate, 1)
	httpsServer.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(string(opts.TLSCertificate), string(opts.TLSCertificateKey))
	if err != nil {
		log.Fatal(err)
	}

	if opts.TLSHost == "" {
		opts.TLSHost = opts.Host
	}
	tlsListener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", opts.TLSHost, opts.TLSPort))
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("serving simple to do list at https://%s\n", tlsListener.Addr())

	wrapped := tls.NewListener(tcpKeepAliveListener{tlsListener.(*net.TCPListener)}, httpsServer.TLSConfig)
	if err := httpsServer.Serve(wrapped); err != nil {
		log.Fatalln(err)
	}
}
コード例 #28
0
ファイル: main.go プロジェクト: gophergala2016/wwcdc_01
func main() {
	swaggerSpec, err := spec.New(SwaggerJSON, "")
	if err != nil {
		log.Fatalln(err)
	}

	parser := flags.NewParser(&opts, flags.Default)
	parser.ShortDescription = swaggerSpec.Spec().Info.Title
	parser.LongDescription = swaggerSpec.Spec().Info.Description

	api := operations.NewGophergalaLearningResourcesAPI(swaggerSpec)
	handler = configureAPI(api)

	for _, optsGroup := range api.CommandLineOptionsGroups {
		parser.AddGroup(optsGroup.ShortDescription, optsGroup.LongDescription, optsGroup.Options)
	}

	if _, err := parser.Parse(); err != nil {
		os.Exit(1)
	}

	httpsServer := &graceful.Server{Server: new(http.Server)}
	// Normal resources
	chttp.Handle("/", http.FileServer(http.Dir("public")))

	mux := http.NewServeMux()
	mux.HandleFunc("/", ApiHandler)
	httpsServer.Handler = mux
	httpsServer.TLSConfig = new(tls.Config)
	httpsServer.TLSConfig.NextProtos = []string{"http/1.1"}
	// https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet#Rule_-_Only_Support_Strong_Protocols
	httpsServer.TLSConfig.MinVersion = tls.VersionTLS11
	httpsServer.TLSConfig.Certificates = make([]tls.Certificate, 1)
	httpsServer.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(string(opts.TLSCertificate), string(opts.TLSCertificateKey))
	if err != nil {
		api.ServerShutdown()
		log.Fatal(err)
	}

	tlsListener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", opts.TLSHost, opts.TLSPort))
	if err != nil {
		api.ServerShutdown()
		log.Fatalln(err)
	}

	log.Printf("serving gophergala learning resources at https://%s:%d\n", opts.TLSHost, opts.TLSPort)

	wrapped := tls.NewListener(tcpKeepAliveListener{tlsListener.(*net.TCPListener)}, httpsServer.TLSConfig)
	if err := httpsServer.Serve(wrapped); err != nil {
		api.ServerShutdown()
		log.Printf("shutting down gophergala learning resources at https://%s:%d\n", opts.TLSHost, opts.TLSPort)
		log.Fatalln(err)
	}
	go func() {

		<-httpsServer.StopChan()
		api.ServerShutdown()
	}()
}
コード例 #29
0
ファイル: subzer.go プロジェクト: razielgn/subzer
func main() {
	var opts struct {
		File      string `short:"i" description:"File input"`
		Directory string `short:"r" description:"Folder input"`
	}

	parser := flags.NewParser(&opts, flags.Default)
	parser.ApplicationName = "subzer"
	parser.Usage = "[OPTIONS]"

	_, err := parser.Parse()

	if err != nil {
		os.Exit(1)
	}

	file := opts.File
	dir := opts.Directory

	if len(file) > 0 && len(dir) > 0 {
		fmt.Println("Error: input a file or a directory, not both.")
		os.Exit(1)
	}

	if len(file) == 0 && len(dir) == 0 {
		parser.WriteHelp(os.Stdout)
		os.Exit(1)
	}

	files := list.New()

	if len(file) > 0 {
		if _, err := os.Stat(file); err != nil {
			fmt.Printf("Error: file \"%s\" does not exist.\n", file)
			os.Exit(1)
		}

		files.PushBack(file)
	}

	if len(dir) > 0 {
		if _, err := os.Stat(dir); err != nil {
			fmt.Printf("Error: directory %s does not exist.\n", dir)
			os.Exit(1)
		}

		err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
			if filepath.Ext(path) == ".srt" {
				files.PushBack(path)
			}

			return err
		})
	}

	for e := files.Front(); e != nil; e = e.Next() {
		ProcessFile(e.Value.(string))
	}
}
コード例 #30
0
ファイル: ourmine.go プロジェクト: pankona/ourmine
func main() {
	var opts Options
	parser := flags.NewParser(&opts, flags.Default)

	parser.Name = "mymine"
	parser.Usage = "[OPTIONS]"

	_, err := parser.Parse()
	if err != nil {
		os.Exit(0)
	}

	if opts.Version != nil {
		showVersion()
		os.Exit(0)
	}

	redmineUrl := getEnvVar("REDMINE_URL")
	if redmineUrl == "" {
		fmt.Println("REDMINE_URL is not specified.")
		os.Exit(0)
	}

	if opts.Open != nil {
		url := redmineUrl + "issues/" + strconv.Itoa(opts.Open[0])
		openUrlByBrowser(url)
		os.Exit(0)
	}

	redmineApiKey := getEnvVar("REDMINE_API_KEY")
	if redmineApiKey == "" {
		fmt.Println("REDMINE_API_KEY is not specified.")
		os.Exit(0)
	}

	project_id := 946 // TODO: should be an option
	request := redmineUrl + "issues.json?key=" + redmineApiKey + "&limit=100&project_id=" + strconv.Itoa(project_id) + "&status_id=open"
	fmt.Println("request =", request)
	fmt.Println("fetching information...")
	var buf map[string]interface{}
	rest.Get(&buf, request, nil)

	issues := buf["issues"].([]interface{})
	for _, v := range issues {
		issue := v.(map[string]interface{})

		var assigned_to string
		tracker := issue["tracker"].(map[string]interface{})
		if issue["assigned_to"] != nil {
			assigned_to_map := issue["assigned_to"].(map[string]interface{})
			assigned_to = assigned_to_map["name"].(string)
		} else {
			assigned_to = "not_assigned"
		}
		id := int(issue["id"].(float64))
		status := issue["status"].(map[string]interface{})
		fmt.Printf("%s #%d %s %s %s\n", tracker["name"], id, status["name"], issue["subject"], assigned_to)
	}
}