Guide / 11 — Go Logic

Server Handlers

For complex HTTP methods (POST, PUT, DELETE, etc.) or JSON API responses, use the stew.server.go file.

stew.server.go File

The stew generate scanner automatically detects all exported functions in stew.server.go whose names correspond to HTTP methods (Get, Post, Put, Delete, Patch). They are automatically registered in the router for the current directory.

// pages/users/stew.server.go
package users

import (
    "encoding/json"
    "net/http"
)

// Automatically registers: POST /users
func Post(w http.ResponseWriter, r *http.Request) {
    var body struct{ Name string }
    json.NewDecoder(r.Body).Decode(&body)
    
    // ... Business logic ...
    
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}

// Automatically registers: DELETE /users
func Delete(w http.ResponseWriter, r *http.Request) {
    id := r.PathValue("id")
    // ... deletion ...
}

Priority Rules

⚠️ GET Route Conflict: If both a @page.stew file (which generates a stew.page.go) AND a Get function in stew.server.go exist in the same directory, the Stew page takes priority for handling GET requests. The server's Get function will be ignored.
  • Encapsulation: Separate form processing and API logic from the template display code in .stew files.
  • Isomorphism: The @page.stew file handles the display (GET), while stew.server.go handles mutations (POST).
  • Go Standards: You write standard http.HandlerFunc functions, making it easy to use third-party packages.

Redirection & HTMX

When using HTMX to submit a form, you can use HTMX headers to force client-side redirections from a Post function:

func Post(w http.ResponseWriter, r *http.Request) {
    // ...
    w.Header().Set("HX-Location", "/success-page")
    w.WriteHeader(http.StatusOK)
}