Skip to content

Mini programs and mini games

Build Go apps as WeChat, QQ, Alipay and Douyin mini programs and mini games, preview and upload them, and reach their hosts’ APIs.

nsgo build -target miniprogram_wechat -run
nsgo dev -target miniprogram_alipay

Each target writes a project for its platform’s developer tool, also in dist/releases/miniprogram/<platform>, which -run and dev open; dev builds again as you save, and the tool reloads:

Target Platform Tool
miniprogram_wechat WeChat WeChat DevTools, with its service port on (Settings, Security)
miniprogram_qq QQ QQ’s developer tool, on macOS
miniprogram_alipay Alipay Alipay’s Mini Program Studio, on macOS
miniprogram_douyin Douyin and ByteDance’s other apps Douyin’s developer tool, on macOS

miniprogram.appid gives the mini program’s AppID on each platform (wechat, qq, alipay, douyin); without one, WeChat DevTools previews it with its tourist AppID and the other tools ask for one. On WeChat, -run and each dev rebuild close and auto-open the project through the CLI, so DevTools compiles the fresh files. This was checked with DevTools 2.01.2510290. The platform’s navigation bar shows the app’s title; with custom_navigation, the app fills the page and its safe area keeps it clear of the menu button. Set miniprogram.wechat_speech_plugin to a plugin version (such as "0.3.5") to declare WeChat’s official WechatSI text-to-speech plugin (wx069ba97219f66d99) in WeChat’s app.json after enabling it in the WeChat MP console. The app reads the phone’s OS with Env.Simulated true, as on the web with --nsgo-os: a stack’s pages show their own Header, as no system header replaces it. crypto/rand is seeded from the platform’s secure random source (wx.getRandomValues, tt.getRandomValues) before the app starts. Where the host has none, the app still starts, but crypto/rand is seeded from weak entropy (the time and Math.random) and Env.HasSecureRandom() is false: on Alipay, which has no such source, in Douyin’s sandbox and on a Douyin base library before 2.87.0. An app that makes keys, tokens or other secrets should check it and make them on its server, or turn the feature off, when it is false. QQ, Alipay and Douyin have not been tried in their tools yet, and Alipay does not yet take back through the app, keyframes or the keyboard’s height.

Mini programs are experimental. A mini program runs Go apps alone, and the platforms hold the app’s compressed module to 2 MB — an app of a few screens on base fits, as examples/gallery-miniprogram does, one of ui‘s controls does not yet, and build says when one does not. Web views (<web-view> fills a page of its own), custom native components and shaders (nsgo_noshader) are unavailable and report errors.ErrUnsupported (core.CodeUnavailable), and build and check warn when the app compiles a shader or links gpu, as MustCompileWGSL and MustCompileShader then panic as it starts; app font files (loadFontFace), tinted images, off-baseline inline attachments, selection areas and <video> playback are wired across all four platforms’ templates though still unchecked in vendor DevTools.

On WeChat a canvas (core.Canvas) that animates or is redrawn several times a second draws straight onto a canvas of its own in the page each time it changes; one drawn once or now and then, such as an icon, stays a picture. QQ, Alipay and Douyin show it as a picture instead: each change is encoded as a PNG and sent to the page, which for a full-screen canvas costs a few megabytes a frame, so a canvas redrawn every frame plays as a slideshow there, and build and dev warn when a game: true app targets them. Build a real-time game as a mini game, or for miniprogram_wechat.

nsgo publish miniprogram previews or uploads a WeChat or Douyin build, minigame_wechat, minigame_douyin, miniprogram_wechat or miniprogram_douyin, through the platform’s own command line tool. It takes the project in dist/releases/minigame/<platform> or dist/releases/miniprogram/<platform>, or the built project directory (the one holding project.config.json) given in place of the app’s:

nsgo build -target minigame_wechat
nsgo publish miniprogram -target minigame_wechat -check
nsgo publish miniprogram -target minigame_wechat -preview qr.png
nsgo publish miniprogram -target minigame_wechat -version 1.2.0 -desc "New levels"

Without -preview it uploads -version (major.minor.patch, else the app’s version) with -desc, at most 200 characters, else nsgo <version>, for the platform’s review. -preview writes the preview’s QR code to the PNG file and prints its file:// URL; -check only checks that this machine can upload. The AppID is NSGO_MINIPROGRAM_APP_ID, else the one build gives the project: a mini program’s miniprogram.appid.<platform>, a mini game’s minigame.appid.<platform>, else the AppID its built project.config.json keeps, else miniprogram.appid.<platform> with the same warning; else the one the project was built with; the tourist AppID cannot upload, and the command refuses it.

