golang urfave/cli 명령 패키지
41362 단어 go
go get github.com/urfave/cli import “github.com/urfave/cli”
패키지 cli 가져오기New App () 는 실행 () 방법을 사용하는 실례를 만들어서 가장 기본적인 명령행 프로그램을 실현했다.Action 포털 함수 지정
package main
import (
"os"
"github.com/urfave/cli"
)
func main() {
app := cli.NewApp()
app.Name = "greet"
app.Usage = "say a greeting"
app.Action = func(c *cli.Context) error {
println("Greetings")
return nil
}
app.Run(os.Args)
}
실행 1:go run main.go --help NAME: greet - say a greeting
USAGE: main.exe [global options] command [command options] [arguments…]
VERSION: 0.0.0
COMMANDS: help, h Shows a list of commands or help for one command
GLOBAL OPTIONS: –help, -h show help –version, -v print the version
실행 2:go run main.go Greetings
Flag 사용
package main
import (
"fmt"
"os"
"github.com/urfave/cli"
)
func main() {
var m_port int
app := cli.NewApp()
app.Name = "greet" //
app.Usage = "say a greeting" //
app.Flags = []cli.Flag{
cli.IntFlag{
Name: "port, p", //
Value: 8000, //
Usage: "listening port", //
Destination: &m_port, //
},
}
app.Action = func(c *cli.Context) error {
println("Greetings")
fmt.Println(c.Int("port"))
fmt.Println(m_port)
return nil
}
app.Run(os.Args)
}
실행 1:go run main.go --help NAME: greet - say a greeting
USAGE: main.exe [global options] command [command options] [arguments…]
VERSION: 0.0.0
COMMANDS: help, h Shows a list of commands or help for one command
GLOBAL OPTIONS: –port value, -p value listening port (default: 8000) –help, -h show help –version, -v print the version
실행 2:go run main.go Greetings 8000 8000
실행 3:go run main.go --port=8080 Greetings 8080 8080
Command 사용
package main
import (
"fmt"
"os"
"github.com/urfave/cli"
)
func main() {
var m_port int
app := cli.NewApp()
app.Name = "greet" //
app.Usage = "say a greeting" //
app.Flags = []cli.Flag{
cli.IntFlag{
Name: "port, p", //
Value: 8000, //
Usage: "listening port", //
Destination: &m_port, //
},
}
app.Commands = []cli.Command{
{
Name: "add", //
Aliases: []string{"a"}, //
Usage: "calc 1+1", //
Category: "arithmetic", //
Action: func(c *cli.Context) error { //
fmt.Println("1 + 1 = ", 1+1)
return nil
},
},
{
Name: "sub",
Aliases: []string{"s"},
Usage: "calc 5-3",
Category: "arithmetic",
Action: func(c *cli.Context) error {
fmt.Println("5 - 3 = ", 5-3)
return nil
},
},
{
Name: "db",
Usage: "database operations",
Category: "database",
Subcommands: []cli.Command{ //
{
Name: "insert",
Usage: "insert data",
Action: func(c *cli.Context) error {
fmt.Println("insert subcommand")
return nil
},
},
{
Name: "delete",
Usage: "delete data",
Action: func(c *cli.Context) error {
fmt.Println("delete subcommand")
return nil
},
},
},
},
}
app.Action = func(c *cli.Context) error {
println("Greetings")
fmt.Println(c.Int("port"))
fmt.Println(m_port)
return nil
}
app.Run(os.Args)
}
실행 1:go run main.go --help NAME: greet - say a greeting
USAGE: main.exe [global options] command [command options] [arguments…]
VERSION: 0.0.0
COMMANDS: help, h Shows a list of commands or help for one command
arithmetic: add, a calc 1+1 sub, s calc 5-3
database: db database operations
GLOBAL OPTIONS: –port value, -p value listening port (default: 8000) –help, -h show help –version, -v print the version
실행 2:go run main.go db --help NAME: greet db - database operations
USAGE: greet db command [command options] [arguments…]
COMMANDS: insert insert data delete delete data
OPTIONS: –help, -h show help
실행 3:go run main.go add --help NAME: main.exe add - calc 1+1
USAGE: main.exe add [arguments…]
CATEGORY: arithmetic
실행 4:go run main.go --port 8080 Greetings 8080 8080
실행 5:go run main.go add 1 + 1 = 2
실행 6:go run main.go db insert insert subcommand
7:go run mai 실행go --port=8080 add db insert 1 + 1 = 2
실행 8:go run main.go add db insert 1 + 1 = 2
실행 9:go run main.go Greetings 8000 8000
고급 사용 방법
package main
import (
"fmt"
"os"
"github.com/urfave/cli"
)
func main() {
app := cli.NewApp()
app.Name = "greet" //
app.Usage = "say a greeting" //
app.Flags = []cli.Flag{
cli.IntFlag{
Name: "port, p", //
Value: 8000, //
Usage: "listening port", //
},
}
app.Action = MigrateFlags(print1)
app.Commands = []cli.Command{
{
Name: "add", //
Aliases: []string{"a"}, //
Usage: "calc 1+1", //
Category: "arithmetic", //
Action: MigrateFlags(print2),
},
}
app.Run(os.Args)
}
func MigrateFlags(action func(ctx *cli.Context) error) func(*cli.Context) error {
return func(ctx *cli.Context) error {
for _, name := range ctx.FlagNames() {
if ctx.IsSet(name) {
ctx.GlobalSet(name, ctx.String(name))
}
}
return action(ctx)
}
}
func print1(ctx *cli.Context) error {
fmt.Println("hello world!")
fmt.Println(ctx.Int("port"))
return nil
}
func print2(ctx *cli.Context) error {
fmt.Println("1 + 1 = ", 1+1)
return nil
}
실행 1:go run main.go hello world! 8000
실행 2:go run main.go add 1 + 1 = 2
type App struct {
// The name of the program. Defaults to path.Base(os.Args[0])
Name string // , , 。
// Full name of command for help, defaults to Name
HelpName string
// Description of the program.
Usage string //
// Text to override the USAGE section of help
UsageText string
// Description of the program argument format.
ArgsUsage string
// Version of the program
Version string
// Description of the program
Description string
// List of commands to execute
Commands []Command
// List of flags to parse
Flags []Flag // Flag cli
// Boolean to enable bash completion commands
EnableBashCompletion bool
// Boolean to hide built-in help command
HideHelp bool
// Boolean to hide built-in version flag and the VERSION section of help
HideVersion bool
// An action to execute when the bash-completion flag is set
BashComplete BashCompleteFunc
// An action to execute before any subcommands are run, but after the context is ready
// If a non-nil error is returned, no subcommands are run
Before BeforeFunc
// An action to execute after any subcommands are run, but after the subcommand has finished
// It is run even if Action() panics
After AfterFunc
// The action to execute when no subcommands are specified
// Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}`
// *Note*: support for the deprecated `Action` signature will be removed in a future version
Action interface{}
// Execute this function if the proper command cannot be found
CommandNotFound CommandNotFoundFunc
// Execute this function if an usage error occurs
OnUsageError OnUsageErrorFunc
// Compilation date
Compiled time.Time
// List of all authors who contributed
Authors []Author
// Copyright of the binary if any
Copyright string
// Name of Author (Note: Use App.Authors, this is deprecated)
Author string
// Email of Author (Note: Use App.Authors, this is deprecated)
Email string
// Writer writer to write output to
Writer io.Writer
// ErrWriter writes error output
ErrWriter io.Writer
// Execute this function to handle ExitErrors. If not provided, HandleExitCoder is provided to
// function as a default, so this is optional.
ExitErrHandler ExitErrHandlerFunc
// Other custom info
Metadata map[string]interface{}
// Carries a function which returns app specific info.
ExtraInfo func() map[string]string
// CustomAppHelpTemplate the text template for app help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
CustomAppHelpTemplate string
// contains filtered or unexported fields
}
Flag은 cli에서 분석 표지와 관련된 공통 인터페이스입니다
type Flag interface {
fmt.Stringer
// Apply Flag settings to the given flag set
Apply(*flag.FlagSet)
GetName() string
}
IntFlag은 Flag의 정형 유형으로 Flag 인터페이스를 실현했다.
type IntFlag struct {
Name string //
Usage string //
EnvVar string
FilePath string
Hidden bool
Value int //
Destination *int //
}
Command 명령
type Command struct {
// The name of the command
Name string
// short name of the command. Typically one character (deprecated, use `Aliases`)
ShortName string
// A list of aliases for the command
Aliases []string
// A short description of the usage of this command
Usage string
// Custom text to show on USAGE section of help
UsageText string
// A longer explanation of how the command works
Description string
// A short description of the arguments of this command
ArgsUsage string
// The category the command is part of
Category string //
// The function to call when checking for bash command completions
BashComplete BashCompleteFunc
// An action to execute before any sub-subcommands are run, but after the context is ready
// If a non-nil error is returned, no sub-subcommands are run
Before BeforeFunc
// An action to execute after any subcommands are run, but after the subcommand has finished
// It is run even if Action() panics
After AfterFunc
// The function to call when this command is invoked
Action interface{}
// Execute this function if a usage error occurs.
OnUsageError OnUsageErrorFunc
// List of child commands
Subcommands Commands
// List of flags to parse
Flags []Flag
// Treat all flags as normal arguments if true
SkipFlagParsing bool
// Skip argument reordering which attempts to move flags before arguments,
// but only works if all flags appear after all arguments. This behavior was
// removed n version 2 since it only works under specific conditions so we
// backport here by exposing it as an option for compatibility.
SkipArgReorder bool
// Boolean to hide built-in help command
HideHelp bool
// Boolean to hide this command from help or completion
Hidden bool
// Boolean to enable short-option handling so user can combine several
// single-character bool arguments into one
// i.e. foobar -o -v -> foobar -ov
UseShortOptionHandling bool
// Full name of command for help, defaults to full command name, including parent commands.
HelpName string
// CustomHelpTemplate the text template for the command help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
CustomHelpTemplate string
// contains filtered or unexported fields
}
// Context is a type that is passed through to
// each Handler action in a cli application. Context
// can be used to retrieve context-specific Args and
// parsed command-line options.
type Context struct {
App *App
Command Command
shellComplete bool
flagSet *flag.FlagSet
setFlags map[string]bool
parentContext *Context
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Go Fiber 및 PlanetScale로 REST API 구축 - 4부다시 사용자 핸들러에 UpdateUser라는 새 함수를 추가합니다. 업데이트 사용자를 main.go에 등록 이제 응용 프로그램을 다시 실행하십시오. 이전에 생성한 사용자를 업데이트합니다. 응답 사용자가 존재하지 않을...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.