'How to alert() in Go to show messagebox

In javascript, if we want to show pop up messagebox with custom message in browser, we can use alert("message") function.

How to do it in Go?



Solution 1:[1]

Log in go with the log package or the fmt package, using log.Printf or log.Println for example.

Solution 2:[2]

I made a very simple package to do this.

There are other packages (like sqweek's) with more features, but I was just after something simple for startup errors.

Download it with go get -u tawesoft.co.uk/go

Then use it like this:

package main

import "tawesoft.co.uk/go/dialog"

func main() {
    dialog.Alert("Message")
    dialog.Alert("There are %d lights", 4)
}

Caveats:

  • Only supports windows and linux at the moment (contribute)

Update

I've seen a few people misusing this when writing server-side code. This messagebox will only appear on the computer running the Go program. If you are displaying a HTML page and want a messagebox to show up on the user's computer, you need to output JavaScript code for an alert on the page the user is visiting instead!

Solution 3:[3]

For the Windows operating system, you can use user32.dll to help you, like below.

package main

import ("fmt";"syscall";"unsafe")

func main() {
    // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messageboxw
    var user32DLL = syscall.NewLazyDLL("user32.dll")
    var procMessageBox = user32DLL.NewProc("MessageBoxW") // Return value: Type int
    const (
        MB_OK          = 0x00000000
        MB_OKCANCEL    = 0x00000001
        MB_YESNO       = 0x00000004
        MB_YESNOCANCEL = 0x00000003
    )

    // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messageboxw#return-value
    const (
        IDCANCEL = 2
        IDYES    = 6
        IDNO     = 7
    )
    lpCaption, _ := syscall.UTF16PtrFromString("Done Title")      // LPCWSTR
    lpText, _ := syscall.UTF16PtrFromString("This test is Done.") // LPCWSTR
    responseValue, _, _ := procMessageBox.Call(uintptr(0x00),
        uintptr(unsafe.Pointer(lpText)),
        uintptr(unsafe.Pointer(lpCaption)),
        uintptr(MB_YESNOCANCEL))
    if responseValue == IDYES {
        fmt.Printf("select Yes")
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kenny Grant
Solution 2
Solution 3