Platform Tool on PATH Signs in with
WeChat, with NSGO_MINIPROGRAM_UPLOAD_KEY miniprogram-ci (npm install -g miniprogram-ci) the code upload key from the WeChat Official Accounts Platform (Development, Development settings), as PEM text or the path of its file
WeChat, without it WeChat DevTools’ CLI, with its service port on DevTools’ login
Douyin mini games tmg (npm install -g tt-minigame-ide-cli) a tmg login made once on the machine
Douyin mini programs tma (npm install -g tt-ide-cli) NSGO_MINIPROGRAM_UPLOAD_KEY as a CLI token, else a tma login

With the WeChat key, -check previews a throwaway project; when the key’s IP allowlist leaves this machine out, it names the address to add, which every upload refusal does too. Node resolves WeChat’s servers over IPv4 first, as rotating temporary IPv6 addresses make an allowlisted one go stale. A key given as text goes to a private temporary file that the command removes, and errors show neither the key, its path nor a PEM body. Without a WeChat key, -check asks DevTools whether it is logged in; for Douyin mini games it asks tmg version, which needs tmg login; for Douyin mini programs it asks tma check-session for the login, or with a token only stores it, as tma cannot check a token before it is used. tmg and tma exit successfully after a failed step, so the command reads what they print instead: an upload counts only when the tool reports success, a preview only when it wrote the QR code, and a missing login names the login to make. Each step has a time limit: 2 minutes for the check, 5 for a preview, 15 for an upload.

nsgo build -target minigame_wechat -run
nsgo dev -target minigame_douyin

minigame_wechat and minigame_douyin (minigame builds both) run the app as a WeChat or Douyin mini game rather than a mini program, written to dist/releases/minigame/<platform> and opened in the same developer tool as that platform’s mini program, switched to a game project. A mini game has no pages: the app’s views are painted by Go onto the game’s screen canvas each frame something changes, and taps, long presses, presses going down and up, and scrolling with inertia, edge bounce and paging are recognized in Go from the screen’s touches. Canvases are drawn straight onto the screen, and images load with the game’s createImage. Pulling a refreshable scroll view down past its top refreshes it, with an indicator above the content. Layout, appear and style transitions do not animate yet, so the change shows at once, and masks, filters and backdrop filters are not drawn.

A game that compiles shaders (core.CompileWGSL, core.CompileShader and their Must forms) or links gpu is built with the shader compilers, and its screen draws through WebGL 2: shader views, ShaderEffect, canvas shaders and gpu.View draw in their place among the views, at their clip’s box and opacity, and Env.SupportsGPU() is true. build decides this from the packages the game links, not from what it calls, so a package that only holds an uncalled core.CompileShader puts the game on WebGL 2 too; build names that package and call, and minigame.webgl: false keeps the 2D screen and leaves the compilers out whatever the game links, where shaders report errors.ErrUnsupported and the Must compilers panic, while true takes WebGL 2 for a game that compiles none. A game that uses neither stays without the compilers, 0.4 to 0.5 MB smaller compressed, and its screen draws in 2D, which skips the screen-sized texture WebGL 2 uploads on each frame where the views change. WeChat has WebGL 2 on Android from WeChat 8.0.24, and on iOS only in high-performance mode (iOS 15 and later, which ios_high_performance turns on) or high-performance+ mode (iOS 14 and later); WeChat says WebGL 2 in iOS high-performance mode still has problems, so try the features the game uses on an iPhone. build warns when a WeChat game that draws with WebGL 2 leaves ios_high_performance off; a game that needs high-performance mode’s JIT but not shaders sets webgl: false with it. The game tries WebGL 2 on a canvas of its own before the screen takes it, and there is no WebGL 1 fallback, so where it does not work the screen draws in 2D: shader views stay empty, effects show their children, Env.SupportsGPU() is false and gpu.View reports gpu.ErrUnsupported. A frame where only a gpu.View or an animated shader changed draws the views’ 2D drawing from the previous frame; a frame where the views change uploads a screen-sized texture for each run of views between two shader or GPU views. Transitions, screen and navigation shaders, backdrop pictures, a gpu.View’s multisampling and its rounded corners are not drawn, and a lost WebGL context is not restored.

minigame:
appid: { wechat: wx0123456789abcdef, douyin: tt0123456789abcdef } # the games' own, not the mini programs'
orientation: landscape # portrait (the default) or landscape
ios_high_performance: false # WeChat's iOS high-performance mode, once the MP console enables it
webgl: false # always the 2D screen, without shader compilers; unset decides from the packages the game links
subpackages: # resources moved out of the 4 MB main package
- name: shared
resources: [sprites/chars, audio, ui/title.jpg] # under resources/: files, folders, or path.Match patterns
preload: true # loaded before the game starts
- name: chapter1
resources: ["sprites/monsters/ch1_*", ground/1.jpg] # loaded the first time the game reads one
friend_ranking: true # the open data context package miniprogram's ShowRanking draws in

