Home > database >  Go Lang - How to build command line menu in Go
Go Lang - How to build command line menu in Go

Time:11-19

I am building a CLI app which interacts with humans on a CLI based menu. e.g Sample Menu Picture

I wrote the code using the following package https://github.com/dixonwille/wmenu.

It is working as expected but I am lost how to retrieve an index of the selected menu item and return it back to the main() function.

I highly appreciate any tips or helpful links.

Thank you

mS


import (
    "fmt"
    "log"
    "os"

    "github.com/dixonwille/wmenu"
)

func createMenu(p string, m []string) {

    optFunc := func(option wmenu.Opt) error {
        fmt.Println("")
        fmt.Println("Option chosen: ", option.ID, option.Text)
        return nil
    }

    menu := wmenu.NewMenu(p)
    menu.ChangeReaderWriter(os.Stdin, os.Stdout, os.Stderr)
    for i, m := range m {
        menu.Option(m, i, false, optFunc)

    }
    err := menu.Run()
    if err != nil {
        log.Fatal(err)
    }

    // return i or option.ID
    // index of a menu item
}

func main() {

    prompt := "Select a Fruit"
    menuitems := []string{"Apple", "Orange", "Mango"}

    createMenu(prompt, menuitems)

    // index := createMenu(prompt, menuitems)
    // fmt.Println("Fruit Selected ",menuitems[index])
}

CodePudding user response:

Here is the self-explanatory working example with minimal changes:

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/dixonwille/wmenu"
)

type userInput struct {
    option wmenu.Opt
}

func (u *userInput) optFunc(option wmenu.Opt) error {
    u.option = option
    return nil
}

func createMenu(p string, m []string, u *userInput) {
    menu := wmenu.NewMenu(p)
    menu.ChangeReaderWriter(os.Stdin, os.Stdout, os.Stderr)
    for i, m := range m {
        menu.Option(m, i, false, u.optFunc)

    }
    err := menu.Run()
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    prompt := "Select a Fruit"
    menuitems := []string{"Apple", "Orange", "Mango"}
    u := &userInput{}
    createMenu(prompt, menuitems, u)
    fmt.Println("")
    fmt.Println("Option chosen: ", u.option.ID, u.option.Text)
}

I don't think that this is the way the library was designed to be used, though.

  •  Tags:  
  • go
  • Related