99//
1010// Alternatively, you can register with [http.DefaultServeMux]:
1111//
12- // ss := statsviz.Server{}
13- // s .Register(http.DefaultServeMux)
12+ // ss := statsviz.NewServer()
13+ // ss .Register(http.DefaultServeMux)
1414//
1515// By default, Statsviz is served at http://host:port/debug/statsviz/. This, and
1616// other settings, can be changed by passing some [Option] to [NewServer].
@@ -83,7 +83,7 @@ func Register(mux *http.ServeMux, opts ...Option) error {
8383// - The Ws handler establishes a WebSocket connection allowing the connected
8484// browser to receive metrics updates from the server.
8585//
86- // The zero value is not a valid Server, use NewServer to create a valid one .
86+ // The zero value is a valid Server, with default options .
8787type Server struct {
8888 interval time.Duration // interval between consecutive metrics emission
8989 root string // HTTP path root
@@ -98,23 +98,41 @@ type Server struct {
9898// with some HTTP server. You can either use the Register method or register yourself
9999// the Index and Ws handlers.
100100func NewServer (opts ... Option ) (* Server , error ) {
101- s := & Server {
101+ var s Server
102+ if err := s .init (opts ... ); err != nil {
103+ return nil , err
104+ }
105+ return & s , nil
106+ }
107+
108+ func (s * Server ) init (opts ... Option ) error {
109+ * s = Server {
102110 interval : defaultSendInterval ,
103111 root : defaultRoot ,
104112 }
105113
106114 for _ , opt := range opts {
107115 if err := opt (s ); err != nil {
108- return nil , err
116+ return err
109117 }
110118 }
111119
112120 pl , err := plot .NewList (s .userPlots )
113121 if err != nil {
114- return nil , err
122+ return err
115123 }
116124 s .plots = pl
117- return s , nil
125+
126+ return nil
127+ }
128+
129+ // Register registers the Statsviz HTTP handlers on the provided mux.
130+ func (s * Server ) Register (mux * http.ServeMux ) {
131+ if s .plots == nil {
132+ s .init ()
133+ }
134+ mux .Handle (s .root + "/" , s .Index ())
135+ mux .HandleFunc (s .root + "/ws" , s .Ws ())
118136}
119137
120138// Option is a configuration option for the Server.
@@ -150,12 +168,6 @@ func TimeseriesPlot(tsp TimeSeriesPlot) Option {
150168 }
151169}
152170
153- // Register registers the Statsviz HTTP handlers on the provided mux.
154- func (s * Server ) Register (mux * http.ServeMux ) {
155- mux .Handle (s .root + "/" , s .Index ())
156- mux .HandleFunc (s .root + "/ws" , s .Ws ())
157- }
158-
159171// Index returns the index handler, which responds with the Statsviz user
160172// interface HTML page. By default, the handler is served at the path specified
161173// by the root. Use [WithRoot] to change the path.
0 commit comments