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.

feat(apiserver): derive HTTP route prefix from global.external_url (#10943)

Pandeyef298af3885b
diff --git a/cmd/community/server.go b/cmd/community/server.go
index 9b11aab38d..a0f440e4e7 100644
--- a/cmd/community/server.go
+++ b/cmd/community/server.go
@@ -75,7 +75,7 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
},
signoz.NewEmailingProviderFactories(),
signoz.NewCacheProviderFactories(),
- signoz.NewWebProviderFactories(),
+ signoz.NewWebProviderFactories(config.Global),
func(sqlstore sqlstore.SQLStore) factory.NamedMap[factory.ProviderFactory[sqlschema.SQLSchema, sqlschema.Config]] {
return signoz.NewSQLSchemaProviderFactories(sqlstore)
},
diff --git a/cmd/enterprise/server.go b/cmd/enterprise/server.go
index d9e4b3cac2..51841407fe 100644
--- a/cmd/enterprise/server.go
+++ b/cmd/enterprise/server.go
@@ -96,7 +96,7 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
},
signoz.NewEmailingProviderFactories(),
signoz.NewCacheProviderFactories(),
- signoz.NewWebProviderFactories(),
+ signoz.NewWebProviderFactories(config.Global),
func(sqlstore sqlstore.SQLStore) factory.NamedMap[factory.ProviderFactory[sqlschema.SQLSchema, sqlschema.Config]] {
existingFactories := signoz.NewSQLSchemaProviderFactories(sqlstore)
if err := existingFactories.Add(postgressqlschema.NewFactory(sqlstore)); err != nil {
diff --git a/conf/example.yaml b/conf/example.yaml
index 22d1e668d6..e604507709 100644
--- a/conf/example.yaml
+++ b/conf/example.yaml
@@ -6,6 +6,8 @@
##################### Global #####################
global:
# the url under which the signoz apiserver is externally reachable.
+ # the path component (e.g. /signoz in https://example.com/signoz) is used
+ # as the base path for all HTTP routes (both API and web frontend).
external_url: <unset>
# the url where the SigNoz backend receives telemetry data (traces, metrics, logs) from instrumented applications.
ingestion_url: <unset>
@@ -50,8 +52,8 @@ pprof:
web:
# Whether to enable the web frontend
enabled: true
- # The prefix to serve web on
- prefix: /
+ # The index file to use as the SPA entrypoint.
+ index: index.html
# The directory containing the static build files.
directory: /etc/signoz/web
diff --git a/ee/query-service/app/server.go b/ee/query-service/app/server.go
index 3f2f9686bf..ba7223bc38 100644
--- a/ee/query-service/app/server.go
+++ b/ee/query-service/app/server.go
@@ -262,6 +262,20 @@ func (s *Server) createPublicServer(apiHandler *api.APIHandler, web web.Web) (*h
return nil, err
}
+ routePrefix := s.config.Global.ExternalPath()
+ if routePrefix != "" {
+ prefixed := http.StripPrefix(routePrefix, handler)
+ handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch req.URL.Path {
+ case "/api/v1/health", "/api/v2/healthz", "/api/v2/readyz", "/api/v2/livez":
+ r.ServeHTTP(w, req)
+ return
+ }
+
+ prefixed.ServeHTTP(w, req)
+ })
+ }
+
return &http.Server{
Handler: handler,
}, nil
diff --git a/pkg/global/config.go b/pkg/global/config.go
index 39900807ed..f27d39d9c2 100644
--- a/pkg/global/config.go
+++ b/pkg/global/config.go
@@ -2,6 +2,8 @@ package global
import (
"net/url"
+ "path"
+ "strings"
"github.com/SigNoz/signoz/pkg/errors"
@@ -37,5 +39,34 @@ func newConfig() factory.Config {
}
func (c Config) Validate() error {
+ if c.ExternalURL != nil {
+ if c.ExternalURL.Path != "" && c.ExternalURL.Path != "/" {
+ if !strings.HasPrefix(c.ExternalURL.Path, "/") {
+ return errors.NewInvalidInputf(ErrCodeInvalidGlobalConfig, "global::external_url path must start with '/', got %q", c.ExternalURL.Path)
+ }
+ }
+ }
+
return nil
}
+
+func (c Config) ExternalPath() string {
+ if c.ExternalURL == nil || c.ExternalURL.Path == "" || c.ExternalURL.Path == "/" {
+ return ""
+ }
+
+ p := path.Clean("/" + c.ExternalURL.Path)
+ if p == "/" {
+ return ""
+ }
+
+ return p
+}
+
+func (c Config) ExternalPathTrailing() string {
+ if p := c.ExternalPath(); p != "" {
+ return p + "/"
+ }
+
+ return "/"
+}
diff --git a/pkg/global/config_test.go b/pkg/global/config_test.go
new file mode 100644
index 0000000000..83bbef04cf
--- /dev/null
+++ b/pkg/global/config_test.go
@@ -0,0 +1,139 @@
+package global
+
+import (
+ "net/url"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestExternalPath(t *testing.T) {
+ testCases := []struct {
+ name string
+ config Config
+ expected string
+ }{
+ {
+ name: "NilURL",
+ config: Config{ExternalURL: nil},
+ expected: "",
+ },
+ {
+ name: "EmptyPath",
+ config: Config{ExternalURL: &url.URL{Scheme: "https", Host: "example.com", Path: ""}},
+ expected: "",
+ },
+ {
+ name: "RootPath",
+ config: Config{ExternalURL: &url.URL{Scheme: "https", Host: "example.com", Path: "/"}},
+ expected: "",
+ },
+ {
+ name: "SingleSegment",
+ config: Config{ExternalURL: &url.URL{Scheme: "https", Host: "example.com", Path: "/signoz"}},
+ expected: "/signoz",
+ },
+ {
+ name: "TrailingSlash",
+ config: Config{ExternalURL: &url.URL{Scheme: "https", Host: "example.com", Path: "/signoz/"}},
+ expected: "/signoz",
+ },
+ {
+ name: "MultiSegment",
+ config: Config{ExternalURL: &url.URL{Scheme: "https", Host: "example.com", Path: "/a/b/c"}},
+ expected: "/a/b/c",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ assert.Equal(t, tc.expected, tc.config.ExternalPath())
+ })
+ }
+}
+
+func TestExternalPathTrailing(t *testing.T) {
+ testCases := []struct {
+ name string
+ config Config
+ expected string
+ }{
+ {
+ name: "NilURL",
+ config: Config{ExternalURL: nil},
+ expected: "/",
+ },
+ {
+ name: "EmptyPath",
+ config: Config{ExternalURL: &url.URL{Path: ""}},
+ expected: "/",
+ },
+ {
+ name: "RootPath",
+ config: Config{ExternalURL: &url.URL{Path: "/"}},
+ expected: "/",
+ },
+ {
+ name: "SingleSegment",
+ config: Config{ExternalURL: &url.URL{Path: "/signoz"}},
+ expected: "/signoz/",
+ },
+ {
+ name: "MultiSegment",
+ config: Config{ExternalURL: &url.URL{Path: "/a/b/c"}},
+ expected: "/a/b/c/",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ assert.Equal(t, tc.expected, tc.config.ExternalPathTrailing())
+ })
+ }
+}
+
+func TestValidate(t *testing.T) {
+ testCases := []struct {
+ name string
+ config Config
+ fail bool
+ }{
+ {
+ name: "NilURL",
+ config: Config{ExternalURL: nil},
+ fail: false,
+ },
+ {
+ name: "EmptyPath",
+ config: Config{ExternalURL: &url.URL{Path: ""}},
+ fail: false,
+ },
+ {
+ name: "RootPath",
+ config: Config{ExternalURL: &url.URL{Path: "/"}},
+ fail: false,
+ },
+ {
+ name: "ValidPath",
+ config: Config{ExternalURL: &url.URL{Path: "/signoz"}},
+ fail: false,
+ },
+ {
+ name: "NoLeadingSlash",
+ config: Config{ExternalURL: &url.URL{Path: "signoz"}},
+ fail: true,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ err := tc.config.Validate()
+ if tc.fail {
+ assert.Error(t, err)
+ return
+ }
+
+ assert.NoError(t, err)
+ })
+ }
+}
diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.go
index 6d7c1a2540..5ee42a1cbf 100644
--- a/pkg/query-service/app/http_handler.go
+++ b/pkg/query-service/app/http_handler.go
@@ -587,7 +587,6 @@ func (aH *APIHandler) RegisterRoutes(router *mux.Router, am *middleware.AuthZ) {
router.HandleFunc("/api/v1/query_filter/analyze", am.ViewAccess(aH.QueryParserAPI.AnalyzeQueryFilter)).Methods(http.MethodPost)
}
-
func Intersection(a, b []int) (c []int) {
m := make(map[int]bool)
diff --git a/pkg/query-service/app/server.go b/pkg/query-service/app/server.go
index 53d3a59ef4..a3744ff446 100644
--- a/pkg/query-service/app/server.go
+++ b/pkg/query-service/app/server.go
@@ -244,6 +244,20 @@ func (s *Server) createPublicServer(api *APIHandler, web web.Web) (*http.Server,
return nil, err
}
+ routePrefix := s.config.Global.ExternalPath()
+ if routePrefix != "" {
+ prefixed := http.StripPrefix(routePrefix, handler)
+ handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch req.URL.Path {
+ case "/api/v1/health", "/api/v2/healthz", "/api/v2/readyz", "/api/v2/livez":
+ r.ServeHTTP(w, req)
+ return
+ }
+
+ prefixed.ServeHTTP(w, req)
+ })
+ }
+
return &http.Server{
Handler: handler,
}, nil
diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.go
index 2280793c31..5ccd0b30c3 100644
--- a/pkg/signoz/provider.go
+++ b/pkg/signoz/provider.go
@@ -88,9 +88,9 @@ func NewCacheProviderFactories() factory.NamedMap[factory.ProviderFactory[cache.
)
}
-func NewWebProviderFactories() factory.NamedMap[factory.ProviderFactory[web.Web, web.Config]] {
+func NewWebProviderFactories(globalConfig global.Config) factory.NamedMap[factory.ProviderFactory[web.Web, web.Config]] {
return factory.MustNewNamedMap(
- routerweb.NewFactory(),
+ routerweb.NewFactory(globalConfig),
noopweb.NewFactory(),
)
}
diff --git a/pkg/signoz/provider_test.go b/pkg/signoz/provider_test.go
index 9001d76e04..a57c07092c 100644
--- a/pkg/signoz/provider_test.go
+++ b/pkg/signoz/provider_test.go
@@ -8,6 +8,7 @@ import (
"github.com/SigNoz/signoz/pkg/alertmanager/nfmanager/nfmanagertest"
"github.com/SigNoz/signoz/pkg/analytics"
"github.com/SigNoz/signoz/pkg/flagger"
+ "github.com/SigNoz/signoz/pkg/global"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/modules/organization/implorganization"
"github.com/SigNoz/signoz/pkg/modules/user/impluser"
@@ -34,7 +35,7 @@ func TestNewProviderFactories(t *testing.T) {
})
assert.NotPanics(t, func() {
- NewWebProviderFactories()
+ NewWebProviderFactories(global.Config{})
})
assert.NotPanics(t, func() {
diff --git a/pkg/web/config.go b/pkg/web/config.go
index 4feb54835c..c5ab0147d3 100644
--- a/pkg/web/config.go
+++ b/pkg/web/config.go
@@ -8,10 +8,11 @@ import (
type Config struct {
// Whether the web package is enabled.
Enabled bool `mapstructure:"enabled"`
- // The prefix to serve the files from
- Prefix string `mapstructure:"prefix"`
- // The directory containing the static build files. The root of this directory should
- // have an index.html file.
+
+ // The name of the index file to serve.
+ Index string `mapstructure:"index"`
+
+ // The directory from which to serve the web files.
Directory string `mapstructure:"directory"`
}
@@ -22,7 +23,7 @@ func NewConfigFactory() factory.ConfigFactory {
func newConfig() factory.Config {
return &Config{
Enabled: true,
- Prefix: "/",
+ Index: "index.html",
Directory: "/etc/signoz/web",
}
}
diff --git a/pkg/web/config_test.go b/pkg/web/config_test.go
index 9d002ea8c0..6bc18be995 100644
--- a/pkg/web/config_test.go
+++ b/pkg/web/config_test.go
@@ -12,7 +12,6 @@ import (
)
func TestNewWithEnvProvider(t *testing.T) {
- t.Setenv("SIGNOZ_WEB_PREFIX", "/web")
t.Setenv("SIGNOZ_WEB_ENABLED", "false")
conf, err := config.New(
@@ -37,7 +36,7 @@ func TestNewWithEnvProvider(t *testing.T) {
expected := &Config{
Enabled: false,
- Prefix: "/web",
+ Index: def.Index,
Directory: def.Directory,
}
diff --git a/pkg/web/routerweb/provider.go b/pkg/web/routerweb/provider.go
index 6bc3899714..b8ec9e6a89 100644
--- a/pkg/web/routerweb/provider.go
+++ b/pkg/web/routerweb/provider.go
@@ -8,56 +8,55 @@ import (
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
+ "github.com/SigNoz/signoz/pkg/global"
"github.com/SigNoz/signoz/pkg/http/middleware"
"github.com/SigNoz/signoz/pkg/web"
"github.com/gorilla/mux"
)
-const (
- indexFileName string = "index.html"
-)
-
type provider struct {
- config web.Config
+ config web.Config
+ indexContents []byte
+ fileHandler http.Handler
}
-func NewFactory() factory.ProviderFactory[web.Web, web.Config] {
- return factory.NewProviderFactory(factory.MustNewName("router"), New)
+func NewFactory(globalConfig global.Config) factory.ProviderFactory[web.Web, web.Config] {
+ return factory.NewProviderFactory(factory.MustNewName("router"), func(ctx context.Context, settings factory.ProviderSettings, config web.Config) (web.Web, error) {
+ return New(ctx, settings, config, globalConfig)
+ })
}
-func New(ctx context.Context, settings factory.ProviderSettings, config web.Config) (web.Web, error) {
+func New(ctx context.Context, settings factory.ProviderSettings, config web.Config, globalConfig global.Config) (web.Web, error) {
fi, err := os.Stat(config.Directory)
if err != nil {
return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot access web directory")
}
- ok := fi.IsDir()
- if !ok {
+ if !fi.IsDir() {
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "web directory is not a directory")
}
- fi, err = os.Stat(filepath.Join(config.Directory, indexFileName))
+ indexPath := filepath.Join(config.Directory, config.Index)
+ raw, err := os.ReadFile(indexPath)
if err != nil {
- return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot access %q in web directory", indexFileName)
+ return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot read %q in web directory", config.Index)
}
- if os.IsNotExist(err) || fi.IsDir() {
- return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "%q does not exist", indexFileName)
- }
+ logger := factory.NewScopedProviderSettings(settings, "github.com/SigNoz/signoz/pkg/web/routerweb").Logger()
+ indexContents := web.NewIndex(ctx, logger, config.Index, raw, web.TemplateData{BaseHref: globalConfig.ExternalPathTrailing()})
return &provider{
- config: config,
+ config: config,
+ indexContents: indexContents,
+ fileHandler: http.FileServer(http.Dir(config.Directory)),
}, nil
}
func (provider *provider) AddToRouter(router *mux.Router) error {
cache := middleware.NewCache(0)
- err := router.PathPrefix(provider.config.Prefix).
+ err := router.PathPrefix("/").
Handler(
- http.StripPrefix(
- provider.config.Prefix,
- cache.Wrap(http.HandlerFunc(provider.ServeHTTP)),
- ),
+ cache.Wrap(http.HandlerFunc(provider.ServeHTTP)),
).GetError()
if err != nil {
return errors.WrapInternalf(err, errors.CodeInternal, "unable to add web to router")
@@ -75,7 +74,7 @@ func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if err != nil {
// if the file doesn't exist, serve index.html
if os.IsNotExist(err) {
- http.ServeFile(rw, req, filepath.Join(provider.config.Directory, indexFileName))
+ provider.serveIndex(rw)
return
}
@@ -87,10 +86,15 @@ func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if fi.IsDir() {
// path is a directory, serve index.html
- http.ServeFile(rw, req, filepath.Join(provider.config.Directory, indexFileName))
+ provider.serveIndex(rw)
return
}
// otherwise, use http.FileServer to serve the static file
- http.FileServer(http.Dir(provider.config.Directory)).ServeHTTP(rw, req)
+ provider.fileHandler.ServeHTTP(rw, req)
+}
+
+func (provider *provider) serveIndex(rw http.ResponseWriter) {
+ rw.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = rw.Write(provider.indexContents)
}
diff --git a/pkg/web/routerweb/provider_test.go b/pkg/web/routerweb/provider_test.go
index 96db1edb37..f6305b04c6 100644
--- a/pkg/web/routerweb/provider_test.go
+++ b/pkg/web/routerweb/provider_test.go
@@ -5,45 +5,113 @@ import (
"io"
"net"
"net/http"
+ "net/url"
"os"
"path/filepath"
+ "strings"
"testing"
"github.com/SigNoz/signoz/pkg/factory/factorytest"
+ "github.com/SigNoz/signoz/pkg/global"
"github.com/SigNoz/signoz/pkg/web"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
-func TestServeHttpWithoutPrefix(t *testing.T) {
- t.Parallel()
- fi, err := os.Open(filepath.Join("testdata", indexFileName))
- require.NoError(t, err)
+func startServer(t *testing.T, config web.Config, globalConfig global.Config) string {
+ t.Helper()
- expected, err := io.ReadAll(fi)
+ web, err := New(context.Background(), factorytest.NewSettings(), config, globalConfig)
require.NoError(t, err)
- web, err := New(context.Background(), factorytest.NewSettings(), web.Config{Prefix: "/", Directory: filepath.Join("testdata")})
+ router := mux.NewRouter()
+ require.NoError(t, web.AddToRouter(router))
+
+ listener, err := net.Listen("tcp", "localhost:0")
require.NoError(t, err)
- router := mux.NewRouter()
- err = web.AddToRouter(router)
+ server := &http.Server{Handler: router}
+ go func() { _ = server.Serve(listener) }()
+ t.Cleanup(func() { _ = server.Close() })
+
+ return "http://" + listener.Addr().String()
+}
+
+func httpGet(t *testing.T, url string) string {
+ t.Helper()
+
+ res, err := http.DefaultClient.Get(url)
require.NoError(t, err)
+ defer func() { _ = res.Body.Close() }()
- listener, err := net.Listen("tcp", "localhost:0")
+ body, err := io.ReadAll(res.Body)
require.NoError(t, err)
- server := &http.Server{
- Handler: router,
+ return string(body)
+}
+
+func TestServeTemplatedIndex(t *testing.T) {
+ t.Parallel()
+
+ testCases := []struct {
+ name string
+ path string
+ globalConfig global.Config
+ expected string
+ }{
+ {
+ name: "RootBaseHrefAtRoot",
+ path: "/",
+ globalConfig: global.Config{},
+ expected: `<html><head><base href="/" /></head><body>Welcome to test data!!!</body></html>`,
+ },
+ {
+ name: "RootBaseHrefAtNonExistentPath",
+ path: "/does-not-exist",
+ globalConfig: global.Config{},
+ expected: `<html><head><base href="/" /></head><body>Welcome to test data!!!</body></html>`,
+ },
+ {
+ name: "RootBaseHrefAtDirectory",
+ path: "/assets",
+ globalConfig: global.Config{},
+ expected: `<html><head><base href="/" /></head><body>Welcome to test data!!!</body></html>`,
+ },
+ {
+ name: "SubPathBaseHrefAtRoot",
+ path: "/",
+ globalConfig: global.Config{ExternalURL: &url.URL{Scheme: "https", Host: "example.com", Path: "/signoz"}},
+ expected: `<html><head><base href="/signoz/" /></head><body>Welcome to test data!!!</body></html>`,
+ },
+ {
+ name: "SubPathBaseHrefAtNonExistentPath",
+ path: "/does-not-exist",
+ globalConfig: global.Config{ExternalURL: &url.URL{Scheme: "https", Host: "example.com", Path: "/signoz"}},
+ expected: `<html><head><base href="/signoz/" /></head><body>Welcome to test data!!!</body></html>`,
+ },
+ {
+ name: "SubPathBaseHrefAtDirectory",
+ path: "/assets",
+ globalConfig: global.Config{ExternalURL: &url.URL{Scheme: "https", Host: "example.com", Path: "/signoz"}},
+ expected: `<html><head><base href="/signoz/" /></head><body>Welcome to test data!!!</body></html>`,
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ base := startServer(t, web.Config{Index: "valid_template.html", Directory: "testdata"}, testCase.globalConfig)
+
+ assert.Equal(t, testCase.expected, strings.TrimSuffix(httpGet(t, base+testCase.path), "\n"))
+ })
}
+}
+
+func TestServeNoTemplateIndex(t *testing.T) {
+ t.Parallel()
- go func() {
- _ = server.Serve(listener)
- }()
- defer func() {
- _ = server.Close()
- }()
+ expected, err := os.ReadFile(filepath.Join("testdata", "no_template.html"))
+ require.NoError(t, err)
testCases := []struct {
name string
@@ -54,11 +122,7 @@ func TestServeHttpWithoutPrefix(t *testing.T) {
path: "/",
},
{
- name: "Index",
- path: "/" + indexFileName,
- },
- {
- name: "DoesNotExist",
+ name: "NonExistentPath",
path: "/does-not-exist",
},
{
@@ -67,104 +131,55 @@ func TestServeHttpWithoutPrefix(t *testing.T) {
},
}
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- res, err := http.DefaultClient.Get("http://" + listener.Addr().String() + tc.path)
- require.NoError(t, err)
-
- defer func() {
- _ = res.Body.Close()
- }()
-
- actual, err := io.ReadAll(res.Body)
- require.NoError(t, err)
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ base := startServer(t, web.Config{Index: "no_template.html", Directory: "testdata"}, global.Config{})
- assert.Equal(t, expected, actual)
+ assert.Equal(t, string(expected), httpGet(t, base+testCase.path))
})
}
-
}
-func TestServeHttpWithPrefix(t *testing.T) {
+func TestServeInvalidTemplateIndex(t *testing.T) {
t.Parallel()
- fi, err := os.Open(filepath.Join("testdata", indexFileName))
- require.NoError(t, err)
-
- expected, err := io.ReadAll(fi)
- require.NoError(t, err)
- web, err := New(context.Background(), factorytest.NewSettings(), web.Config{Prefix: "/web", Directory: filepath.Join("testdata")})
+ expected, err := os.ReadFile(filepath.Join("testdata", "invalid_template.html"))
require.NoError(t, err)
- router := mux.NewRouter()
- err = web.AddToRouter(router)
- require.NoError(t, err)
-
- listener, err := net.Listen("tcp", "localhost:0")
- require.NoError(t, err)
-
- server := &http.Server{
- Handler: router,
- }
-
- go func() {
- _ = server.Serve(listener)
- }()
- defer func() {
- _ = server.Close()
- }()
-
testCases := []struct {
- name string
- path string
- found bool
+ name string
+ path string
}{
{
- name: "Root",
- path: "/web",
- found: true,
- },
- {
- name: "Index",
- path: "/web/" + indexFileName,
- found: true,
- },
- {
- name: "FileDoesNotExist",
- path: "/web/does-not-exist",
- found: true,
+ name: "Root",
+ path: "/",
},
{
- name: "Directory",
- path: "/web/assets",
- found: true,
+ name: "NonExistentPath",
+ path: "/does-not-exist",
},
{
- name: "DoesNotExist",
- path: "/does-not-exist",
- found: false,
+ name: "Directory",
+ path: "/assets",
},
}
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- res, err := http.DefaultClient.Get("http://" + listener.Addr().String() + tc.path)
- require.NoError(t, err)
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ base := startServer(t, web.Config{Index: "invalid_template.html", Directory: "testdata"}, global.Config{ExternalURL: &url.URL{Path: "/signoz"}})
- defer func() {
- _ = res.Body.Close()
- }()
+ assert.Equal(t, string(expected), httpGet(t, base+testCase.path))
+ })
+ }
+}
- if tc.found {
- actual, err := io.ReadAll(res.Body)
- require.NoError(t, err)
+func TestServeStaticFilesUnchanged(t *testing.T) {
+ t.Parallel()
- assert.Equal(t, expected, actual)
- } else {
- assert.Equal(t, http.StatusNotFound, res.StatusCode)
- }
+ expected, err := os.ReadFile(filepath.Join("testdata", "assets", "style.css"))
+ require.NoError(t, err)
- })
- }
+ base := startServer(t, web.Config{Index: "valid_template.html", Directory: "testdata"}, global.Config{ExternalURL: &url.URL{Path: "/signoz"}})
+ assert.Equal(t, string(expected), httpGet(t, base+"/assets/style.css"))
}
diff --git a/pkg/web/routerweb/testdata/assets/index.css b/pkg/web/routerweb/testdata/assets/index.css
deleted file mode 100644
index f93ad5f421..0000000000
--- a/pkg/web/routerweb/testdata/assets/index.css
+++ /dev/null
@@ -1,3 +0,0 @@
-#root {
- background-color: red;
-}
\ No newline at end of file
diff --git a/pkg/web/routerweb/testdata/assets/style.css b/pkg/web/routerweb/testdata/assets/style.css
new file mode 100644
index 0000000000..991912d894
--- /dev/null
+++ b/pkg/web/routerweb/testdata/assets/style.css
@@ -0,0 +1 @@
+body { color: red; }
diff --git a/pkg/web/routerweb/testdata/index.html b/pkg/web/routerweb/testdata/index.html
deleted file mode 100644
index 49c8c8383a..0000000000
--- a/pkg/web/routerweb/testdata/index.html
+++ /dev/null
@@ -1 +0,0 @@
-<h1>Welcome to test data!!!</h1>
\ No newline at end of file
diff --git a/pkg/web/routerweb/testdata/invalid_template.html b/pkg/web/routerweb/testdata/invalid_template.html
new file mode 100644
index 0000000000..d240bb3c36
--- /dev/null
+++ b/pkg/web/routerweb/testdata/invalid_template.html
@@ -0,0 +1 @@
+<html><head><base href="[[." /></head><body>Bad template</body></html>
diff --git a/pkg/web/routerweb/testdata/no_template.html b/pkg/web/routerweb/testdata/no_template.html
new file mode 100644
index 0000000000..f01ae5ba82
--- /dev/null
+++ b/pkg/web/routerweb/testdata/no_template.html
@@ -0,0 +1 @@
+<html><head></head><body>No template here</body></html>
diff --git a/pkg/web/routerweb/testdata/valid_template.html b/pkg/web/routerweb/testdata/valid_template.html
new file mode 100644
index 0000000000..f48c8d9a11
--- /dev/null
+++ b/pkg/web/routerweb/testdata/valid_template.html
@@ -0,0 +1 @@
+<html><head><base href="[[.BaseHref]]" /></head><body>Welcome to test data!!!</body></html>
diff --git a/pkg/web/template.go b/pkg/web/template.go
new file mode 100644
index 0000000000..84c1585bf4
--- /dev/null
+++ b/pkg/web/template.go
@@ -0,0 +1,42 @@
+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]]" />
+type TemplateData struct {
+ BaseHref string
+}
+
+// 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
+}