Guide / 08 β€” Go Logic

goscript server

The <goscript> (or <goscript server>) block contains Go logic executed only on the server during the HTTP rendering of the page.

Basic Syntax

<goscript>
    import "database/sql"
    import "fmt"

    // Standard Go code β€” DB access, sessions, calculations, etc.
    db, _ := sql.Open("sqlite3", "./data.db")
    rows, _ := db.Query("SELECT name FROM users LIMIT 10")
    defer rows.Close()

    var users []string
    for rows.Next() {
        var name string
        rows.Scan(&name)
        users = append(users, name)
    }

    title := fmt.Sprintf("%d users", len(users))
</goscript>

<h1>{{ title }}</h1>

{{ each users as name, i }}
    <p>{{ i }}. {{ name }}</p>
{{ end }}

Rules and Behaviors

πŸ“¦ Imports

Each import "pkg" line is extracted by the compiler and added to the top of the generated Go file. The compiler only links packages actually used in the generated code.

πŸ”€ Variables

Variables declared with := are available throughout the page template (in {{ }} expressions and {{ if }}/{{ each }} blocks).

πŸ— Struct Types

type Xxx struct {} declarations are extracted at the package level (outside the render function), which is required by Go.

🚫 Isolation

Server code is never accessible on the client side. There is no leakage of server logic into Wasm. Communication occurs solely through JSON serialization.

Importing Stew Components

To use a component in a page, import it within the <goscript> block using the relative path to the .stew file:

<goscript>
    import "./component/Card.stew"
    import "../shared/Avatar.stew"
</goscript>

<Card Title="Hello" Description="World" />

The compiler resolves the path into a Go package import corresponding to the folder.

Sharing Data via data.Store

The data.Store field is a free-form map[string]any. It can be populated on the server and automatically serialized for the Wasm client:

<goscript>
    // Server-side: Populate the Store
    data.Store["Title"] = "My App"
    data.Store["Version"] = "1.0"
</goscript>

This data is injected as JSON into the HTML as <script id="stew-pagedata">{...}</script> and can be retrieved on the Wasm side with wasm.GetPageDataJSON().