Build Your First App
Build Your First App
This document uses the official scaffold template (frontend pages plus a Go backend) as its baseline and walks you through the project structure of a GM Desktop micro-app, the frontend/backend communication mechanism, and the local rapid development flow.
When this applies
- You have already created a micro-app in the console and have its dedicated Git repository
- You want to quickly grasp the project layout, frontend/backend debugging, and the minimal coding loop
- You are building secondary business logic on top of the official Go scaffold
Before you start
1. Create an app and get the scaffold
When you create an app in the GM Desktop Developer Center, choose a frontend template and enable the Go backend template as needed, and you get the full scaffold code already initialized:
Creation steps
- Sign in to the Developer Center
- Click "Create new app" in "Control Panel" or "App Management"
- Fill in the basic app information, and when choosing the tech stack select a frontend template and tick the Go backend template
- Click "Create app"; the system generates a dedicated Git repository for you
If you are not yet familiar with the app creation flow, read the app template creation guide first.
2. Standard project directory structure
After cloning the Git repository locally, you see the following clean and standardized micro-app project layout (frontend and backend live in the same repository):
micro-app root/
├── web/ # Frontend project directory
│ ├── index.html # Frontend page entry (demonstrates $gm calls and RPC requests)
│ ├── build.sh # Frontend automated build and packaging script
│ └── README.md # Frontend notes
├── backend/ # Go backend project directory (Go 1.24+)
│ ├── main.go # Program entry: parse the socket path and start the RPC Server
│ ├── Makefile # Backend build, run, and cross-platform packaging scripts
│ ├── config.json # Environment configuration (test/prod environments)
│ ├── go.mod / go.sum # Go module dependency definitions
│ ├── i18n/ # Internationalization language packs (zh-CN.ini / en.ini)
│ ├── internal/ # Core business logic (strictly layered architecture)
│ │ ├── common/ # App constants (AppName, path rules, error codes)
│ │ ├── dto/ # Request and response structs (XxxReq / XxxResp)
│ │ ├── handler/rpc/ # RPC method registration and request handlers (access layer)
│ │ ├── service/ # Core business logic implementation (factory pattern)
│ │ ├── model/ # Business data entity definitions
│ │ └── core/adapter/ # Infrastructure adapters (DB, low-level commands, etc.)
│ └── pkg/ # Shared utility libraries (pkg/files, pkg/rpcutil)
├── install.sh # App install/initialization script (optional)
├── makefile # Root build orchestration file
└── README.md # Project documentationCore communication mechanism
Frontend/backend communication in a GM Desktop micro-app uses a Unix Domain Socket + JSON-RPC 2.0 architecture that is lightweight, high-performance, and free of port conflicts:
[ Micro-app frontend (web) ]
│ $gm.request('hello', { name: '极目' })
▼
[ GM Desktop client main process ]
│ Transparent proxy forwarding (Unix Socket file)
▼
[ Go backend daemon (backend) ] (responds through the method routes registered with simplejrpc-go)- No network port usage: communication lands on a local socket file, so it never competes with other services for a port.
- No CORS concerns: frontend and backend requests are bridged safely by the desktop client, so during development you do not need to configure tedious proxies and cross-origin headers.
- Built-in health check: the Go backend template implements and registers a
pingmethod by default, so the client can check whether the backend is alive.
Core code implementation
1. Go backend service (based on simplejrpc-go)
The backend template already ships a complete RPC service bootstrap skeleton and standard route registration.
Program entry (backend/main.go)
In main.go, the program calls common.DefaultSockPath() to resolve the socket address; simplejrpc-go manages socket listening underneath and supports graceful exit with logging when it receives SIGINT / SIGTERM:
package main
import (
"fmt"
"github.com/DemonZack/simplejrpc-go/core"
"app-skeleton-backend-go/internal/common"
"app-skeleton-backend-go/internal/handler/rpc"
)
func main() {
// Resolve the socket path for the current runtime (./tmp/app.sock for local debugging, the platform path after installation)
sock := common.DefaultSockPath()
// Create the RPC Server and register services
server := rpc.NewServer()
// Start the service (blocks; receives SIGINT/SIGTERM and exits gracefully)
if err := server.Start(sock); err != nil {
core.Container.Log().Error(fmt.Sprintf("启动RPC服务器失败: %v", err))
return
}
core.Container.Log().Info(fmt.Sprintf("服务启动成功, socket: %s", sock))
}RPC route registration and handlers (internal/handler/rpc/)
Following the layering convention, a handler only parses parameters → calls the Service → returns the result, and carries no concrete business logic.
- Define and register all routes together in
server.go(⚠️pingis the platform health check endpoint; never modify or delete it):
// internal/handler/rpc/server.go
package rpc
import (
"github.com/DemonZack/simplejrpc-go/net/gsock"
)
// RegisterHandles registers all RPC handlers (camelCase is recommended for route names)
func (s *Server) RegisterHandles(ds interface {
RegisterHandle(name string, handler func(*gsock.Request) (any, error), middlewares ...gsock.RPCMiddleware)
}) {
// Basic endpoints (⚠️ ping is the platform health check endpoint; never delete or modify it)
ds.RegisterHandle("ping", s.Ping)
// Business endpoints
ds.RegisterHandle("hello", s.Hello)
ds.RegisterHandle("getItemList", s.GetItemList)
ds.RegisterHandle("createItem", s.CreateItem)
ds.RegisterHandle("deleteItem", s.DeleteItem)
}
// Ping heartbeat check — GMSSH platform health check endpoint (do not delete); never add slow logic here
func (s *Server) Ping(req *gsock.Request) (any, error) {
return "pong", nil
}- Handle frontend requests in the specific handler files (such as
example_handler.go):
// internal/handler/rpc/example_handler.go
package rpc
import (
"app-skeleton-backend-go/internal/dto"
"app-skeleton-backend-go/internal/service"
"app-skeleton-backend-go/pkg/rpcutil"
"github.com/DemonZack/simplejrpc-go/gsock"
)
// Hello is a sample handler
func (s *Server) Hello(req *gsock.Request) (any, error) {
var args dto.HelloReq
// Parse the JSON-RPC parameters into the struct automatically and set the i18n language context per request
if err := rpcutil.ParseParams(req, &args); err != nil {
return nil, err
}
// Call the business Service and return the data
return service.NewExampleService().Hello(args)
}2. Frontend page calls (web/index.html)
Through the global $gm client bridge that GM Desktop injects, the frontend page can issue RPC calls to the Go backend directly:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>微应用前端示例</title>
<script>
// Call the Go backend once the page has finished loading
async function testCall() {
if (!window.$gm || !window.$gm.request) {
alert('请在极目桌面客户端中运行该页面');
return;
}
try {
// 1. Test the backend health check
const pingRes = await window.$gm.request('ping');
console.log('健康检查响应:', pingRes);
// 2. Call the business hello method and pass parameters
const helloRes = await window.$gm.request('hello', { name: '极目桌面开发者' });
document.getElementById('result').innerText = JSON.stringify(helloRes, null, 2);
} catch (err) {
console.error('RPC 请求失败:', err);
}
}
</script>
</head>
<body>
<h1>极目桌面微应用</h1>
<button onclick="testCall()">调用 Go 后端接口</button>
<pre id="result">等待调用...</pre>
</body>
</html>Local rapid debugging and running
After cloning the scaffold locally, you can quickly self-test it or hook it into GM Desktop for development in the following ways:
1. Start the backend locally
Enter the backend directory and run:
cd backend
# Download and tidy the Go dependencies
make deps
# Start the local development service (listens on ./tmp/app.sock by default)
make runWhen the terminal prints logs like the following, the backend socket service has started:
[INFO] RPC server listening on ./tmp/app.sock
[INFO] Methods registered: ping, hello, getItemList, createItem, deleteItem2. Automated build and compilation
When development is finished and you need to package for release:
- Package the frontend:
cd web && ./build.sh - Cross-compile the Linux backend executable:
cd backend && make build-linux - One-command packaging from the root:The artifacts are consolidated into the
make alldist/directory automatically; once everything is ready, submit them for review and release.
Next step
To actually link the code you are developing locally inside the GM Desktop client and turn on live debugging, go to Debugging - DevTools.
