Go (Golang) Integration

Integrate PulsePoint with Go's native html/template engine using a `FuncMap` helper.

Go Integration Demo

Ep. 03
Go

FuncMap & Template Composition

04:45

The Implementation

We create a component function that renders a sub-template, injects the properties, and transforms the script tags.

main.go
package main

import (
    "bytes"
    "html/template"
    "net/http"
    "regexp"
)

// 1. Regex to find standard script tags
var scriptRegex = regexp.MustCompile(`<script(?![^>]*\btype=)`)

func main() {
    // 2. Define the Component Helper
    funcMap := template.FuncMap{
        "component": func(name string, data interface{}) template.HTML {
            // Parse the component file
            tmpl, _ := template.ParseFiles("templates/components/" + name + ".html")
            
            // Render to buffer
            var buf bytes.Buffer
            tmpl.Execute(&buf, data)
            
            // Transform <script> to <script type="text/pp">
            output := scriptRegex.ReplaceAllString(buf.String(), `<script type="text/pp"`)
            
            // Return safe HTML
            return template.HTML(output)
        },
    }

    // 3. Register and Serve
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        tmpl := template.New("index.html").Funcs(funcMap)
        tmpl, _ = tmpl.ParseFiles("templates/index.html")
        
        data := map[string]interface{}{
            "User": "Gopher",
            "InitialCount": 10,
        }
        tmpl.Execute(w, data)
    })

    http.ListenAndServe(":8080", nil)
}
templates/index.html
<!-- Usage in Template -->
<body>
    <h1>Hello, {{ .User }}</h1>

    <!-- Load Component -->
    {{ component "counter" . }}
</body>


<!-- templates/components/counter.html -->
<div class="p-4 border rounded">
    <p>Count: {count}</p>
    <button onclick="setCount(count + 1)">+</button>

    <script>
        // Go variable injected into JS state
        const [count, setCount] = pp.state({{ .InitialCount }});
    </script>
</div>
PHP / Prisma PHP Next: Python / FastAPI