1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package expvar provides a standardized interface to public variables, such
6 // as operation counters in servers. It exposes these variables via HTTP at
7 // /debug/vars in JSON format.
9 // Operations to set or modify these public variables are atomic.
11 // In addition to adding the HTTP handler, this package registers the
12 // following variables:
15 // memstats runtime.Memstats
17 // The package is sometimes only imported for the side effect of
18 // registering its HTTP handler and the above variables. To use it
19 // this way, link this package into your program:
39 // Var is an abstract type for all exported variables.
41 // String returns a valid JSON value for the variable.
42 // Types with String methods that do not return valid JSON
43 // (such as time.Time) must not be used as a Var.
47 // Int is a 64-bit integer variable that satisfies the Var interface.
52 func (v
*Int
) Value() int64 {
53 return atomic
.LoadInt64(&v
.i
)
56 func (v
*Int
) String() string {
57 return strconv
.FormatInt(atomic
.LoadInt64(&v
.i
), 10)
60 func (v
*Int
) Add(delta
int64) {
61 atomic
.AddInt64(&v
.i
, delta
)
64 func (v
*Int
) Set(value
int64) {
65 atomic
.StoreInt64(&v
.i
, value
)
68 // Float is a 64-bit float variable that satisfies the Var interface.
73 func (v
*Float
) Value() float64 {
74 return math
.Float64frombits(atomic
.LoadUint64(&v
.f
))
77 func (v
*Float
) String() string {
78 return strconv
.FormatFloat(
79 math
.Float64frombits(atomic
.LoadUint64(&v
.f
)), 'g', -1, 64)
82 // Add adds delta to v.
83 func (v
*Float
) Add(delta
float64) {
85 cur
:= atomic
.LoadUint64(&v
.f
)
86 curVal
:= math
.Float64frombits(cur
)
87 nxtVal
:= curVal
+ delta
88 nxt
:= math
.Float64bits(nxtVal
)
89 if atomic
.CompareAndSwapUint64(&v
.f
, cur
, nxt
) {
95 // Set sets v to value.
96 func (v
*Float
) Set(value
float64) {
97 atomic
.StoreUint64(&v
.f
, math
.Float64bits(value
))
100 // Map is a string-to-Var map variable that satisfies the Var interface.
102 m sync
.Map
// map[string]Var
104 keys
[]string // sorted
107 // KeyValue represents a single entry in a Map.
108 type KeyValue
struct {
113 func (v
*Map
) String() string {
114 var b strings
.Builder
117 v
.Do(func(kv KeyValue
) {
119 fmt
.Fprintf(&b
, ", ")
121 fmt
.Fprintf(&b
, "%q: %v", kv
.Key
, kv
.Value
)
128 // Init removes all keys from the map.
129 func (v
*Map
) Init() *Map
{
131 defer v
.keysMu
.Unlock()
133 v
.m
.Range(func(k
, _ any
) bool {
140 // addKey updates the sorted list of keys in v.keys.
141 func (v
*Map
) addKey(key
string) {
143 defer v
.keysMu
.Unlock()
144 // Using insertion sort to place key into the already-sorted v.keys.
145 if i
:= sort
.SearchStrings(v
.keys
, key
); i
>= len(v
.keys
) {
146 v
.keys
= append(v
.keys
, key
)
147 } else if v
.keys
[i
] != key
{
148 v
.keys
= append(v
.keys
, "")
149 copy(v
.keys
[i
+1:], v
.keys
[i
:])
154 func (v
*Map
) Get(key
string) Var
{
155 i
, _
:= v
.m
.Load(key
)
160 func (v
*Map
) Set(key
string, av Var
) {
161 // Before we store the value, check to see whether the key is new. Try a Load
162 // before LoadOrStore: LoadOrStore causes the key interface to escape even on
164 if _
, ok
:= v
.m
.Load(key
); !ok
{
165 if _
, dup
:= v
.m
.LoadOrStore(key
, av
); !dup
{
174 // Add adds delta to the *Int value stored under the given map key.
175 func (v
*Map
) Add(key
string, delta
int64) {
176 i
, ok
:= v
.m
.Load(key
)
179 i
, dup
= v
.m
.LoadOrStore(key
, new(Int
))
185 // Add to Int; ignore otherwise.
186 if iv
, ok
:= i
.(*Int
); ok
{
191 // AddFloat adds delta to the *Float value stored under the given map key.
192 func (v
*Map
) AddFloat(key
string, delta
float64) {
193 i
, ok
:= v
.m
.Load(key
)
196 i
, dup
= v
.m
.LoadOrStore(key
, new(Float
))
202 // Add to Float; ignore otherwise.
203 if iv
, ok
:= i
.(*Float
); ok
{
208 // Delete deletes the given key from the map.
209 func (v
*Map
) Delete(key
string) {
211 defer v
.keysMu
.Unlock()
212 i
:= sort
.SearchStrings(v
.keys
, key
)
213 if i
< len(v
.keys
) && key
== v
.keys
[i
] {
214 v
.keys
= append(v
.keys
[:i
], v
.keys
[i
+1:]...)
219 // Do calls f for each entry in the map.
220 // The map is locked during the iteration,
221 // but existing entries may be concurrently updated.
222 func (v
*Map
) Do(f
func(KeyValue
)) {
224 defer v
.keysMu
.RUnlock()
225 for _
, k
:= range v
.keys
{
227 f(KeyValue
{k
, i
.(Var
)})
231 // String is a string variable, and satisfies the Var interface.
233 s atomic
.Value
// string
236 func (v
*String
) Value() string {
237 p
, _
:= v
.s
.Load().(string)
241 // String implements the Var interface. To get the unquoted string
243 func (v
*String
) String() string {
245 b
, _
:= json
.Marshal(s
)
249 func (v
*String
) Set(value
string) {
253 // Func implements Var by calling the function
254 // and formatting the returned value using JSON.
257 func (f Func
) Value() any
{
261 func (f Func
) String() string {
262 v
, _
:= json
.Marshal(f())
266 // All published variables.
268 vars sync
.Map
// map[string]Var
269 varKeysMu sync
.RWMutex
270 varKeys
[]string // sorted
273 // Publish declares a named exported variable. This should be called from a
274 // package's init function when it creates its Vars. If the name is already
275 // registered then this will log.Panic.
276 func Publish(name
string, v Var
) {
277 if _
, dup
:= vars
.LoadOrStore(name
, v
); dup
{
278 log
.Panicln("Reuse of exported var name:", name
)
281 defer varKeysMu
.Unlock()
282 varKeys
= append(varKeys
, name
)
283 sort
.Strings(varKeys
)
286 // Get retrieves a named exported variable. It returns nil if the name has
287 // not been registered.
288 func Get(name
string) Var
{
289 i
, _
:= vars
.Load(name
)
294 // Convenience functions for creating new exported variables.
296 func NewInt(name
string) *Int
{
302 func NewFloat(name
string) *Float
{
308 func NewMap(name
string) *Map
{
314 func NewString(name
string) *String
{
320 // Do calls f for each exported variable.
321 // The global variable map is locked during the iteration,
322 // but existing entries may be concurrently updated.
323 func Do(f
func(KeyValue
)) {
325 defer varKeysMu
.RUnlock()
326 for _
, k
:= range varKeys
{
327 val
, _
:= vars
.Load(k
)
328 f(KeyValue
{k
, val
.(Var
)})
332 func expvarHandler(w http
.ResponseWriter
, r
*http
.Request
) {
333 w
.Header().Set("Content-Type", "application/json; charset=utf-8")
334 fmt
.Fprintf(w
, "{\n")
336 Do(func(kv KeyValue
) {
338 fmt
.Fprintf(w
, ",\n")
341 fmt
.Fprintf(w
, "%q: %s", kv
.Key
, kv
.Value
)
343 fmt
.Fprintf(w
, "\n}\n")
346 // Handler returns the expvar HTTP Handler.
348 // This is only needed to install the handler in a non-standard location.
349 func Handler() http
.Handler
{
350 return http
.HandlerFunc(expvarHandler
)
357 func memstats() any
{
358 stats
:= new(runtime
.MemStats
)
359 runtime
.ReadMemStats(stats
)
364 http
.HandleFunc("/debug/vars", expvarHandler
)
365 Publish("cmdline", Func(cmdline
))
366 Publish("memstats", Func(memstats
))