Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

1.4 KB
Raw Blame
package web

import (
	"bytes"
	"context"
	"html/template"
	"log/slog"

	"github.com/SigNoz/signoz/pkg/errors"
)

// Field names map to the HTML attributes they populate in the template:
//   - BaseHref  → <base href="[[.BaseHref]]" />
//   - Settings  → window.signozBootData = { settings: [[.Settings]] }
type TemplateData struct {
	BaseHref string

	// Settings is the pre-serialized JSON of web.Settings for injection into a
	// <script> block. The template.JS type prevents html/template from
	// HTML-escaping the value.
	Settings template.JS
}

// If the template cannot be parsed or executed, the raw bytes are
// returned unchanged and the error is logged.
func NewIndex(ctx context.Context, logger *slog.Logger, name string, raw []byte, data TemplateData) []byte {
	result, err := NewIndexE(name, raw, data)
	if err != nil {
		logger.ErrorContext(ctx, "cannot render index template, serving raw file", slog.String("name", name), errors.Attr(err))
		return raw
	}

	return result
}

func NewIndexE(name string, raw []byte, data TemplateData) ([]byte, error) {
	tmpl, err := template.New(name).Delims("[[", "]]").Parse(string(raw))
	if err != nil {
		return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot parse %q as template", name)
	}

	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, data); err != nil {
		return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot execute template for %q", name)
	}

	return buf.Bytes(), nil
}