How to Expose Golang Function to the JavaScript - Golang Web Development

Опубликовано: 03 Март 2025
на канале: Maharlikans Code
859
17

In this Golang Web Development Series #13, we will learn how to expose the Golang's Function to the JavaScript side to be executed directly with step by step guide here in Golang's Web Development Series.

Example Syntax on How to Build Golang WASM in different OS:
BUILD WASM IN UBUNTU:
GOOS=js GOARCH=wasm go build -o /var/www/html/maharlikanscode.com/public_html/static/assets/js/auth/auth.wasm main.go

BUILD WASM IN WINDOWS:
go build -o "C:\maharlikans_code\go\Golang Web Development\gowebapp\static\assets\js\auth\auth.wasm" main.go

Get Linode Account:
https://www.linode.com/?r=6aae17162e9...

If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode

#MaharlikansCode
#GolangWebDevelopment13
#GolangWebAssembly
#GoWASM
#GolangFunctionExposeToJS
#GolangTutorial
#LearnGolangWebDevelopment
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper

Source Codes:
package main

import (
"fmt"
"strings"
"syscall/js"
)

func login(this js.Value, args []js.Value) interface{} {
jsDoc := js.Global().Get("document")
if !jsDoc.Truthy() {
return js.Global().Call("eval", `Swal.fire("Oops!, Error", "Unable to get document objects", "error");`)
}
username := jsDoc.Call("getElementById", "username")
if !username.Truthy() {
return js.Global().Call("eval", `Swal.fire("Username is Required!", "Unable to get username object", "error");`)
}
password := jsDoc.Call("getElementById", "password")
if !password.Truthy() {
return js.Global().Call("eval", `Swal.fire("Password is Required!", "Unable to get password object", "error");`)
}

var pUserName string = username.Get("value").String()
var pPassword string = password.Get("value").String()

if len(strings.TrimSpace(pUserName)) == 0 {
return js.Global().Call("eval", `Swal.fire("Username is Required!", "Please enter your username!", "error");`)
}
if len(strings.TrimSpace(pPassword)) == 0 {
return js.Global().Call("eval", `Swal.fire("Password is Required!", "Please enter your password!", "error");`)
}
return nil
}

func exposeGoFuncJS() {
// Exposing the following Go Functions to Javascript client side
js.Global().Set("login", js.FuncOf(login))
}

func main() {
fmt.Println("Welcome to Maharlikans WASM tutorials")
c := make(chan bool, 1)

// Start exposing this following Go functions to JS
exposeGoFuncJS()
lt-c
}