Golang : Launch Mac OS X Preview (or other OS) application from your program example

Problem :

You are building a program that specifically target an operating system and you want to invoke another application from the Operating System. For instance, you want to invoke the Mac OS X's Preview Application to display an image generated by your program. This example can also be used to invoke other applications as long the full path to the application can be provided and of course with the right permission.

Solution :

Use the exec.Command() function to call the open command (open files from a shell) and in turn to open the target file with Preview.app.

Here is an example code on how to do that.

 package main

 import (

 func displayImage(fileName string) {
 command := "open"
 arg1 := "-a"
 arg2 := "/Applications/Preview.app"
 cmd := exec.Command(command, arg1, arg2, fileName)
 err := cmd.Run()

 if err != nil {

 func main() {

 imgFile, err := os.Open("QRImgGA.png") // change here

 if err != nil {

 defer imgFile.Close()


You will need to change the image file name to your own file and execute this program from a terminal. If everything goes well. The image file will be opened in Preview.app

Reference :

From the terminal, run >open -help :

 Usage: open [-e] [-t] [-f] [-W] [-R] [-n] [-g] [-h] [-b <bundle identifier>] [-a <application>] [filenames] [--args arguments]
 Help: Open opens files from a shell.
 By default, opens each file using the default application for that file.
 If the file is in the form of a URL, the file will be opened as a URL.
 -a Opens with the specified application.
 -b Opens with the specified application bundle identifier.
 -e Opens with TextEdit.
 -t Opens with default text editor.
 -f Reads input from standard input and opens with TextEdit.
 -F  --fresh Launches the app fresh, that is, without restoring windows. Saved persistent state is lost, excluding Untitled documents.
 -R, --reveal Selects in the Finder instead of opening.
 -W, --wait-apps Blocks until the used applications are closed (even if they were already running).
 --args All remaining arguments are passed in argv to the application's main() function instead of opened.
 -n, --new Open a new instance of the application even if one is already running.
 -j, --hide Launches the app hidden.
 -g, --background  Does not bring the application to the foreground.
 -h, --header Searches header file locations for headers matching the given filenames, and opens them.

By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.