├── go.mod ├── .github ├── FUNDING.yml ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── actions.yml ├── .gitignore ├── codecov.yml ├── .golangci.yml ├── LICENSE ├── README.md ├── gosh.go └── gosh_test.go /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/osamingo/gosh 2 | 3 | go 1.24 4 | 5 | toolchain go1.24.1 6 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: osamingo 4 | custom: https://paypal.me/osamingo 5 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## WHAT 2 | 3 | 4 | 5 | ## WHY 6 | 7 | 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | branch: master 3 | 4 | coverage: 5 | precision: 2 6 | round: down 7 | range: "70...100" 8 | 9 | status: 10 | project: 11 | default: 12 | target: auto 13 | branches: null 14 | 15 | patch: 16 | default: 17 | target: auto 18 | branches: null 19 | 20 | changes: 21 | default: 22 | branches: null 23 | 24 | comment: off 25 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | linters-settings: 2 | errcheck: 3 | check-type-assertions: true 4 | check-blank: true 5 | misspell: 6 | locale: US 7 | funlen: 8 | lines: 65 9 | varnamelen: 10 | min-name-length: 2 11 | tagliatelle: 12 | case: 13 | rules: 14 | json: snake 15 | ireturn: 16 | allow: 17 | - error 18 | - net\/http\.Handler 19 | - github\.com\/osamingo\/gosh\.JSONEncoder 20 | gosec: 21 | excludes: 22 | - G115 23 | 24 | linters: 25 | enable-all: true 26 | disable: 27 | - depguard 28 | -------------------------------------------------------------------------------- /.github/workflows/actions.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | schedule: 9 | - cron: '10 10 * * 0' 10 | 11 | jobs: 12 | lint: 13 | name: Lint 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 17 | - uses: golangci/golangci-lint-action@55c2c1448f86e01eaae002a5a3a9624417608d84 # v6.5.2 18 | with: 19 | version: v1.64.8 20 | test: 21 | name: Test 22 | runs-on: ubuntu-latest 23 | strategy: 24 | matrix: 25 | go: [ 'stable', 'oldstable' ] 26 | steps: 27 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 28 | - uses: actions/setup-go@0aaccfd150d50ccaeb58ebd88d36e91967a5f35b # v5.4.0 29 | with: 30 | go-version: ${{ matrix.go }} 31 | - run: go test -race -covermode=atomic -coverprofile=coverage.txt ./... 32 | - uses: codecov/codecov-action@0565863a31f2c772f9f0395002a31e3f06189574 # v5.4.0 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Osamu TONOMORI 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Go Statistics Handler 2 | 3 | [![CI](https://github.com/osamingo/gosh/actions/workflows/actions.yml/badge.svg)](https://github.com/osamingo/gosh/actions/workflows/actions.yml) 4 | [![codecov](https://codecov.io/gh/osamingo/gosh/branch/master/graph/badge.svg)](https://codecov.io/gh/osamingo/gosh) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/osamingo/gosh)](https://goreportcard.com/report/github.com/osamingo/gosh) 6 | [![GoDoc](https://godoc.org/github.com/osamingo/gosh?status.svg)](https://godoc.org/github.com/osamingo/gosh) 7 | [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/osamingo/gosh/master/LICENSE) 8 | 9 | ## About 10 | 11 | - The `gosh` is an abbreviation for Go Statistics Handler. 12 | - This Repository is provided following functions. 13 | - Go runtime statistics struct. 14 | - Go runtime statistics API handler. 15 | - Go runtime measure method. 16 | - You can specify the favorite JSON encoder. 17 | - [`encoding/json`](https://pkg.go.dev/encoding/json/) package. 18 | - [`goccy/go-json`](https://pkg.go.dev/github.com/goccy/go-json) package. 19 | - The original package you created, and so on. 20 | 21 | ## Install 22 | 23 | ```bash 24 | $ go get github.com/osamingo/gosh@latest 25 | ``` 26 | 27 | ## Usage 28 | 29 | ### Example 30 | 31 | ```go 32 | package main 33 | 34 | import ( 35 | "encoding/json" 36 | "io" 37 | "log" 38 | "net/http" 39 | 40 | "github.com/osamingo/gosh" 41 | ) 42 | 43 | func main() { 44 | 45 | h, err := gosh.NewStatisticsHandler(func(w io.Writer) gosh.JSONEncoder { 46 | return json.NewEncoder(w) 47 | }) 48 | if err != nil { 49 | log.Fatalln(err) 50 | } 51 | 52 | mux := http.NewServeMux() 53 | mux.Handle("/healthz", h) 54 | 55 | if err := http.ListenAndServe(":8080", mux); err != nil { 56 | log.Fatalln(err) 57 | } 58 | } 59 | ``` 60 | 61 | ### Output 62 | 63 | ```bash 64 | $ curl "localhost:8080/healthz" | jq . 65 | { 66 | "timestamp": 1527317620, 67 | "go_version": "go1.10.2", 68 | "go_os": "darwin", 69 | "go_arch": "amd64", 70 | "cpu_num": 8, 71 | "goroutine_num": 6, 72 | "gomaxprocs": 8, 73 | "cgo_call_num": 1, 74 | "memory_alloc": 422272, 75 | "memory_total_alloc": 422272, 76 | "memory_sys": 3084288, 77 | "memory_lookups": 6, 78 | "memory_mallocs": 4720, 79 | "memory_frees": 71, 80 | "stack_inuse": 491520, 81 | "heap_alloc": 422272, 82 | "heap_sys": 1605632, 83 | "heap_idle": 401408, 84 | "heap_inuse": 1204224, 85 | "heap_released": 0, 86 | "heap_objects": 4649, 87 | "gc_next": 4473924, 88 | "gc_last": 0, 89 | "gc_num": 0, 90 | "gc_per_second": 0, 91 | "gc_pause_per_second": 0, 92 | "gc_pause": [] 93 | } 94 | ``` 95 | 96 | 97 | ## License 98 | 99 | Released under the [MIT License](https://github.com/osamingo/gosh/blob/master/LICENSE). 100 | -------------------------------------------------------------------------------- /gosh.go: -------------------------------------------------------------------------------- 1 | package gosh 2 | 3 | import ( 4 | "errors" 5 | "io" 6 | "math" 7 | "net/http" 8 | "runtime" 9 | "sync" 10 | "time" 11 | ) 12 | 13 | type ( 14 | // A Statistics has runtime information. 15 | Statistics struct { 16 | Timestamp int64 `json:"timestamp"` 17 | GoVersion string `json:"go_version"` 18 | GoOS string `json:"go_os"` 19 | GoArch string `json:"go_arch"` 20 | CPUNum int `json:"cpu_num"` 21 | GoroutineNum int `json:"goroutine_num"` 22 | Gomaxprocs int `json:"gomaxprocs"` 23 | CgoCallNum int64 `json:"cgo_call_num"` 24 | MemoryAlloc uint64 `json:"memory_alloc"` 25 | MemoryTotalAlloc uint64 `json:"memory_total_alloc"` 26 | MemorySys uint64 `json:"memory_sys"` 27 | MemoryLookups uint64 `json:"memory_lookups"` 28 | MemoryMallocs uint64 `json:"memory_mallocs"` 29 | MemoryFrees uint64 `json:"memory_frees"` 30 | StackInuse uint64 `json:"stack_inuse"` 31 | HeapAlloc uint64 `json:"heap_alloc"` 32 | HeapSys uint64 `json:"heap_sys"` 33 | HeapIdle uint64 `json:"heap_idle"` 34 | HeapInuse uint64 `json:"heap_inuse"` 35 | HeapReleased uint64 `json:"heap_released"` 36 | HeapObjects uint64 `json:"heap_objects"` 37 | GCNext uint64 `json:"gc_next"` 38 | GCLast uint64 `json:"gc_last"` 39 | GCNum uint32 `json:"gc_num"` 40 | GCPerSecond float64 `json:"gc_per_second"` 41 | GCPausePerSecond float64 `json:"gc_pause_per_second"` 42 | GCPause []float64 `json:"gc_pause"` 43 | } 44 | // A StatisticsHandler provides runtime information handler. 45 | StatisticsHandler struct { 46 | NewJSONEncoder func(w io.Writer) JSONEncoder 47 | 48 | m sync.Mutex 49 | lastSampledAt time.Time 50 | lastPauseTotalNs uint64 51 | lastNumGC uint32 52 | } 53 | 54 | // A JSONEncoder provides Encode method. 55 | // The Encode method writes the JSON encoding of v to the stream, followed by a newline character. 56 | JSONEncoder interface { 57 | Encode(v interface{}) error 58 | } 59 | ) 60 | 61 | // NewStatisticsHandler returns new StatisticsHandler. 62 | func NewStatisticsHandler(fn func(w io.Writer) JSONEncoder) (http.Handler, error) { 63 | if fn == nil { 64 | //nolint: goerr113 65 | return nil, errors.New("gosh: an argument should not be nil") 66 | } 67 | 68 | sh := &StatisticsHandler{ 69 | NewJSONEncoder: fn, 70 | m: sync.Mutex{}, 71 | lastSampledAt: time.Time{}, 72 | lastPauseTotalNs: 0, 73 | lastNumGC: 0, 74 | } 75 | sh.MeasureRuntime() 76 | 77 | return sh, nil 78 | } 79 | 80 | // ServeHTTP implements http.Handler interface. 81 | func (sh *StatisticsHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) { 82 | w.Header().Set("Content-Type", "application/json") 83 | 84 | if err := sh.NewJSONEncoder(w).Encode(sh.MeasureRuntime()); err != nil { 85 | http.Error(w, err.Error(), http.StatusInternalServerError) 86 | } 87 | } 88 | 89 | // MeasureRuntime accesses runtime information. 90 | func (sh *StatisticsHandler) MeasureRuntime() Statistics { 91 | sh.m.Lock() 92 | defer sh.m.Unlock() 93 | 94 | var ms runtime.MemStats 95 | 96 | runtime.ReadMemStats(&ms) 97 | 98 | now := time.Now() 99 | 100 | var gcPausePerSec, gcPerSec float64 101 | if sh.lastPauseTotalNs > 0 { 102 | gcPausePerSec = time.Duration(ms.PauseTotalNs - sh.lastPauseTotalNs).Seconds() 103 | } 104 | 105 | gcCount := int(ms.NumGC - sh.lastNumGC) 106 | if sh.lastNumGC > 0 { 107 | gcPerSec = float64(gcCount) / now.Sub(sh.lastSampledAt).Seconds() 108 | } 109 | 110 | const gcCountThreshold = 256 111 | if gcCount > gcCountThreshold { 112 | gcCount = gcCountThreshold 113 | } 114 | 115 | gcPause := make([]float64, gcCount) 116 | for i := range gcCount { 117 | gcPause[i] = time.Duration(ms.PauseNs[(int(ms.NumGC)-i+math.MaxUint8)%gcCountThreshold]).Seconds() 118 | } 119 | 120 | sh.lastSampledAt = now 121 | sh.lastPauseTotalNs = ms.PauseTotalNs 122 | sh.lastNumGC = ms.NumGC 123 | 124 | return Statistics{ 125 | Timestamp: now.Unix(), 126 | GoVersion: runtime.Version(), 127 | GoOS: runtime.GOOS, 128 | GoArch: runtime.GOARCH, 129 | CPUNum: runtime.NumCPU(), 130 | GoroutineNum: runtime.NumGoroutine(), 131 | Gomaxprocs: runtime.GOMAXPROCS(0), 132 | CgoCallNum: runtime.NumCgoCall(), 133 | MemoryAlloc: ms.Alloc, 134 | MemoryTotalAlloc: ms.TotalAlloc, 135 | MemorySys: ms.Sys, 136 | MemoryLookups: ms.Lookups, 137 | MemoryMallocs: ms.Mallocs, 138 | MemoryFrees: ms.Frees, 139 | StackInuse: ms.StackInuse, 140 | HeapAlloc: ms.HeapAlloc, 141 | HeapSys: ms.HeapSys, 142 | HeapIdle: ms.HeapIdle, 143 | HeapInuse: ms.HeapInuse, 144 | HeapReleased: ms.HeapReleased, 145 | HeapObjects: ms.HeapObjects, 146 | GCNext: ms.NextGC, 147 | GCLast: ms.LastGC, 148 | GCNum: ms.NumGC, 149 | GCPerSecond: gcPerSec, 150 | GCPausePerSecond: gcPausePerSec, 151 | GCPause: gcPause, 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /gosh_test.go: -------------------------------------------------------------------------------- 1 | package gosh_test 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "net/http" 10 | "net/http/httptest" 11 | "runtime" 12 | "testing" 13 | 14 | "github.com/osamingo/gosh" 15 | ) 16 | 17 | type wrongJSONEncoder struct{} 18 | 19 | func (e *wrongJSONEncoder) Encode(_ any) error { 20 | return errors.New("wrong json encoder") //nolint: goerr113 21 | } 22 | 23 | func newJSONEncoder(w io.Writer) gosh.JSONEncoder { 24 | return json.NewEncoder(w) 25 | } 26 | 27 | func newWrongJSONEncoder(_ io.Writer) gosh.JSONEncoder { 28 | return &wrongJSONEncoder{} 29 | } 30 | 31 | func TestNewStatisticsHandler(t *testing.T) { 32 | t.Parallel() 33 | 34 | _, err := gosh.NewStatisticsHandler(nil) 35 | if err == nil { 36 | t.Fatal("expect occur an error") 37 | } 38 | 39 | sh, err := gosh.NewStatisticsHandler(newJSONEncoder) 40 | if err != nil { 41 | t.Fatal(err) 42 | } else if sh == nil { 43 | t.Fatal("value is nil") 44 | } 45 | 46 | if _, ok := sh.(*gosh.StatisticsHandler); !ok { 47 | t.Fatal("failed to cast to StatisticsHandler") 48 | } 49 | } 50 | 51 | func TestStatisticsHandler_ServeHTTP(t *testing.T) { 52 | t.Parallel() 53 | 54 | h, err := gosh.NewStatisticsHandler(newJSONEncoder) 55 | if err != nil { 56 | t.Fatal(err) 57 | } 58 | 59 | srv := httptest.NewServer(h) 60 | defer srv.Close() 61 | 62 | req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, srv.URL, nil) 63 | if err != nil { 64 | t.Fatal("failed to generate request") 65 | } 66 | 67 | resp, err := http.DefaultClient.Do(req) 68 | if err != nil { 69 | t.Fatal("failed to request") 70 | } 71 | defer resp.Body.Close() 72 | 73 | if resp.StatusCode != http.StatusOK { 74 | t.Fatal("unexpect status code") 75 | } else if resp.ContentLength == 0 { 76 | t.Fatal("response body should not be empty") 77 | } 78 | } 79 | 80 | func TestStatisticsHandler_ServeHTTPWithError(t *testing.T) { 81 | t.Parallel() 82 | 83 | h, err := gosh.NewStatisticsHandler(newWrongJSONEncoder) 84 | if err != nil { 85 | t.Fatal(err) 86 | } 87 | 88 | srv := httptest.NewServer(h) 89 | defer srv.Close() 90 | 91 | req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, srv.URL, nil) 92 | if err != nil { 93 | t.Fatal("failed to generate request") 94 | } 95 | 96 | resp, err := http.DefaultClient.Do(req) 97 | if err != nil { 98 | t.Fatal("failed to request") 99 | } 100 | defer resp.Body.Close() 101 | 102 | if resp.StatusCode != http.StatusInternalServerError { 103 | t.Fatal("unexpect status code") 104 | } else if resp.ContentLength == 0 { 105 | t.Fatal("response body should not be empty") 106 | } 107 | } 108 | 109 | func TestStatisticsHandler_MeasureRuntime(t *testing.T) { 110 | t.Parallel() 111 | 112 | defer func() { 113 | if err := recover(); err != nil { 114 | t.Fatal("panic occurred") 115 | } 116 | }() 117 | 118 | h, err := gosh.NewStatisticsHandler(newJSONEncoder) 119 | if err != nil { 120 | t.Fatal(err) 121 | } 122 | 123 | hh, ok := h.(*gosh.StatisticsHandler) 124 | if !ok { 125 | t.Fatal("failed to cast *gosh.StatisticsHandler") 126 | } 127 | 128 | ss := make([]*gosh.Statistics, 100000) 129 | for i := 0; i < len(ss); i++ { 130 | s := hh.MeasureRuntime() 131 | ss[i] = &s 132 | } 133 | } 134 | 135 | func TestStatisticsHandler_MeasureRuntimeWithGC(t *testing.T) { 136 | t.Parallel() 137 | 138 | defer func() { 139 | if err := recover(); err != nil { 140 | t.Fatal("panic occurred") 141 | } 142 | }() 143 | 144 | sh, err := gosh.NewStatisticsHandler(newJSONEncoder) 145 | if err != nil { 146 | t.Fatal(err) 147 | } 148 | 149 | for range 256 { 150 | runtime.GC() 151 | } 152 | 153 | hh, ok := sh.(*gosh.StatisticsHandler) 154 | if !ok { 155 | t.Fatal("failed to cast to *gosh.StatisticsHandler") 156 | } 157 | 158 | ss := make([]*gosh.Statistics, 100000) 159 | for i := 0; i < len(ss); i++ { 160 | s := hh.MeasureRuntime() 161 | ss[i] = &s 162 | } 163 | } 164 | 165 | func BenchmarkStatisticsHandler_MeasureRuntime(b *testing.B) { 166 | h, err := gosh.NewStatisticsHandler(newJSONEncoder) 167 | if err != nil { 168 | b.Fatal(err) 169 | } 170 | 171 | hh, ok := h.(*gosh.StatisticsHandler) 172 | if !ok { 173 | b.Fatal("failed to cast *gosh.StatisticsHandler") 174 | } 175 | 176 | b.ReportAllocs() 177 | b.ResetTimer() 178 | 179 | for range b.N { 180 | hh.MeasureRuntime() 181 | } 182 | } 183 | 184 | func ExampleNewStatisticsHandler() { 185 | sh, err := gosh.NewStatisticsHandler(newJSONEncoder) 186 | if err != nil { 187 | fmt.Println(err) 188 | 189 | return 190 | } 191 | 192 | srv := httptest.NewServer(sh) 193 | 194 | defer srv.Close() 195 | 196 | req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL, nil) 197 | if err != nil { 198 | fmt.Println(err) 199 | 200 | return 201 | } 202 | 203 | resp, err := srv.Client().Do(req) 204 | if err != nil { 205 | fmt.Println(err) 206 | 207 | return 208 | } 209 | 210 | defer func() { 211 | if err := resp.Body.Close(); err != nil { 212 | fmt.Println(err) 213 | 214 | return 215 | } 216 | }() 217 | 218 | if resp.StatusCode != http.StatusOK { 219 | fmt.Println("unexpect status code:", resp.StatusCode) 220 | 221 | return 222 | } 223 | 224 | var stats gosh.Statistics 225 | if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { 226 | fmt.Println(err) 227 | 228 | return 229 | } 230 | 231 | fmt.Printf("status_code: %d, has_gorutine: %t", resp.StatusCode, stats.GoroutineNum > 0) 232 | 233 | // Output: 234 | // status_code: 200, has_gorutine: true 235 | } 236 | --------------------------------------------------------------------------------