Use Cli based Utilties and application with golang



Actually, this post is about " use cli based utilities and application with golang", but I will explain it using the example of the 7zip.

The best way I found for zip extraction is using the 7zip cli. This is just sample how you can use any cli based application with your golang project. I will explain it using the example of 7zip cli.



( I am assuming that you have basic knowledge of golang )

What we are going to do is we will make cli command calls from our golang app using the os/exec package

For details of os/exec package please visit this official doc.


Let's see the code of unzipping of the archive using cli and golang



cmd := exec.Command("7z","e", "path-to-file")

err := cmd.Run()

if err != nil {
 fmt.Println("error during extraction:" ,err.Error())
 continue
}



In this code first, we are getting the command struct for our cli based process.


Here Command takes the name of cli utility as the first argument like 7z or echo.

For the simplest example, 
if you want to run echo command through the go app you should pass arguments like this to exec.Command
cmd := exec.Command("echo", "Hello world")


After the name of cli utility, you have to provide the arguments required by that utility.

Each argument defined by be strings.
In our example, the name is 7z while e and path to file is an argument.


Next, we have to run that cmd, for this there are three options


cmd.Run()
This command will run the command and wait until the process is done and will return err, if occurs any.

cmd.Output()
Output() function runs the command as well as returns the standard output.

cmd.Start()
Start() will just start the process but don't wait for finishing and will return an error when the process will finish.


Like our example, if you are going to make tool that is going to extract file you might need something like this



wd := fullpath to the output directory for extraction

cmd := exec.Command("7z","e", filepath.Join(wd,myfile.Name())
        ,"-o"+wd)

err := cmd.Run()

if err != nil {
 fmt.Println("error during extraction :",err.Error())
 continue
}


For production code, i am suggesting the use of full path of source zip as well as a full path to the location where you want to extract. The reason behind it is that if you go for the relative path it will use the path relative to the path of the console in which app runs.



Here 7zip is just example. You can use any other cli base application with golang this way. I used it when I have to do work with pdf where pdf utility was written in Java and having cli interface available.

Comments

Popular Posts