本文整理汇总了Golang中github.com/bobappleyard/readline.String函数的典型用法代码示例。如果您正苦于以下问题:Golang String函数的具体用法?Golang String怎么用?Golang String使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了String函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: loaderCreator
// Prompts for input and creates a new loader entry through the API
func loaderCreator(cli client.Client) (err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("loaderCreator() -> %v", e)
}
}()
var newle mig.LoaderEntry
fmt.Println("Entering loader creation mode.\nPlease provide the name" +
" of the new entry")
newle.Name, err = readline.String("name> ")
if err != nil {
panic(err)
}
if len(newle.Name) < 3 {
panic("input name too short")
}
fmt.Printf("Name: '%s'\n", newle.Name)
fmt.Println("Please provide loader key for entry.")
newle.Key, err = readline.String("key> ")
if err != nil {
panic(err)
}
fmt.Printf("Key: '%s'\n", newle.Key)
// Validate the new loader entry before sending it to the API
err = newle.Validate()
if err != nil {
panic(err)
}
jsonle, err := json.MarshalIndent(newle, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", jsonle)
input, err := readline.String("create loader entry? (y/n)> ")
if err != nil {
panic(err)
}
if input != "y" {
fmt.Println("abort")
return
}
err = cli.PostNewLoader(newle)
if err != nil {
panic(err)
}
fmt.Println("New entry successfully created but is disabled")
return
}
示例2: replCLI
func replCLI(env *Env) {
defer fmt.Println("\nbye!")
counter := readline.HistorySize()
for {
buf := bytes.Buffer{}
prompt := fmt.Sprintf("[%d]-> ", counter)
for {
l, err := readline.String(prompt)
if err == io.EOF {
return
}
buf.WriteString(l)
if validSexp(buf.String()) {
break
}
buf.WriteString("\n")
prompt = ": "
}
result, err := repl(buf.String(), env)
if err != nil && err != ErrorEOF {
fmt.Println("Error:", err)
} else {
fmt.Println(result)
}
readline.AddHistory(buf.String())
counter++
}
}
示例3: main
func main() {
env := evaluator.BuildEnvironment()
for {
l, err := readline.String("> ")
if err == io.EOF {
break
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
break
}
f, err := parser.Parse(strings.NewReader(l))
if err != nil {
fmt.Fprintln(os.Stderr, err)
readline.AddHistory(l)
}
r, err := evaluator.Eval(env, f)
if err != nil {
fmt.Fprintln(os.Stderr, err)
} else {
fmt.Println(r)
}
readline.AddHistory(l)
}
}
示例4: ExampleCleanup
func ExampleCleanup() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, syscall.SIGINT)
readline.CatchSigint = false
var line string
var err error
done := make(chan struct{})
go func() {
line, err = readline.String("> ")
close(done)
}()
select {
case <-sigint:
fmt.Println("\nInterrupted")
// Restore terminal attributes
readline.Cleanup()
// Note that we still have a goroutine reading from Stdin that
// will terminate when we exit.
os.Exit(1)
case <-done:
fmt.Printf("Read line %s, error %v\n", line, err)
}
}
示例5: main
/*
func main() {
flag.Parse()
go sigHandler()
rl, err := readline.New("> ")
if err != nil {
panic(err)
}
defer rl.Close()
for {
line, err := rl.Readline()
if err != nil {
break
}
args := strings.Fields(line)
if len(args) == 0 {
continue
}
f, ok := cmd[args[0]]
if ok {
err := f(args[1:])
if err != nil {
log.Println(line, err)
}
} else {
log.Println("Not found:", line)
}
stop = false
}
fmt.Println("Exiting")
}
*/
func main() {
flag.Parse()
go sigHandler()
for {
line, err := readline.String("% ")
if err == io.EOF {
break
}
if err != nil {
log.Println("error:", err)
break
}
args := strings.Fields(line)
if len(args) == 0 {
continue
}
f, ok := cmd[args[0]]
if ok {
err := f(args[1:])
if err != nil {
log.Println(line, err)
}
} else {
log.Println("Not found:", line)
}
stop = false
readline.AddHistory(line)
}
fmt.Println("Exiting")
}
示例6: uiLoop
func uiLoop() {
for {
line := readline.String("> ")
rc := uiParseHistory(line)
if !rc {
break
}
}
}
示例7: Start
// Starts the controller.
func (c *Controller) Start() int {
c.welcome()
c.ChangeWorkingDir("/")
readline.Completer = c.filenameCompleter
buffer := bytes.NewBufferString("")
prompt := ""
for {
if buffer.Len() == 0 {
prompt = c.ps1()
} else {
prompt = c.ps2()
}
line, err := readline.String(prompt)
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
line = strings.TrimSpace(line)
if strings.ToLower(line) == "q" || strings.ToLower(line) == "exit" {
return 0
}
if strings.HasSuffix(line, "\\") {
buffer.WriteString(strings.TrimSuffix(line, "\\") + "\n")
} else {
if buffer.Len() > 0 {
buffer.WriteString(line)
line = buffer.String()
buffer.Reset()
}
parts, err := shlex.Split(line)
if err != nil {
panic(err)
}
readline.AddHistory(line)
in := NewInput(parts[0])
if len(parts) > 1 {
in.Args = parts[1:]
}
c.handleInput(in)
}
}
return 0
}
示例8: interact
// Gets additional suppression patterns, etc. from the user.
func interact(done chan<- string) {
const prompt = "prolix> "
L:
for {
cmd, _ := readline.String(prompt)
if cmd == "" {
break L
}
readline.AddHistory(cmd)
unary := unaryRe.FindStringSubmatch(cmd)
if unary == nil {
trimmed := strings.TrimSpace(cmd)
switch trimmed {
case "quit":
done <- "quit"
return
case "pats":
printPats()
case "help":
printInteractiveHelp()
default:
fmt.Println("Unknown command. Try 'help'.")
}
} else {
switch strings.Replace(unary[1], "_", "-", -1) {
case "ignore-re":
if importIgnoreRE(unary[2:3]) {
ignoreRe = append(ignoreRe, unary[2])
}
case "ignore-line":
ignoreLine = append(ignoreLine, unary[2])
case "ignore-substring":
ignoreSubstring = append(ignoreSubstring, unary[2])
case "snippet":
if importSnippet(unary[2:3]) {
snippet = append(snippet, unary[2])
}
default:
fmt.Println("Unknown unary command. Try 'help'.")
}
}
}
done <- ""
}
示例9: CommandParser
func CommandParser() <-chan Command {
commands := make(chan Command, 1)
go func() {
for {
in, err := readline.String("")
if err == io.EOF { // Ctrl+D
commands <- Exit
break
} else if err != nil {
log.Fatal(err)
}
commands <- NormalizeCommand(in)
readline.AddHistory(in)
}
}()
return commands
}
示例10: doPrompt
func doPrompt(s *KinesisStream) {
moreToRead := true
for moreToRead {
line, err := readline.String("Send to Kinesis, <crtl-d> to end: ")
if err == io.EOF {
moreToRead = false
} else if err != nil {
log.Fatal(err)
} else {
resp, err := s.PutLogLine(strings.TrimRight(line, "\n"))
if err != nil {
log.Fatal(err)
}
if verbose {
fmt.Println("Response:", awsutil.StringValue(resp))
}
readline.AddHistory(line)
}
}
}
示例11: promptLoop
func promptLoop(prompt string, process func(string) error) (err error) {
errStr := "Error - %s.\n"
for moreCommands := true; moreCommands; {
line, err := readline.String(prompt)
if err == io.EOF {
moreCommands = false
} else if err != nil {
fmt.Printf(errStr, err)
} else {
readline.AddHistory(line)
err = process(line)
if err == io.EOF {
moreCommands = false
} else if err != nil {
fmt.Printf(errStr, err)
}
}
}
return nil
}
示例12: actionLauncher
// actionLauncher prepares an action for launch, either by starting with an empty
// template, or by loading an existing action from the api or the local disk
func actionLauncher(tpl mig.Action, ctx Context) (err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("actionLauncher() -> %v", e)
}
}()
var a mig.Action
if tpl.ID == 0 {
fmt.Println("Entering action launcher with empty template")
a.SyntaxVersion = mig.ActionVersion
} else {
// reinit the fields that we don't reuse
a.Name = tpl.Name
a.Target = tpl.Target
a.Description = tpl.Description
a.Threat = tpl.Threat
a.Operations = tpl.Operations
a.SyntaxVersion = tpl.SyntaxVersion
fmt.Printf("Entering action launcher using template '%s'\n", a.Name)
}
hasTimes := false
hasSignatures := false
fmt.Println("Type \x1b[32;1mexit\x1b[0m or press \x1b[32;1mctrl+d\x1b[0m to leave. \x1b[32;1mhelp\x1b[0m may help.")
prompt := "\x1b[33;1mlauncher>\x1b[0m "
for {
// completion
var symbols = []string{"addoperation", "deloperation", "exit", "help", "init",
"json", "launch", "load", "details", "filechecker", "netstat",
"setname", "settarget", "settimes", "sign", "times"}
readline.Completer = func(query, ctx string) []string {
var res []string
for _, sym := range symbols {
if strings.HasPrefix(sym, query) {
res = append(res, sym)
}
}
return res
}
input, err := readline.String(prompt)
if err == io.EOF {
break
}
if err != nil {
fmt.Println("error: ", err)
break
}
orders := strings.Split(strings.TrimSpace(input), " ")
switch orders[0] {
case "addoperation":
if len(orders) != 2 {
fmt.Println("Wrong arguments. Expects 'addoperation <module_name>'")
fmt.Println("example: addoperation filechecker")
break
}
// attempt to call ParamsCreator from the requested module
// ParamsCreator takes care of retrieving using input
var operation mig.Operation
operation.Module = orders[1]
if _, ok := mig.AvailableModules[operation.Module]; ok {
// instanciate and call module parameters creation function
modRunner := mig.AvailableModules[operation.Module]()
if _, ok := modRunner.(mig.HasParamsCreator); !ok {
fmt.Println(operation.Module, "module does not provide a parameters creator.")
fmt.Println("You can write your action by hand and import it using 'load <file>'")
break
}
operation.Parameters, err = modRunner.(mig.HasParamsCreator).ParamsCreator()
if err != nil {
fmt.Printf("Parameters creation failed with error: %v\n", err)
break
}
a.Operations = append(a.Operations, operation)
opjson, err := json.MarshalIndent(operation, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("Inserting %s operation with parameters:\n%s\n", operation.Module, opjson)
} else {
fmt.Println("Module", operation.Module, "is not available in this console...")
fmt.Println("You can write your action by hand and import it using 'load <file>'")
}
case "deloperation":
if len(orders) != 2 {
fmt.Println("Wrong arguments. Expects 'deloperation <opnum>'")
fmt.Println("example: deloperation 0")
break
}
opnum, err := strconv.Atoi(orders[1])
if err != nil || opnum < 0 || opnum > len(a.Operations)-1 {
fmt.Println("error: <opnum> must be a positive integer between 0 and", len(a.Operations)-1)
break
}
a.Operations = append(a.Operations[:opnum], a.Operations[opnum+1:]...)
case "details":
fmt.Printf("ID %.0f\nName %s\nTarget %s\nAuthor %s <%s>\n"+
"Revision %.0f\nURL %s\nThreat Type %s, Level %s, Family %s, Reference %s\n",
//.........这里部分代码省略.........
示例13: main
func main() {
var err error
fmt.Println("\x1b[32;1m" + `
## ## _.---._ .---.
# # # /-\ ---|| | /\ __...---' .---. '---'-. '.
# #| | / || | /--\ .-''__.--' _.'( | )'. '. '._ :
# # \_/ ---| \_ \_/ \ .'__-'_ .--'' ._'---'_.-. '. '-'.
### ~ -._ -._''---. -. '-._ '.
# |\ |\ /---------| ~ -.._ _ _ _ ..-_ '. '-._''--.._
# | \| \ / |- |__ | | -~ -._ '-. -. '-._''--.._.--''.
###| \ \/ ---__| | | ~ ~-.__ -._ '-.__ '. '.
##### ~~ ~---...__ _ ._ .' '.
# /\ --- /-\ |--|---- ~ ~--.....--~
# ### /--\ | | ||-\ //
#####/ \ | \_/ | \//__
` + "\x1b[0m")
ctx.Homedir = findHomedir()
// command line options
var config = flag.String("c", ctx.Homedir+"/.migconsole", "Load configuration from file")
var api = flag.String("a", "undef", "API base url (ex: http://localhost:1664/api/v1/)")
var shortnames = flag.Bool("s", false, "Shorten all agent names to first and last 5 characters)")
flag.Parse()
// append a space after completion
readline.CompletionAppendChar = 0x20
if *shortnames {
useShortNames = true
}
if *api != "undef" {
ctx.API.URL = *api
} else {
err := gcfg.ReadFileInto(&ctx, *config)
if err != nil {
panic(err)
}
}
ctx.GPG.Home, err = findGPGHome(ctx)
if err != nil {
panic(err)
}
err = printStatus(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("\nConnected to %s. Exit with \x1b[32;1mctrl+d\x1b[0m. Type \x1b[32;1mhelp\x1b[0m for help.\n", ctx.API.URL)
for {
// completion
var symbols = []string{"action", "agent", "command", "help", "exit", "showcfg", "status",
"search", "where", "and"}
readline.Completer = func(query, ctx string) []string {
var res []string
for _, sym := range symbols {
if strings.HasPrefix(sym, query) {
res = append(res, sym)
}
}
return res
}
input, err := readline.String("\x1b[32;1mmig>\x1b[0m ")
if err == io.EOF {
break
}
if err != nil {
fmt.Println("error: ", err)
break
}
orders := strings.Split(strings.TrimSpace(input), " ")
switch orders[0] {
case "action":
if len(orders) == 2 {
if orders[1] == "new" {
var a mig.Action
err = actionLauncher(a, ctx)
} else {
err = actionReader(input, ctx)
}
if err != nil {
log.Println(err)
}
} else {
fmt.Println("error: 'action' order takes one argument; " +
"either 'new' to enter launcher mode, or an action ID to enter reader mode.")
}
case "agent":
err = agentReader(input, ctx)
if err != nil {
log.Println(err)
}
case "command":
err = commandReader(input, ctx)
if err != nil {
log.Println(err)
}
case "exit":
fmt.Printf("exit\n")
goto exit
case "help":
//.........这里部分代码省略.........
示例14: REPL
func REPL(c Context) (Context, error) {
tokens := []string{}
leftCount := 0
rightCount := 0
for {
prompt := mainPrompt
if len(tokens) > 0 {
prompt = incompletePrompt
}
line, err := readline.String(prompt)
if err != nil {
return nil, err
}
if line != "" {
line = strings.TrimRight(line, "\r\n ")
readline.AddHistory(line)
if line == "quit" {
return c, nil
}
temp := Tokenize(line)
for _, t := range temp {
if t == "(" || t == "'(" {
leftCount += 1
} else if t == ")" {
rightCount += 1
}
}
tokens = append(tokens, temp...)
if leftCount == rightCount {
nodes, err := Parse(tokens)
if err != nil {
fmt.Println("error: ", err)
} else {
for _, n := range nodes {
r := n.Eval(c)
if r.Type() == "error" {
fmt.Println("error:", r.Value().(string))
break
}
if r != NIL {
fmt.Println(r)
}
}
}
leftCount = 0
rightCount = 0
tokens = []string{}
}
}
}
}
示例15: commandReader
// commandReader retrieves an command from the API using its numerical ID
// and enters prompt mode to analyze it
func commandReader(input string, cli client.Client) (err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("commandReader() -> %v", e)
}
}()
inputArr := strings.Split(input, " ")
if len(inputArr) < 2 {
panic("wrong order format. must be 'command <commandid>'")
}
cmdid, err := strconv.ParseFloat(inputArr[1], 64)
if err != nil {
panic(err)
}
cmd, err := cli.GetCommand(cmdid)
if err != nil {
panic(err)
}
fmt.Println("Entering command reader mode. Type \x1b[32;1mexit\x1b[0m or press \x1b[32;1mctrl+d\x1b[0m to leave. \x1b[32;1mhelp\x1b[0m may help.")
fmt.Printf("Command %.0f ran on agent '%s' based on action '%s'\n",
cmd.ID, cmd.Agent.Name, cmd.Action.Name)
prompt := fmt.Sprintf("\x1b[36;1mcommand %d>\x1b[0m ", uint64(cmdid)%1000)
for {
// completion
var symbols = []string{"exit", "help", "json", "found", "pretty", "r", "results"}
readline.Completer = func(query, ctx string) []string {
var res []string
for _, sym := range symbols {
if strings.HasPrefix(sym, query) {
res = append(res, sym)
}
}
return res
}
input, err := readline.String(prompt)
if err == io.EOF {
break
}
if err != nil {
fmt.Println("error: ", err)
break
}
orders := strings.Split(strings.TrimSpace(input), " ")
switch orders[0] {
case "exit":
fmt.Printf("exit\n")
goto exit
case "help":
fmt.Printf(`The following orders are available:
exit exit this mode
help show this help
json show the json of the command
r refresh the command (get latest version from upstream)
results <found> print the results. if "found" is set, only print results that have at least one found
`)
case "json":
var cjson []byte
cjson, err = json.MarshalIndent(cmd, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", cjson)
case "r":
cmd, err = cli.GetCommand(cmdid)
if err != nil {
panic(err)
}
fmt.Println("Reload succeeded")
case "results":
found := false
if len(orders) > 1 {
if orders[1] == "found" {
found = true
} else {
fmt.Printf("Unknown option '%s'\n", orders[1])
}
}
err = client.PrintCommandResults(cmd, found, false)
if err != nil {
panic(err)
}
case "":
break
default:
fmt.Printf("Unknown order '%s'. You are in command reader mode. Try `help`.\n", orders[0])
}
readline.AddHistory(input)
}
exit:
fmt.Printf("\n")
return
}