• Stars
    star
    594
  • Rank 72,428 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created about 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Go middleware that stores various information about your web application (response time, status code count, etc.)

Go stats handler

Build Status

stats is a net/http handler in golang reporting various metrics about your web application.

This middleware has been developed and required for the need of picfit, an image resizing server written in Go.

Compatibility

This handler supports the following frameworks at the moment:

We don't support your favorite Go framework? Send me a PR or create a new issue and I will implement it :)

Installation

  1. Make sure you have a Go language compiler >= 1.3 (required) and git installed.
  2. Make sure you have the following go system dependencies in your $PATH: bzr, svn, hg, git
  3. Ensure your GOPATH is properly set.
  4. Download it:
go get github.com/thoas/stats

Usage

Basic net/http

To use this handler directly with net/http, you need to call the middleware with the handler itself:

package main

import (
    "net/http"
    "github.com/thoas/stats"
)

func main() {
    h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte("{\"hello\": \"world\"}"))
    })

    handler := stats.New().Handler(h)
    http.ListenAndServe(":8080", handler)
}

Negroni

If you are using negroni you can implement the handler as a simple middleware in server.go:

package main

import (
    "net/http"
    "github.com/codegangsta/negroni"
    "github.com/thoas/stats"
    "encoding/json"
)

func main() {
    middleware := stats.New()

    mux := http.NewServeMux()

    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte("{\"hello\": \"world\"}"))
    })

    mux.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")

        stats := middleware.Data()

        b, _ := json.Marshal(stats)

        w.Write(b)
    })

    n := negroni.Classic()
    n.Use(middleware)
    n.UseHandler(mux)
    n.Run(":3000")
}

HTTPRouter .......

If you are using HTTPRouter you need to call the middleware with the handler itself:

package main                                                                          

import (
        "encoding/json"
        "github.com/julienschmidt/httprouter"
        "github.com/thoas/stats"
        "net/http"
)

func main() {
        router := httprouter.New()
        s := stats.New()
        router.GET("/stats", func(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
                w.Header().Set("Content-Type", "application/json; charset=utf-8")
                s, err := json.Marshal(s.Data())
                if err != nil {
                        http.Error(w, err.Error(), http.StatusInternalServerError)
                }
                w.Write(s)
        })
        http.ListenAndServe(":8080", s.Handler(router))
}

Martini

If you are using martini, you can implement the handler as a wrapper of a Martini.Context in server.go:

package main

import (
    "encoding/json"
    "github.com/go-martini/martini"
    "github.com/thoas/stats"
    "net/http"
)

func main() {
    middleware := stats.New()

    m := martini.Classic()
    m.Get("/", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte("{\"hello\": \"world\"}"))
    })
    m.Get("/stats", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")

        stats := middleware.Data()

        b, _ := json.Marshal(stats)

        w.Write(b)
    })

    m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
        beginning, recorder := middleware.Begin(w)

        c.Next()

        middleware.End(beginning, stats.WithRecorder(recorder))
    })
    m.Run()
}

Run it in a shell:

$ go run server.go

Then in another shell run:

$ curl http://localhost:3000/stats | python -m "json.tool"

Expect the following result:

{
    "total_response_time": "1.907382ms",
    "average_response_time": "86.699\u00b5s",
    "average_response_time_sec": 8.6699e-05,
    "count": 1,
    "pid": 99894,
    "status_code_count": {
        "200": 1
    },
    "time": "2015-03-06 17:23:27.000677896 +0100 CET",
    "total_count": 22,
    "total_response_time_sec": 0.0019073820000000002,
    "total_status_code_count": {
        "200": 22
    },
    "unixtime": 1425659007,
    "uptime": "4m14.502271612s",
    "uptime_sec": 254.502271612
}

See examples to test them.

Inspiration

Antoine Imbert is the original author of this middleware.

Originally developed for go-json-rest, it had been ported as a simple Golang handler by Florent Messa to be used in various frameworks.

This middleware implements a ticker which is launched every seconds to reset requests/sec and will implement new features in a near future :)

More Repositories

1

go-funk

A modern Go utility library which provides helpers (map, find, contains, filter, ...)
Go
4,577
star
2

picfit

An image resizing server written in Go
Go
1,990
star
3

bokchoy

Simple job queues for Go backed by Redis
Go
263
star
4

django-sequere

A Django application to implement a follow system and a timeline using multiple backends (db, redis, etc.)
Python
57
star
5

django-backward

A Django application to store your previous history and action in your session engine
Python
30
star
6

django-metadata

Attach metadata to any Django models using redis
Python
27
star
7

django-rq-mail

Store mails with waiting and active queues and send them asynchronously
Python
20
star
8

django-sluggable

Manage your slugs and redirect old slugs to the new one
Python
19
star
9

djangogo

Utilities to integrate Go with Django web framework (users management, password encryption, etc.)
Go
10
star
10

observr

A microservice to store analytics about your visitors
Go
9
star
11

django-online

Standalone application to know if a django user is online or not
Python
8
star
12

python-leetchi

A client library written in python to work with leetchi api
Python
7
star
13

django-events-watcher

A basic django application to log information with a data model
Python
7
star
14

finder

Find files and directories in Go
Go
6
star
15

django-fairepart

A generic application to import your contact from facebook, google, etc.
Python
5
star
16

django-data-exporter

[ABANDONED] Export asynchronously your data from your models
Python
5
star
17

vimconfig

My personal vimconfig
Vim Script
4
star
18

letitcrash

A middleware to display debug information when your Go application is panicking
Go
3
star
19

django-eros

Standalone application to like any content types you want and transform link
JavaScript
2
star
20

django-gravatar

Templatetag to get Gravatar URL's from email addresses
Python
2
star
21

vimagneto

Tutoriels gratuits en vidéo en français autour de l'éditeur de code vim
Python
1
star
22

forj

Michel berard personal project
Jinja
1
star
23

isolation

A simple nodejs project with MongoDB
JavaScript
1
star
24

muxer

Basic extension to build http server on top of gorilla mux
Go
1
star
25

may

JavaScript
1
star