A mini game is registered apart from its mini program and has an AppID of its own: without minigame.appid, build keeps the AppID the developer tool wrote into the project, and only then takes miniprogram.appid, with a warning. WeChat’s developer tool does not open a game with touristappid, so build warns when a WeChat game has none; a test account’s AppID from the sandbox works until the game has its own. The module goes in the nsgo-app subpackage, loaded before Go starts. The app’s resources go in the main package’s resources/, except those minigame.subpackages moves to subpackages/<name>/resources/: each entry names a subpackage and the files, folders or patterns under resources/ it takes, and build declares it in game.json, refuses a file two subpackages take or an entry that takes none, and records where each resource went for the game. A subpackage with preload: true loads with the module, behind a progress bar in launch_screen’s colors; the others load the first time the game reads one of their files, through Scope.ReadAsset, an image, a sound, a player or a font, once however many ask, and a load that fails is that read’s error; Scope.ReadAsset, sounds, players and fonts try again on the next read, and an image that did not load, whatever kept it, is loaded again the next time the game draws it once a backoff has passed, 2 seconds doubling with each failure up to 2 minutes, or as soon as its subpackage has loaded for another read; Scope.ImageSize and Scope.PrefetchImage load it again at once, its subpackage too, so a Retry button never waits out the backoff. build holds the main package to 4 MB on both platforms (WeChat, Douyin), and the whole game to 30 MB on WeChat or 20 MB on Douyin, which also holds each subpackage to 20 MB, measured after the resources are laid out; when the module does not fit, it is built again without inlining, and build says which package is too large, naming the main package’s biggest resources when that is the one. A tool that groups a game’s resources writes its groups into minigame.subpackages before nsgo build rather than moving files afterwards, which the main package’s limit and the runtime’s map of resources do not allow; nsgo-dev/game does not do this for mini games yet. ios_high_performance sets WeChat’s iOSHighPerformance, which runs WebAssembly with a JIT on iOS and gives it WebGL 2 but holds the game to less memory, and needs the mode enabled for the game in the MP console first. friend_ranking adds NSGo’s open data context, nsgo-open/, and declares it in game.json’s openDataContext, for the friend ranking of package miniprogram (host APIs); both platforms then refuse toDataURL and toTempFilePath on the game’s own canvases, so it is off by default.

The host keeps its capsule, the menu and close buttons, over the screen’s top right corner and takes the touches on it. Env.SafeArea() stays the system’s, so a background can still fill the screen, and miniprogram.MenuButton(cx) gives the capsule’s frame in points (Env.MenuButton() in core), read tracked so it follows a resize or a turn, and zero on every other target: keep buttons and text out of it, for instance by moving a top-right button below or to the left of it.

Sounds, players and audio.NewOutput play through the host’s WebAudioContext and InnerAudioContext from the start, with no tap to unlock them, and pause while the game is in the background; a player’s bytes and data URLs are written to the user data folder for it.

A text field the user taps, or the app focuses, opens the platform’s keyboard, whose own bar above it shows the text being edited (a masked field’s text too); its confirm button submits as the field’s submit behavior says, closing the keyboard blurs the field, and the field shows a caret after its text but no selection. App fonts (nsgo.Fonts, Scope.RegisterFont) are written to the game’s user data folder and loaded with the game’s loadFont. Haptics, the clipboard and opening links work as in mini programs, and there is no back button. Scope.Secrets keeps secrets in WeChat’s encrypted storage from base library 2.21.3, and is unavailable on Douyin, whose storage has no encryption. Mini games get no theme change events, so the appearance is the one the game started with.

net/http, fetch and WebSocket work in a mini game: NSGo puts fetch, Headers, AbortController and WebSocket over the platform’s request and connectSocket on the global Go runs in, so http.DefaultClient and code written for the browser’s APIs run unchanged. Each answer is buffered whole before Go reads it. A release game reaches only the request and socket domains (https and wss) on its allow-list in the MP console, and a request to another fails with the platform’s message, such as net/http: fetch() failed: TypeError: request:fail url not in domain list; the developer tool can skip the check while you develop. WeChat’s request sends no PATCH, which fails before it is sent; redirect: "manual" stops at a redirect only where the platform supports it, and otherwise the redirect is followed; credentials, mode and cache are ignored; WeChat keeps at most 5 sockets open at once. core.Download is unavailable.

Mini games are experimental, with what mini programs lack. Neither platform’s tool has run one yet. crypto/rand is seeded as in mini programs: from the platform’s secure random source where it has one, else from weak entropy with Env.HasSecureRandom() false. Douyin documents no secure source for mini games, so a Douyin mini game may report false until a device confirms otherwise.

Package miniprogram reaches what WeChat’s and Douyin’s mini programs and mini games grow and earn with: the launch query, sharing, hosted data and the friend ranking, ads, virtual payments, subscribe messages and the game club button. Each call answers miniprogram.ErrUnsupported, which wraps errors.ErrUnsupported, unless cx.Env().HasMiniProgramAPI is true for its API: on every other target, on QQ and Alipay, and where the platform has no such API for that kind of app. Answers run on the engine goroutine.

if l, err := miniprogram.LaunchOptions(cx); err == nil {
level.Set(l.Query["level"]) // "3" for a card shared with Query "level=3"
}
miniprogram.OnShow(cx, func(l miniprogram.Launch) { level.Set(l.Query["level"]) })
miniprogram.OnShareRequest(cx, func() miniprogram.ShareCard {
return miniprogram.ShareCard{Title: "Beat level " + level.Get(), Query: "level=" + level.Get()}
})
ad := miniprogram.NewRewardedAd(cx, "adunit-0123456789")
ad.OnClose(func(completed bool) {
if completed {
coins.Set(coins.Get() + 10)
}
})
ad.Show(func(err error) { /* errors.Is(err, miniprogram.ErrUnsupported) off the platforms */ })
API WeChat mini game WeChat mini program Douyin mini game Douyin mini program
LaunchOptions, OnShow, OnShareRequest, ShowShareMenu yes yes yes yes
Share yes — yes —
ShareTicketInfo yes yes — —
SetCloudStorage yes — yes —
ShowRanking with friend_ranking — with friend_ranking —
NewRewardedAd, NewInterstitialAd yes yes yes —
NewBannerAd yes — yes —
RequestPayment, RequestSubscribeMessage yes yes yes —
NewGameClubButton yes — — —

The share menu shares the card OnShareRequest’s function returns, again whenever the signals it reads change; without one it shares the app with the platform’s title and picture. A mini program’s card opens the app with the card’s Query. The menu’s share item stays as the platform has it until the app asks: where the platform leaves it off (WeChat, and Douyin’s mini programs below base library 2.91.0) it shows once the app calls ShowShareMenu or OnShareRequest, and hides again when OnShareRequest’s scope ends unless ShowShareMenu asked; Douyin’s mini programs show it on every page from 2.91.0. Share opens the share sheet from the game’s own button; WeChat reports no result, so its done gets nil once the sheet is asked for. ShowShareMenu(cx, true, …) puts a WeChat group’s share ticket in what a card shared to a group launches with, which ShareTicketInfo turns into data for the app’s server to decrypt, and which ranks that group in ShowRanking.

A friend ranking needs nsgo.yaml‘s minigame.friend_ranking, which adds NSGo’s open data context to the game (building). SetCloudStorage writes the user’s score as JSON whose wxgame (WeChat) or ttgame (Douyin) object holds score and update_time, or as a plain number; ShowRanking has the context draw the friends’ scores under that key, highest first, and an image whose source is miniprogram.RankingImage shows them at the ranking’s size:

miniprogram.SetCloudStorage(cx, map[string]string{"best": fmt.Sprintf(`{"wxgame":{"score":%d,"update_time":%d}}`, best, time.Now().Unix())}, nil)
miniprogram.ShowRanking(cx, miniprogram.Ranking{Key: "best", Width: 300, Height: 400})
core.Image{Source: miniprogram.RankingImage, Style: core.Style{Width: core.Pt(300), Height: core.Pt(400)}}

miniprogram.Current() tells what the app runs as, on every target: Kind is miniprogram.MiniGame, miniprogram.MiniProgram or miniprogram.None, and Platform the host app (miniprogram.WeChat, Douyin, QQ or Alipay). It holds for the whole run, so branch on it to leave out what a platform’s review refuses, such as WeChat’s links to outside the app:

if miniprogram.Current().Kind == miniprogram.None {
children = append(children, ui.Button{Text: "Privacy policy", OnPress: func() { cx.OpenURL(policyURL, nil) }})
}

Mini programs have no open data context, so they rank friends only through their own server. RequestPayment passes the platform’s own fields, which the app’s server signs, and answers core.PurchaseCancelled, core.PurchaseFailed or core.PurchasesUnavailable as in-app purchases do; confirm each order on the server before delivering it. The ads, the game club button and the ranking are drawn by the host over the app, which a screenshot of the app does not show.