mirror of
https://github.com/prymitive/karma
synced 2026-08-28 11:17:28 +00:00
Merge pull request #155 from cloudflare/cache-vendor
Stop committing vendor dir to git
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
.build
|
||||
unsee
|
||||
vendor
|
||||
assets/static/dist
|
||||
node_modules
|
||||
.coverage
|
||||
|
||||
@@ -8,6 +8,7 @@ go_import_path: github.com/cloudflare/unsee
|
||||
cache:
|
||||
directories:
|
||||
- node_modules
|
||||
- vendor
|
||||
|
||||
env:
|
||||
- NODE_ENV=test
|
||||
|
||||
@@ -49,11 +49,11 @@ endif
|
||||
rm -f .build/bindata_assetfs.*
|
||||
touch $@
|
||||
|
||||
bindata_assetfs.go: .build/deps.ok .build/bindata_assetfs.$(GO_BINDATA_MODE) $(ASSET_SOURCES) webpack.config.js
|
||||
bindata_assetfs.go: .build/deps.ok .build/bindata_assetfs.$(GO_BINDATA_MODE) $(ASSET_SOURCES) webpack.config.js .build/vendor.ok
|
||||
$(CURDIR)/node_modules/.bin/webpack -p
|
||||
go-bindata-assetfs $(GO_BINDATA_FLAGS) -prefix assets -nometadata assets/templates/... assets/static/dist/...
|
||||
|
||||
$(NAME): .build/deps.ok bindata_assetfs.go $(SOURCES)
|
||||
$(NAME): .build/deps.ok .build/vendor.ok bindata_assetfs.go $(SOURCES)
|
||||
go build -ldflags "-X main.version=$(VERSION)"
|
||||
|
||||
.PHONY: clean
|
||||
@@ -104,6 +104,11 @@ test: lint bindata_assetfs.go
|
||||
@mkdir -p .build
|
||||
touch $@
|
||||
|
||||
.build/vendor.ok: Gopkg.lock Gopkg.toml .build/dep.ok
|
||||
dep ensure
|
||||
dep prune
|
||||
touch $@
|
||||
|
||||
.PHONY: vendor
|
||||
vendor: .build/dep.ok
|
||||
dep ensure
|
||||
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.5
|
||||
- 1.6
|
||||
- 1.7
|
||||
- 1.8
|
||||
- tip
|
||||
|
||||
script:
|
||||
- go test
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Yangliang Li
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
ginpprof
|
||||
========
|
||||
|
||||
[](https://godoc.org/github.com/DeanThompson/ginpprof)
|
||||
[](https://travis-ci.org/DeanThompson/ginpprof)
|
||||
|
||||
A wrapper for [golang web framework gin](https://github.com/gin-gonic/gin) to use `net/http/pprof` easily.
|
||||
|
||||
## Install
|
||||
|
||||
First install ginpprof to your GOPATH using `go get`:
|
||||
|
||||
```sh
|
||||
go get github.com/DeanThompson/ginpprof
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/DeanThompson/ginpprof"
|
||||
)
|
||||
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
|
||||
router.GET("/ping", func(c *gin.Context) {
|
||||
c.String(200, "pong")
|
||||
})
|
||||
|
||||
// automatically add routers for net/http/pprof
|
||||
// e.g. /debug/pprof, /debug/pprof/heap, etc.
|
||||
ginpprof.Wrap(router)
|
||||
|
||||
// ginpprof also plays well with *gin.RouterGroup
|
||||
// group := router.Group("/debug/pprof")
|
||||
// ginpprof.WrapGroup(group)
|
||||
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
Start this server, and you will see such outputs:
|
||||
|
||||
```text
|
||||
[GIN-debug] GET /ping --> main.main.func1 (3 handlers)
|
||||
[GIN-debug] GET /debug/pprof/ --> github.com/DeanThompson/ginpprof.IndexHandler.func1 (3 handlers)
|
||||
[GIN-debug] GET /debug/pprof/heap --> github.com/DeanThompson/ginpprof.HeapHandler.func1 (3 handlers)
|
||||
[GIN-debug] GET /debug/pprof/goroutine --> github.com/DeanThompson/ginpprof.GoroutineHandler.func1 (3 handlers)
|
||||
[GIN-debug] GET /debug/pprof/block --> github.com/DeanThompson/ginpprof.BlockHandler.func1 (3 handlers)
|
||||
[GIN-debug] GET /debug/pprof/threadcreate --> github.com/DeanThompson/ginpprof.ThreadCreateHandler.func1 (3 handlers)
|
||||
[GIN-debug] GET /debug/pprof/cmdline --> github.com/DeanThompson/ginpprof.CmdlineHandler.func1 (3 handlers)
|
||||
[GIN-debug] GET /debug/pprof/profile --> github.com/DeanThompson/ginpprof.ProfileHandler.func1 (3 handlers)
|
||||
[GIN-debug] GET /debug/pprof/symbol --> github.com/DeanThompson/ginpprof.SymbolHandler.func1 (3 handlers)
|
||||
[GIN-debug] POST /debug/pprof/symbol --> github.com/DeanThompson/ginpprof.SymbolHandler.func1 (3 handlers)
|
||||
[GIN-debug] GET /debug/pprof/trace --> github.com/DeanThompson/ginpprof.TraceHandler.func1 (3 handlers)
|
||||
[GIN-debug] GET /debug/pprof/mutex --> github.com/DeanThompson/ginpprof.MutexHandler.func1 (3 handlers)
|
||||
[GIN-debug] Listening and serving HTTP on :8080
|
||||
```
|
||||
|
||||
Now visit [http://127.0.0.1:8080/debug/pprof/](http://127.0.0.1:8080/debug/pprof/) and you'll see what you want.
|
||||
|
||||
Have Fun.
|
||||
-123
@@ -1,123 +0,0 @@
|
||||
package ginpprof
|
||||
|
||||
import (
|
||||
"net/http/pprof"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Wrap adds several routes from package `net/http/pprof` to *gin.Engine object
|
||||
func Wrap(router *gin.Engine) {
|
||||
WrapGroup(&router.RouterGroup)
|
||||
}
|
||||
|
||||
// Wrapper make sure we are backward compatible
|
||||
var Wrapper = Wrap
|
||||
|
||||
// WrapGroup adds several routes from package `net/http/pprof` to *gin.RouterGroup object
|
||||
func WrapGroup(router *gin.RouterGroup) {
|
||||
routers := []struct {
|
||||
Method string
|
||||
Path string
|
||||
Handler gin.HandlerFunc
|
||||
}{
|
||||
{"GET", "/debug/pprof/", IndexHandler()},
|
||||
{"GET", "/debug/pprof/heap", HeapHandler()},
|
||||
{"GET", "/debug/pprof/goroutine", GoroutineHandler()},
|
||||
{"GET", "/debug/pprof/block", BlockHandler()},
|
||||
{"GET", "/debug/pprof/threadcreate", ThreadCreateHandler()},
|
||||
{"GET", "/debug/pprof/cmdline", CmdlineHandler()},
|
||||
{"GET", "/debug/pprof/profile", ProfileHandler()},
|
||||
{"GET", "/debug/pprof/symbol", SymbolHandler()},
|
||||
{"POST", "/debug/pprof/symbol", SymbolHandler()},
|
||||
{"GET", "/debug/pprof/trace", TraceHandler()},
|
||||
{"GET", "/debug/pprof/mutex", MutexHandler()},
|
||||
}
|
||||
|
||||
basePath := strings.TrimSuffix(router.BasePath(), "/")
|
||||
var prefix string
|
||||
|
||||
switch {
|
||||
case basePath == "":
|
||||
prefix = ""
|
||||
case strings.HasSuffix(basePath, "/debug"):
|
||||
prefix = "/debug"
|
||||
case strings.HasSuffix(basePath, "/debug/pprof"):
|
||||
prefix = "/debug/pprof"
|
||||
}
|
||||
|
||||
for _, r := range routers {
|
||||
router.Handle(r.Method, strings.TrimPrefix(r.Path, prefix), r.Handler)
|
||||
}
|
||||
}
|
||||
|
||||
// IndexHandler will pass the call from /debug/pprof to pprof
|
||||
func IndexHandler() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
pprof.Index(ctx.Writer, ctx.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// HeapHandler will pass the call from /debug/pprof/heap to pprof
|
||||
func HeapHandler() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
pprof.Handler("heap").ServeHTTP(ctx.Writer, ctx.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// GoroutineHandler will pass the call from /debug/pprof/goroutine to pprof
|
||||
func GoroutineHandler() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
pprof.Handler("goroutine").ServeHTTP(ctx.Writer, ctx.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// BlockHandler will pass the call from /debug/pprof/block to pprof
|
||||
func BlockHandler() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
pprof.Handler("block").ServeHTTP(ctx.Writer, ctx.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// ThreadCreateHandler will pass the call from /debug/pprof/threadcreate to pprof
|
||||
func ThreadCreateHandler() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
pprof.Handler("threadcreate").ServeHTTP(ctx.Writer, ctx.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// CmdlineHandler will pass the call from /debug/pprof/cmdline to pprof
|
||||
func CmdlineHandler() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
pprof.Cmdline(ctx.Writer, ctx.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// ProfileHandler will pass the call from /debug/pprof/profile to pprof
|
||||
func ProfileHandler() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
pprof.Profile(ctx.Writer, ctx.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// SymbolHandler will pass the call from /debug/pprof/symbol to pprof
|
||||
func SymbolHandler() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
pprof.Symbol(ctx.Writer, ctx.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// TraceHandler will pass the call from /debug/pprof/trace to pprof
|
||||
func TraceHandler() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
pprof.Trace(ctx.Writer, ctx.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// MutexHandler will pass the call from /debug/pprof/mutex to pprof
|
||||
func MutexHandler() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
pprof.Handler("mutex").ServeHTTP(ctx.Writer, ctx.Request)
|
||||
}
|
||||
}
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
package ginpprof
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func newServer() *gin.Engine {
|
||||
r := gin.Default()
|
||||
return r
|
||||
}
|
||||
|
||||
func checkRouters(routers gin.RoutesInfo, t *testing.T) {
|
||||
expectedRouters := map[string]string{
|
||||
"/debug/pprof/": "IndexHandler",
|
||||
"/debug/pprof/heap": "HeapHandler",
|
||||
"/debug/pprof/goroutine": "GoroutineHandler",
|
||||
"/debug/pprof/block": "BlockHandler",
|
||||
"/debug/pprof/threadcreate": "ThreadCreateHandler",
|
||||
"/debug/pprof/cmdline": "CmdlineHandler",
|
||||
"/debug/pprof/profile": "ProfileHandler",
|
||||
"/debug/pprof/symbol": "SymbolHandler",
|
||||
"/debug/pprof/trace": "TraceHandler",
|
||||
"/debug/pprof/mutex": "MutexHandler",
|
||||
}
|
||||
|
||||
for _, router := range routers {
|
||||
//fmt.Println(router.Path, router.Method, router.Handler)
|
||||
name, ok := expectedRouters[router.Path]
|
||||
if !ok {
|
||||
t.Errorf("missing router %s", router.Path)
|
||||
}
|
||||
if !strings.Contains(router.Handler, name) {
|
||||
t.Errorf("handler for %s should contain %s, got %s", router.Path, name, router.Handler)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrap(t *testing.T) {
|
||||
r := newServer()
|
||||
Wrap(r)
|
||||
checkRouters(r.Routes(), t)
|
||||
}
|
||||
|
||||
func TestWrapGroup(t *testing.T) {
|
||||
for _, prefix := range []string{"/debug", "/debug/", "/debug/pprof", "/debug/pprof/"} {
|
||||
r := newServer()
|
||||
g := r.Group(prefix)
|
||||
WrapGroup(g)
|
||||
checkRouters(r.Routes(), t)
|
||||
}
|
||||
}
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
*.test
|
||||
*.prof
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
Copyright (C) 2013 Blake Mizerany
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
# Perks for Go (golang.org)
|
||||
|
||||
Perks contains the Go package quantile that computes approximate quantiles over
|
||||
an unbounded data stream within low memory and CPU bounds.
|
||||
|
||||
For more information and examples, see:
|
||||
http://godoc.org/github.com/bmizerany/perks
|
||||
|
||||
A very special thank you and shout out to Graham Cormode (Rutgers University),
|
||||
Flip Korn (AT&T Labs–Research), S. Muthukrishnan (Rutgers University), and
|
||||
Divesh Srivastava (AT&T Labs–Research) for their research and publication of
|
||||
[Effective Computation of Biased Quantiles over Data Streams](http://www.cs.rutgers.edu/~muthu/bquant.pdf)
|
||||
|
||||
Thank you, also:
|
||||
* Armon Dadgar (@armon)
|
||||
* Andrew Gerrand (@nf)
|
||||
* Brad Fitzpatrick (@bradfitz)
|
||||
* Keith Rarick (@kr)
|
||||
|
||||
FAQ:
|
||||
|
||||
Q: Why not move the quantile package into the project root?
|
||||
A: I want to add more packages to perks later.
|
||||
|
||||
Copyright (C) 2013 Blake Mizerany
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package quantile
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func BenchmarkInsertTargeted(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
s := NewTargeted(Targets)
|
||||
b.ResetTimer()
|
||||
for i := float64(0); i < float64(b.N); i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInsertTargetedSmallEpsilon(b *testing.B) {
|
||||
s := NewTargeted(TargetsSmallEpsilon)
|
||||
b.ResetTimer()
|
||||
for i := float64(0); i < float64(b.N); i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInsertBiased(b *testing.B) {
|
||||
s := NewLowBiased(0.01)
|
||||
b.ResetTimer()
|
||||
for i := float64(0); i < float64(b.N); i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInsertBiasedSmallEpsilon(b *testing.B) {
|
||||
s := NewLowBiased(0.0001)
|
||||
b.ResetTimer()
|
||||
for i := float64(0); i < float64(b.N); i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkQuery(b *testing.B) {
|
||||
s := NewTargeted(Targets)
|
||||
for i := float64(0); i < 1e6; i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
b.ResetTimer()
|
||||
n := float64(b.N)
|
||||
for i := float64(0); i < n; i++ {
|
||||
s.Query(i / n)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkQuerySmallEpsilon(b *testing.B) {
|
||||
s := NewTargeted(TargetsSmallEpsilon)
|
||||
for i := float64(0); i < 1e6; i++ {
|
||||
s.Insert(i)
|
||||
}
|
||||
b.ResetTimer()
|
||||
n := float64(b.N)
|
||||
for i := float64(0); i < n; i++ {
|
||||
s.Query(i / n)
|
||||
}
|
||||
}
|
||||
-121
@@ -1,121 +0,0 @@
|
||||
// +build go1.1
|
||||
|
||||
package quantile_test
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/beorn7/perks/quantile"
|
||||
)
|
||||
|
||||
func Example_simple() {
|
||||
ch := make(chan float64)
|
||||
go sendFloats(ch)
|
||||
|
||||
// Compute the 50th, 90th, and 99th percentile.
|
||||
q := quantile.NewTargeted(map[float64]float64{
|
||||
0.50: 0.005,
|
||||
0.90: 0.001,
|
||||
0.99: 0.0001,
|
||||
})
|
||||
for v := range ch {
|
||||
q.Insert(v)
|
||||
}
|
||||
|
||||
fmt.Println("perc50:", q.Query(0.50))
|
||||
fmt.Println("perc90:", q.Query(0.90))
|
||||
fmt.Println("perc99:", q.Query(0.99))
|
||||
fmt.Println("count:", q.Count())
|
||||
// Output:
|
||||
// perc50: 5
|
||||
// perc90: 16
|
||||
// perc99: 223
|
||||
// count: 2388
|
||||
}
|
||||
|
||||
func Example_mergeMultipleStreams() {
|
||||
// Scenario:
|
||||
// We have multiple database shards. On each shard, there is a process
|
||||
// collecting query response times from the database logs and inserting
|
||||
// them into a Stream (created via NewTargeted(0.90)), much like the
|
||||
// Simple example. These processes expose a network interface for us to
|
||||
// ask them to serialize and send us the results of their
|
||||
// Stream.Samples so we may Merge and Query them.
|
||||
//
|
||||
// NOTES:
|
||||
// * These sample sets are small, allowing us to get them
|
||||
// across the network much faster than sending the entire list of data
|
||||
// points.
|
||||
//
|
||||
// * For this to work correctly, we must supply the same quantiles
|
||||
// a priori the process collecting the samples supplied to NewTargeted,
|
||||
// even if we do not plan to query them all here.
|
||||
ch := make(chan quantile.Samples)
|
||||
getDBQuerySamples(ch)
|
||||
q := quantile.NewTargeted(map[float64]float64{0.90: 0.001})
|
||||
for samples := range ch {
|
||||
q.Merge(samples)
|
||||
}
|
||||
fmt.Println("perc90:", q.Query(0.90))
|
||||
}
|
||||
|
||||
func Example_window() {
|
||||
// Scenario: We want the 90th, 95th, and 99th percentiles for each
|
||||
// minute.
|
||||
|
||||
ch := make(chan float64)
|
||||
go sendStreamValues(ch)
|
||||
|
||||
tick := time.NewTicker(1 * time.Minute)
|
||||
q := quantile.NewTargeted(map[float64]float64{
|
||||
0.90: 0.001,
|
||||
0.95: 0.0005,
|
||||
0.99: 0.0001,
|
||||
})
|
||||
for {
|
||||
select {
|
||||
case t := <-tick.C:
|
||||
flushToDB(t, q.Samples())
|
||||
q.Reset()
|
||||
case v := <-ch:
|
||||
q.Insert(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sendStreamValues(ch chan float64) {
|
||||
// Use your imagination
|
||||
}
|
||||
|
||||
func flushToDB(t time.Time, samples quantile.Samples) {
|
||||
// Use your imagination
|
||||
}
|
||||
|
||||
// This is a stub for the above example. In reality this would hit the remote
|
||||
// servers via http or something like it.
|
||||
func getDBQuerySamples(ch chan quantile.Samples) {}
|
||||
|
||||
func sendFloats(ch chan<- float64) {
|
||||
f, err := os.Open("exampledata.txt")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
b := sc.Bytes()
|
||||
v, err := strconv.ParseFloat(string(b), 64)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
ch <- v
|
||||
}
|
||||
if sc.Err() != nil {
|
||||
log.Fatal(sc.Err())
|
||||
}
|
||||
close(ch)
|
||||
}
|
||||
-2388
File diff suppressed because it is too large
Load Diff
-292
@@ -1,292 +0,0 @@
|
||||
// Package quantile computes approximate quantiles over an unbounded data
|
||||
// stream within low memory and CPU bounds.
|
||||
//
|
||||
// A small amount of accuracy is traded to achieve the above properties.
|
||||
//
|
||||
// Multiple streams can be merged before calling Query to generate a single set
|
||||
// of results. This is meaningful when the streams represent the same type of
|
||||
// data. See Merge and Samples.
|
||||
//
|
||||
// For more detailed information about the algorithm used, see:
|
||||
//
|
||||
// Effective Computation of Biased Quantiles over Data Streams
|
||||
//
|
||||
// http://www.cs.rutgers.edu/~muthu/bquant.pdf
|
||||
package quantile
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Sample holds an observed value and meta information for compression. JSON
|
||||
// tags have been added for convenience.
|
||||
type Sample struct {
|
||||
Value float64 `json:",string"`
|
||||
Width float64 `json:",string"`
|
||||
Delta float64 `json:",string"`
|
||||
}
|
||||
|
||||
// Samples represents a slice of samples. It implements sort.Interface.
|
||||
type Samples []Sample
|
||||
|
||||
func (a Samples) Len() int { return len(a) }
|
||||
func (a Samples) Less(i, j int) bool { return a[i].Value < a[j].Value }
|
||||
func (a Samples) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
|
||||
type invariant func(s *stream, r float64) float64
|
||||
|
||||
// NewLowBiased returns an initialized Stream for low-biased quantiles
|
||||
// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but
|
||||
// error guarantees can still be given even for the lower ranks of the data
|
||||
// distribution.
|
||||
//
|
||||
// The provided epsilon is a relative error, i.e. the true quantile of a value
|
||||
// returned by a query is guaranteed to be within (1±Epsilon)*Quantile.
|
||||
//
|
||||
// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error
|
||||
// properties.
|
||||
func NewLowBiased(epsilon float64) *Stream {
|
||||
ƒ := func(s *stream, r float64) float64 {
|
||||
return 2 * epsilon * r
|
||||
}
|
||||
return newStream(ƒ)
|
||||
}
|
||||
|
||||
// NewHighBiased returns an initialized Stream for high-biased quantiles
|
||||
// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but
|
||||
// error guarantees can still be given even for the higher ranks of the data
|
||||
// distribution.
|
||||
//
|
||||
// The provided epsilon is a relative error, i.e. the true quantile of a value
|
||||
// returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile).
|
||||
//
|
||||
// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error
|
||||
// properties.
|
||||
func NewHighBiased(epsilon float64) *Stream {
|
||||
ƒ := func(s *stream, r float64) float64 {
|
||||
return 2 * epsilon * (s.n - r)
|
||||
}
|
||||
return newStream(ƒ)
|
||||
}
|
||||
|
||||
// NewTargeted returns an initialized Stream concerned with a particular set of
|
||||
// quantile values that are supplied a priori. Knowing these a priori reduces
|
||||
// space and computation time. The targets map maps the desired quantiles to
|
||||
// their absolute errors, i.e. the true quantile of a value returned by a query
|
||||
// is guaranteed to be within (Quantile±Epsilon).
|
||||
//
|
||||
// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties.
|
||||
func NewTargeted(targets map[float64]float64) *Stream {
|
||||
ƒ := func(s *stream, r float64) float64 {
|
||||
var m = math.MaxFloat64
|
||||
var f float64
|
||||
for quantile, epsilon := range targets {
|
||||
if quantile*s.n <= r {
|
||||
f = (2 * epsilon * r) / quantile
|
||||
} else {
|
||||
f = (2 * epsilon * (s.n - r)) / (1 - quantile)
|
||||
}
|
||||
if f < m {
|
||||
m = f
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
return newStream(ƒ)
|
||||
}
|
||||
|
||||
// Stream computes quantiles for a stream of float64s. It is not thread-safe by
|
||||
// design. Take care when using across multiple goroutines.
|
||||
type Stream struct {
|
||||
*stream
|
||||
b Samples
|
||||
sorted bool
|
||||
}
|
||||
|
||||
func newStream(ƒ invariant) *Stream {
|
||||
x := &stream{ƒ: ƒ}
|
||||
return &Stream{x, make(Samples, 0, 500), true}
|
||||
}
|
||||
|
||||
// Insert inserts v into the stream.
|
||||
func (s *Stream) Insert(v float64) {
|
||||
s.insert(Sample{Value: v, Width: 1})
|
||||
}
|
||||
|
||||
func (s *Stream) insert(sample Sample) {
|
||||
s.b = append(s.b, sample)
|
||||
s.sorted = false
|
||||
if len(s.b) == cap(s.b) {
|
||||
s.flush()
|
||||
}
|
||||
}
|
||||
|
||||
// Query returns the computed qth percentiles value. If s was created with
|
||||
// NewTargeted, and q is not in the set of quantiles provided a priori, Query
|
||||
// will return an unspecified result.
|
||||
func (s *Stream) Query(q float64) float64 {
|
||||
if !s.flushed() {
|
||||
// Fast path when there hasn't been enough data for a flush;
|
||||
// this also yields better accuracy for small sets of data.
|
||||
l := len(s.b)
|
||||
if l == 0 {
|
||||
return 0
|
||||
}
|
||||
i := int(math.Ceil(float64(l) * q))
|
||||
if i > 0 {
|
||||
i -= 1
|
||||
}
|
||||
s.maybeSort()
|
||||
return s.b[i].Value
|
||||
}
|
||||
s.flush()
|
||||
return s.stream.query(q)
|
||||
}
|
||||
|
||||
// Merge merges samples into the underlying streams samples. This is handy when
|
||||
// merging multiple streams from separate threads, database shards, etc.
|
||||
//
|
||||
// ATTENTION: This method is broken and does not yield correct results. The
|
||||
// underlying algorithm is not capable of merging streams correctly.
|
||||
func (s *Stream) Merge(samples Samples) {
|
||||
sort.Sort(samples)
|
||||
s.stream.merge(samples)
|
||||
}
|
||||
|
||||
// Reset reinitializes and clears the list reusing the samples buffer memory.
|
||||
func (s *Stream) Reset() {
|
||||
s.stream.reset()
|
||||
s.b = s.b[:0]
|
||||
}
|
||||
|
||||
// Samples returns stream samples held by s.
|
||||
func (s *Stream) Samples() Samples {
|
||||
if !s.flushed() {
|
||||
return s.b
|
||||
}
|
||||
s.flush()
|
||||
return s.stream.samples()
|
||||
}
|
||||
|
||||
// Count returns the total number of samples observed in the stream
|
||||
// since initialization.
|
||||
func (s *Stream) Count() int {
|
||||
return len(s.b) + s.stream.count()
|
||||
}
|
||||
|
||||
func (s *Stream) flush() {
|
||||
s.maybeSort()
|
||||
s.stream.merge(s.b)
|
||||
s.b = s.b[:0]
|
||||
}
|
||||
|
||||
func (s *Stream) maybeSort() {
|
||||
if !s.sorted {
|
||||
s.sorted = true
|
||||
sort.Sort(s.b)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Stream) flushed() bool {
|
||||
return len(s.stream.l) > 0
|
||||
}
|
||||
|
||||
type stream struct {
|
||||
n float64
|
||||
l []Sample
|
||||
ƒ invariant
|
||||
}
|
||||
|
||||
func (s *stream) reset() {
|
||||
s.l = s.l[:0]
|
||||
s.n = 0
|
||||
}
|
||||
|
||||
func (s *stream) insert(v float64) {
|
||||
s.merge(Samples{{v, 1, 0}})
|
||||
}
|
||||
|
||||
func (s *stream) merge(samples Samples) {
|
||||
// TODO(beorn7): This tries to merge not only individual samples, but
|
||||
// whole summaries. The paper doesn't mention merging summaries at
|
||||
// all. Unittests show that the merging is inaccurate. Find out how to
|
||||
// do merges properly.
|
||||
var r float64
|
||||
i := 0
|
||||
for _, sample := range samples {
|
||||
for ; i < len(s.l); i++ {
|
||||
c := s.l[i]
|
||||
if c.Value > sample.Value {
|
||||
// Insert at position i.
|
||||
s.l = append(s.l, Sample{})
|
||||
copy(s.l[i+1:], s.l[i:])
|
||||
s.l[i] = Sample{
|
||||
sample.Value,
|
||||
sample.Width,
|
||||
math.Max(sample.Delta, math.Floor(s.ƒ(s, r))-1),
|
||||
// TODO(beorn7): How to calculate delta correctly?
|
||||
}
|
||||
i++
|
||||
goto inserted
|
||||
}
|
||||
r += c.Width
|
||||
}
|
||||
s.l = append(s.l, Sample{sample.Value, sample.Width, 0})
|
||||
i++
|
||||
inserted:
|
||||
s.n += sample.Width
|
||||
r += sample.Width
|
||||
}
|
||||
s.compress()
|
||||
}
|
||||
|
||||
func (s *stream) count() int {
|
||||
return int(s.n)
|
||||
}
|
||||
|
||||
func (s *stream) query(q float64) float64 {
|
||||
t := math.Ceil(q * s.n)
|
||||
t += math.Ceil(s.ƒ(s, t) / 2)
|
||||
p := s.l[0]
|
||||
var r float64
|
||||
for _, c := range s.l[1:] {
|
||||
r += p.Width
|
||||
if r+c.Width+c.Delta > t {
|
||||
return p.Value
|
||||
}
|
||||
p = c
|
||||
}
|
||||
return p.Value
|
||||
}
|
||||
|
||||
func (s *stream) compress() {
|
||||
if len(s.l) < 2 {
|
||||
return
|
||||
}
|
||||
x := s.l[len(s.l)-1]
|
||||
xi := len(s.l) - 1
|
||||
r := s.n - 1 - x.Width
|
||||
|
||||
for i := len(s.l) - 2; i >= 0; i-- {
|
||||
c := s.l[i]
|
||||
if c.Width+x.Width+x.Delta <= s.ƒ(s, r) {
|
||||
x.Width += c.Width
|
||||
s.l[xi] = x
|
||||
// Remove element at i.
|
||||
copy(s.l[i:], s.l[i+1:])
|
||||
s.l = s.l[:len(s.l)-1]
|
||||
xi -= 1
|
||||
} else {
|
||||
x = c
|
||||
xi = i
|
||||
}
|
||||
r -= c.Width
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stream) samples() Samples {
|
||||
samples := make(Samples, len(s.l))
|
||||
copy(samples, s.l)
|
||||
return samples
|
||||
}
|
||||
-215
@@ -1,215 +0,0 @@
|
||||
package quantile
|
||||
|
||||
import (
|
||||
"math"
|
||||
"math/rand"
|
||||
"sort"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
Targets = map[float64]float64{
|
||||
0.01: 0.001,
|
||||
0.10: 0.01,
|
||||
0.50: 0.05,
|
||||
0.90: 0.01,
|
||||
0.99: 0.001,
|
||||
}
|
||||
TargetsSmallEpsilon = map[float64]float64{
|
||||
0.01: 0.0001,
|
||||
0.10: 0.001,
|
||||
0.50: 0.005,
|
||||
0.90: 0.001,
|
||||
0.99: 0.0001,
|
||||
}
|
||||
LowQuantiles = []float64{0.01, 0.1, 0.5}
|
||||
HighQuantiles = []float64{0.99, 0.9, 0.5}
|
||||
)
|
||||
|
||||
const RelativeEpsilon = 0.01
|
||||
|
||||
func verifyPercsWithAbsoluteEpsilon(t *testing.T, a []float64, s *Stream) {
|
||||
sort.Float64s(a)
|
||||
for quantile, epsilon := range Targets {
|
||||
n := float64(len(a))
|
||||
k := int(quantile * n)
|
||||
if k < 1 {
|
||||
k = 1
|
||||
}
|
||||
lower := int((quantile - epsilon) * n)
|
||||
if lower < 1 {
|
||||
lower = 1
|
||||
}
|
||||
upper := int(math.Ceil((quantile + epsilon) * n))
|
||||
if upper > len(a) {
|
||||
upper = len(a)
|
||||
}
|
||||
w, min, max := a[k-1], a[lower-1], a[upper-1]
|
||||
if g := s.Query(quantile); g < min || g > max {
|
||||
t.Errorf("q=%f: want %v [%f,%f], got %v", quantile, w, min, max, g)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func verifyLowPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) {
|
||||
sort.Float64s(a)
|
||||
for _, qu := range LowQuantiles {
|
||||
n := float64(len(a))
|
||||
k := int(qu * n)
|
||||
|
||||
lowerRank := int((1 - RelativeEpsilon) * qu * n)
|
||||
upperRank := int(math.Ceil((1 + RelativeEpsilon) * qu * n))
|
||||
w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1]
|
||||
if g := s.Query(qu); g < min || g > max {
|
||||
t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func verifyHighPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) {
|
||||
sort.Float64s(a)
|
||||
for _, qu := range HighQuantiles {
|
||||
n := float64(len(a))
|
||||
k := int(qu * n)
|
||||
|
||||
lowerRank := int((1 - (1+RelativeEpsilon)*(1-qu)) * n)
|
||||
upperRank := int(math.Ceil((1 - (1-RelativeEpsilon)*(1-qu)) * n))
|
||||
w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1]
|
||||
if g := s.Query(qu); g < min || g > max {
|
||||
t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func populateStream(s *Stream) []float64 {
|
||||
a := make([]float64, 0, 1e5+100)
|
||||
for i := 0; i < cap(a); i++ {
|
||||
v := rand.NormFloat64()
|
||||
// Add 5% asymmetric outliers.
|
||||
if i%20 == 0 {
|
||||
v = v*v + 1
|
||||
}
|
||||
s.Insert(v)
|
||||
a = append(a, v)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func TestTargetedQuery(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s := NewTargeted(Targets)
|
||||
a := populateStream(s)
|
||||
verifyPercsWithAbsoluteEpsilon(t, a, s)
|
||||
}
|
||||
|
||||
func TestTargetedQuerySmallSampleSize(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s := NewTargeted(TargetsSmallEpsilon)
|
||||
a := []float64{1, 2, 3, 4, 5}
|
||||
for _, v := range a {
|
||||
s.Insert(v)
|
||||
}
|
||||
verifyPercsWithAbsoluteEpsilon(t, a, s)
|
||||
// If not yet flushed, results should be precise:
|
||||
if !s.flushed() {
|
||||
for φ, want := range map[float64]float64{
|
||||
0.01: 1,
|
||||
0.10: 1,
|
||||
0.50: 3,
|
||||
0.90: 5,
|
||||
0.99: 5,
|
||||
} {
|
||||
if got := s.Query(φ); got != want {
|
||||
t.Errorf("want %f for φ=%f, got %f", want, φ, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLowBiasedQuery(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s := NewLowBiased(RelativeEpsilon)
|
||||
a := populateStream(s)
|
||||
verifyLowPercsWithRelativeEpsilon(t, a, s)
|
||||
}
|
||||
|
||||
func TestHighBiasedQuery(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s := NewHighBiased(RelativeEpsilon)
|
||||
a := populateStream(s)
|
||||
verifyHighPercsWithRelativeEpsilon(t, a, s)
|
||||
}
|
||||
|
||||
// BrokenTestTargetedMerge is broken, see Merge doc comment.
|
||||
func BrokenTestTargetedMerge(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s1 := NewTargeted(Targets)
|
||||
s2 := NewTargeted(Targets)
|
||||
a := populateStream(s1)
|
||||
a = append(a, populateStream(s2)...)
|
||||
s1.Merge(s2.Samples())
|
||||
verifyPercsWithAbsoluteEpsilon(t, a, s1)
|
||||
}
|
||||
|
||||
// BrokenTestLowBiasedMerge is broken, see Merge doc comment.
|
||||
func BrokenTestLowBiasedMerge(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s1 := NewLowBiased(RelativeEpsilon)
|
||||
s2 := NewLowBiased(RelativeEpsilon)
|
||||
a := populateStream(s1)
|
||||
a = append(a, populateStream(s2)...)
|
||||
s1.Merge(s2.Samples())
|
||||
verifyLowPercsWithRelativeEpsilon(t, a, s2)
|
||||
}
|
||||
|
||||
// BrokenTestHighBiasedMerge is broken, see Merge doc comment.
|
||||
func BrokenTestHighBiasedMerge(t *testing.T) {
|
||||
rand.Seed(42)
|
||||
s1 := NewHighBiased(RelativeEpsilon)
|
||||
s2 := NewHighBiased(RelativeEpsilon)
|
||||
a := populateStream(s1)
|
||||
a = append(a, populateStream(s2)...)
|
||||
s1.Merge(s2.Samples())
|
||||
verifyHighPercsWithRelativeEpsilon(t, a, s2)
|
||||
}
|
||||
|
||||
func TestUncompressed(t *testing.T) {
|
||||
q := NewTargeted(Targets)
|
||||
for i := 100; i > 0; i-- {
|
||||
q.Insert(float64(i))
|
||||
}
|
||||
if g := q.Count(); g != 100 {
|
||||
t.Errorf("want count 100, got %d", g)
|
||||
}
|
||||
// Before compression, Query should have 100% accuracy.
|
||||
for quantile := range Targets {
|
||||
w := quantile * 100
|
||||
if g := q.Query(quantile); g != w {
|
||||
t.Errorf("want %f, got %f", w, g)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUncompressedSamples(t *testing.T) {
|
||||
q := NewTargeted(map[float64]float64{0.99: 0.001})
|
||||
for i := 1; i <= 100; i++ {
|
||||
q.Insert(float64(i))
|
||||
}
|
||||
if g := q.Samples().Len(); g != 100 {
|
||||
t.Errorf("want count 100, got %d", g)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUncompressedOne(t *testing.T) {
|
||||
q := NewTargeted(map[float64]float64{0.99: 0.01})
|
||||
q.Insert(3.14)
|
||||
if g := q.Query(0.90); g != 3.14 {
|
||||
t.Error("want PI, got", g)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaults(t *testing.T) {
|
||||
if g := NewTargeted(map[float64]float64{0.99: 0.001}).Query(0.99); g != 0 {
|
||||
t.Errorf("want 0, got %f", g)
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2014 Benedikt Lang <github at benediktlang.de>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
-191
@@ -1,191 +0,0 @@
|
||||
semver for golang [](https://drone.io/github.com/blang/semver/latest) [](https://godoc.org/github.com/blang/semver) [](https://coveralls.io/r/blang/semver?branch=master)
|
||||
======
|
||||
|
||||
semver is a [Semantic Versioning](http://semver.org/) library written in golang. It fully covers spec version `2.0.0`.
|
||||
|
||||
Usage
|
||||
-----
|
||||
```bash
|
||||
$ go get github.com/blang/semver
|
||||
```
|
||||
Note: Always vendor your dependencies or fix on a specific version tag.
|
||||
|
||||
```go
|
||||
import github.com/blang/semver
|
||||
v1, err := semver.Make("1.0.0-beta")
|
||||
v2, err := semver.Make("2.0.0-beta")
|
||||
v1.Compare(v2)
|
||||
```
|
||||
|
||||
Also check the [GoDocs](http://godoc.org/github.com/blang/semver).
|
||||
|
||||
Why should I use this lib?
|
||||
-----
|
||||
|
||||
- Fully spec compatible
|
||||
- No reflection
|
||||
- No regex
|
||||
- Fully tested (Coverage >99%)
|
||||
- Readable parsing/validation errors
|
||||
- Fast (See [Benchmarks](#benchmarks))
|
||||
- Only Stdlib
|
||||
- Uses values instead of pointers
|
||||
- Many features, see below
|
||||
|
||||
|
||||
Features
|
||||
-----
|
||||
|
||||
- Parsing and validation at all levels
|
||||
- Comparator-like comparisons
|
||||
- Compare Helper Methods
|
||||
- InPlace manipulation
|
||||
- Ranges `>=1.0.0 <2.0.0 || >=3.0.0 !3.0.1-beta.1`
|
||||
- Sortable (implements sort.Interface)
|
||||
- database/sql compatible (sql.Scanner/Valuer)
|
||||
- encoding/json compatible (json.Marshaler/Unmarshaler)
|
||||
|
||||
Ranges
|
||||
------
|
||||
|
||||
A `Range` is a set of conditions which specify which versions satisfy the range.
|
||||
|
||||
A condition is composed of an operator and a version. The supported operators are:
|
||||
|
||||
- `<1.0.0` Less than `1.0.0`
|
||||
- `<=1.0.0` Less than or equal to `1.0.0`
|
||||
- `>1.0.0` Greater than `1.0.0`
|
||||
- `>=1.0.0` Greater than or equal to `1.0.0`
|
||||
- `1.0.0`, `=1.0.0`, `==1.0.0` Equal to `1.0.0`
|
||||
- `!1.0.0`, `!=1.0.0` Not equal to `1.0.0`. Excludes version `1.0.0`.
|
||||
|
||||
A `Range` can link multiple `Ranges` separated by space:
|
||||
|
||||
Ranges can be linked by logical AND:
|
||||
|
||||
- `>1.0.0 <2.0.0` would match between both ranges, so `1.1.1` and `1.8.7` but not `1.0.0` or `2.0.0`
|
||||
- `>1.0.0 <3.0.0 !2.0.3-beta.2` would match every version between `1.0.0` and `3.0.0` except `2.0.3-beta.2`
|
||||
|
||||
Ranges can also be linked by logical OR:
|
||||
|
||||
- `<2.0.0 || >=3.0.0` would match `1.x.x` and `3.x.x` but not `2.x.x`
|
||||
|
||||
AND has a higher precedence than OR. It's not possible to use brackets.
|
||||
|
||||
Ranges can be combined by both AND and OR
|
||||
|
||||
- `>1.0.0 <2.0.0 || >3.0.0 !4.2.1` would match `1.2.3`, `1.9.9`, `3.1.1`, but not `4.2.1`, `2.1.1`
|
||||
|
||||
Range usage:
|
||||
|
||||
```
|
||||
v, err := semver.Parse("1.2.3")
|
||||
range, err := semver.ParseRange(">1.0.0 <2.0.0 || >=3.0.0")
|
||||
if range(v) {
|
||||
//valid
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Example
|
||||
-----
|
||||
|
||||
Have a look at full examples in [examples/main.go](examples/main.go)
|
||||
|
||||
```go
|
||||
import github.com/blang/semver
|
||||
|
||||
v, err := semver.Make("0.0.1-alpha.preview+123.github")
|
||||
fmt.Printf("Major: %d\n", v.Major)
|
||||
fmt.Printf("Minor: %d\n", v.Minor)
|
||||
fmt.Printf("Patch: %d\n", v.Patch)
|
||||
fmt.Printf("Pre: %s\n", v.Pre)
|
||||
fmt.Printf("Build: %s\n", v.Build)
|
||||
|
||||
// Prerelease versions array
|
||||
if len(v.Pre) > 0 {
|
||||
fmt.Println("Prerelease versions:")
|
||||
for i, pre := range v.Pre {
|
||||
fmt.Printf("%d: %q\n", i, pre)
|
||||
}
|
||||
}
|
||||
|
||||
// Build meta data array
|
||||
if len(v.Build) > 0 {
|
||||
fmt.Println("Build meta data:")
|
||||
for i, build := range v.Build {
|
||||
fmt.Printf("%d: %q\n", i, build)
|
||||
}
|
||||
}
|
||||
|
||||
v001, err := semver.Make("0.0.1")
|
||||
// Compare using helpers: v.GT(v2), v.LT, v.GTE, v.LTE
|
||||
v001.GT(v) == true
|
||||
v.LT(v001) == true
|
||||
v.GTE(v) == true
|
||||
v.LTE(v) == true
|
||||
|
||||
// Or use v.Compare(v2) for comparisons (-1, 0, 1):
|
||||
v001.Compare(v) == 1
|
||||
v.Compare(v001) == -1
|
||||
v.Compare(v) == 0
|
||||
|
||||
// Manipulate Version in place:
|
||||
v.Pre[0], err = semver.NewPRVersion("beta")
|
||||
if err != nil {
|
||||
fmt.Printf("Error parsing pre release version: %q", err)
|
||||
}
|
||||
|
||||
fmt.Println("\nValidate versions:")
|
||||
v.Build[0] = "?"
|
||||
|
||||
err = v.Validate()
|
||||
if err != nil {
|
||||
fmt.Printf("Validation failed: %s\n", err)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Benchmarks
|
||||
-----
|
||||
|
||||
BenchmarkParseSimple-4 5000000 390 ns/op 48 B/op 1 allocs/op
|
||||
BenchmarkParseComplex-4 1000000 1813 ns/op 256 B/op 7 allocs/op
|
||||
BenchmarkParseAverage-4 1000000 1171 ns/op 163 B/op 4 allocs/op
|
||||
BenchmarkStringSimple-4 20000000 119 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkStringLarger-4 10000000 206 ns/op 32 B/op 2 allocs/op
|
||||
BenchmarkStringComplex-4 5000000 324 ns/op 80 B/op 3 allocs/op
|
||||
BenchmarkStringAverage-4 5000000 273 ns/op 53 B/op 2 allocs/op
|
||||
BenchmarkValidateSimple-4 200000000 9.33 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkValidateComplex-4 3000000 469 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkValidateAverage-4 5000000 256 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkCompareSimple-4 100000000 11.8 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkCompareComplex-4 50000000 30.8 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkCompareAverage-4 30000000 41.5 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkSort-4 3000000 419 ns/op 256 B/op 2 allocs/op
|
||||
BenchmarkRangeParseSimple-4 2000000 850 ns/op 192 B/op 5 allocs/op
|
||||
BenchmarkRangeParseAverage-4 1000000 1677 ns/op 400 B/op 10 allocs/op
|
||||
BenchmarkRangeParseComplex-4 300000 5214 ns/op 1440 B/op 30 allocs/op
|
||||
BenchmarkRangeMatchSimple-4 50000000 25.6 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkRangeMatchAverage-4 30000000 56.4 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkRangeMatchComplex-4 10000000 153 ns/op 0 B/op 0 allocs/op
|
||||
|
||||
See benchmark cases at [semver_test.go](semver_test.go)
|
||||
|
||||
|
||||
Motivation
|
||||
-----
|
||||
|
||||
I simply couldn't find any lib supporting the full spec. Others were just wrong or used reflection and regex which i don't like.
|
||||
|
||||
|
||||
Contribution
|
||||
-----
|
||||
|
||||
Feel free to make a pull request. For bigger changes create a issue first to discuss about it.
|
||||
|
||||
|
||||
License
|
||||
-----
|
||||
|
||||
See [LICENSE](LICENSE) file.
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package semver
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// MarshalJSON implements the encoding/json.Marshaler interface.
|
||||
func (v Version) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(v.String())
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the encoding/json.Unmarshaler interface.
|
||||
func (v *Version) UnmarshalJSON(data []byte) (err error) {
|
||||
var versionString string
|
||||
|
||||
if err = json.Unmarshal(data, &versionString); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
*v, err = Parse(versionString)
|
||||
|
||||
return
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
package semver
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestJSONMarshal(t *testing.T) {
|
||||
versionString := "3.1.4-alpha.1.5.9+build.2.6.5"
|
||||
v, err := Parse(versionString)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
versionJSON, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
quotedVersionString := strconv.Quote(versionString)
|
||||
|
||||
if string(versionJSON) != quotedVersionString {
|
||||
t.Fatalf("JSON marshaled semantic version not equal: expected %q, got %q", quotedVersionString, string(versionJSON))
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONUnmarshal(t *testing.T) {
|
||||
versionString := "3.1.4-alpha.1.5.9+build.2.6.5"
|
||||
quotedVersionString := strconv.Quote(versionString)
|
||||
|
||||
var v Version
|
||||
if err := json.Unmarshal([]byte(quotedVersionString), &v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if v.String() != versionString {
|
||||
t.Fatalf("JSON unmarshaled semantic version not equal: expected %q, got %q", versionString, v.String())
|
||||
}
|
||||
|
||||
badVersionString := strconv.Quote("3.1.4.1.5.9.2.6.5-other-digits-of-pi")
|
||||
if err := json.Unmarshal([]byte(badVersionString), &v); err == nil {
|
||||
t.Fatal("expected JSON unmarshal error, got nil")
|
||||
}
|
||||
|
||||
if err := json.Unmarshal([]byte("3.1"), &v); err == nil {
|
||||
t.Fatal("expected JSON unmarshal error, got nil")
|
||||
}
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"author": "blang",
|
||||
"bugs": {
|
||||
"URL": "https://github.com/blang/semver/issues",
|
||||
"url": "https://github.com/blang/semver/issues"
|
||||
},
|
||||
"gx": {
|
||||
"dvcsimport": "github.com/blang/semver"
|
||||
},
|
||||
"gxVersion": "0.10.0",
|
||||
"language": "go",
|
||||
"license": "MIT",
|
||||
"name": "semver",
|
||||
"releaseCmd": "git commit -a -m \"gx publish $VERSION\"",
|
||||
"version": "3.4.0"
|
||||
}
|
||||
|
||||
-416
@@ -1,416 +0,0 @@
|
||||
package semver
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
type wildcardType int
|
||||
|
||||
const (
|
||||
noneWildcard wildcardType = iota
|
||||
majorWildcard wildcardType = 1
|
||||
minorWildcard wildcardType = 2
|
||||
patchWildcard wildcardType = 3
|
||||
)
|
||||
|
||||
func wildcardTypefromInt(i int) wildcardType {
|
||||
switch i {
|
||||
case 1:
|
||||
return majorWildcard
|
||||
case 2:
|
||||
return minorWildcard
|
||||
case 3:
|
||||
return patchWildcard
|
||||
default:
|
||||
return noneWildcard
|
||||
}
|
||||
}
|
||||
|
||||
type comparator func(Version, Version) bool
|
||||
|
||||
var (
|
||||
compEQ comparator = func(v1 Version, v2 Version) bool {
|
||||
return v1.Compare(v2) == 0
|
||||
}
|
||||
compNE = func(v1 Version, v2 Version) bool {
|
||||
return v1.Compare(v2) != 0
|
||||
}
|
||||
compGT = func(v1 Version, v2 Version) bool {
|
||||
return v1.Compare(v2) == 1
|
||||
}
|
||||
compGE = func(v1 Version, v2 Version) bool {
|
||||
return v1.Compare(v2) >= 0
|
||||
}
|
||||
compLT = func(v1 Version, v2 Version) bool {
|
||||
return v1.Compare(v2) == -1
|
||||
}
|
||||
compLE = func(v1 Version, v2 Version) bool {
|
||||
return v1.Compare(v2) <= 0
|
||||
}
|
||||
)
|
||||
|
||||
type versionRange struct {
|
||||
v Version
|
||||
c comparator
|
||||
}
|
||||
|
||||
// rangeFunc creates a Range from the given versionRange.
|
||||
func (vr *versionRange) rangeFunc() Range {
|
||||
return Range(func(v Version) bool {
|
||||
return vr.c(v, vr.v)
|
||||
})
|
||||
}
|
||||
|
||||
// Range represents a range of versions.
|
||||
// A Range can be used to check if a Version satisfies it:
|
||||
//
|
||||
// range, err := semver.ParseRange(">1.0.0 <2.0.0")
|
||||
// range(semver.MustParse("1.1.1") // returns true
|
||||
type Range func(Version) bool
|
||||
|
||||
// OR combines the existing Range with another Range using logical OR.
|
||||
func (rf Range) OR(f Range) Range {
|
||||
return Range(func(v Version) bool {
|
||||
return rf(v) || f(v)
|
||||
})
|
||||
}
|
||||
|
||||
// AND combines the existing Range with another Range using logical AND.
|
||||
func (rf Range) AND(f Range) Range {
|
||||
return Range(func(v Version) bool {
|
||||
return rf(v) && f(v)
|
||||
})
|
||||
}
|
||||
|
||||
// ParseRange parses a range and returns a Range.
|
||||
// If the range could not be parsed an error is returned.
|
||||
//
|
||||
// Valid ranges are:
|
||||
// - "<1.0.0"
|
||||
// - "<=1.0.0"
|
||||
// - ">1.0.0"
|
||||
// - ">=1.0.0"
|
||||
// - "1.0.0", "=1.0.0", "==1.0.0"
|
||||
// - "!1.0.0", "!=1.0.0"
|
||||
//
|
||||
// A Range can consist of multiple ranges separated by space:
|
||||
// Ranges can be linked by logical AND:
|
||||
// - ">1.0.0 <2.0.0" would match between both ranges, so "1.1.1" and "1.8.7" but not "1.0.0" or "2.0.0"
|
||||
// - ">1.0.0 <3.0.0 !2.0.3-beta.2" would match every version between 1.0.0 and 3.0.0 except 2.0.3-beta.2
|
||||
//
|
||||
// Ranges can also be linked by logical OR:
|
||||
// - "<2.0.0 || >=3.0.0" would match "1.x.x" and "3.x.x" but not "2.x.x"
|
||||
//
|
||||
// AND has a higher precedence than OR. It's not possible to use brackets.
|
||||
//
|
||||
// Ranges can be combined by both AND and OR
|
||||
//
|
||||
// - `>1.0.0 <2.0.0 || >3.0.0 !4.2.1` would match `1.2.3`, `1.9.9`, `3.1.1`, but not `4.2.1`, `2.1.1`
|
||||
func ParseRange(s string) (Range, error) {
|
||||
parts := splitAndTrim(s)
|
||||
orParts, err := splitORParts(parts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
expandedParts, err := expandWildcardVersion(orParts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var orFn Range
|
||||
for _, p := range expandedParts {
|
||||
var andFn Range
|
||||
for _, ap := range p {
|
||||
opStr, vStr, err := splitComparatorVersion(ap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vr, err := buildVersionRange(opStr, vStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Could not parse Range %q: %s", ap, err)
|
||||
}
|
||||
rf := vr.rangeFunc()
|
||||
|
||||
// Set function
|
||||
if andFn == nil {
|
||||
andFn = rf
|
||||
} else { // Combine with existing function
|
||||
andFn = andFn.AND(rf)
|
||||
}
|
||||
}
|
||||
if orFn == nil {
|
||||
orFn = andFn
|
||||
} else {
|
||||
orFn = orFn.OR(andFn)
|
||||
}
|
||||
|
||||
}
|
||||
return orFn, nil
|
||||
}
|
||||
|
||||
// splitORParts splits the already cleaned parts by '||'.
|
||||
// Checks for invalid positions of the operator and returns an
|
||||
// error if found.
|
||||
func splitORParts(parts []string) ([][]string, error) {
|
||||
var ORparts [][]string
|
||||
last := 0
|
||||
for i, p := range parts {
|
||||
if p == "||" {
|
||||
if i == 0 {
|
||||
return nil, fmt.Errorf("First element in range is '||'")
|
||||
}
|
||||
ORparts = append(ORparts, parts[last:i])
|
||||
last = i + 1
|
||||
}
|
||||
}
|
||||
if last == len(parts) {
|
||||
return nil, fmt.Errorf("Last element in range is '||'")
|
||||
}
|
||||
ORparts = append(ORparts, parts[last:])
|
||||
return ORparts, nil
|
||||
}
|
||||
|
||||
// buildVersionRange takes a slice of 2: operator and version
|
||||
// and builds a versionRange, otherwise an error.
|
||||
func buildVersionRange(opStr, vStr string) (*versionRange, error) {
|
||||
c := parseComparator(opStr)
|
||||
if c == nil {
|
||||
return nil, fmt.Errorf("Could not parse comparator %q in %q", opStr, strings.Join([]string{opStr, vStr}, ""))
|
||||
}
|
||||
v, err := Parse(vStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Could not parse version %q in %q: %s", vStr, strings.Join([]string{opStr, vStr}, ""), err)
|
||||
}
|
||||
|
||||
return &versionRange{
|
||||
v: v,
|
||||
c: c,
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
// inArray checks if a byte is contained in an array of bytes
|
||||
func inArray(s byte, list []byte) bool {
|
||||
for _, el := range list {
|
||||
if el == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// splitAndTrim splits a range string by spaces and cleans whitespaces
|
||||
func splitAndTrim(s string) (result []string) {
|
||||
last := 0
|
||||
var lastChar byte
|
||||
excludeFromSplit := []byte{'>', '<', '='}
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == ' ' && !inArray(lastChar, excludeFromSplit) {
|
||||
if last < i-1 {
|
||||
result = append(result, s[last:i])
|
||||
}
|
||||
last = i + 1
|
||||
} else if s[i] != ' ' {
|
||||
lastChar = s[i]
|
||||
}
|
||||
}
|
||||
if last < len(s)-1 {
|
||||
result = append(result, s[last:])
|
||||
}
|
||||
|
||||
for i, v := range result {
|
||||
result[i] = strings.Replace(v, " ", "", -1)
|
||||
}
|
||||
|
||||
// parts := strings.Split(s, " ")
|
||||
// for _, x := range parts {
|
||||
// if s := strings.TrimSpace(x); len(s) != 0 {
|
||||
// result = append(result, s)
|
||||
// }
|
||||
// }
|
||||
return
|
||||
}
|
||||
|
||||
// splitComparatorVersion splits the comparator from the version.
|
||||
// Input must be free of leading or trailing spaces.
|
||||
func splitComparatorVersion(s string) (string, string, error) {
|
||||
i := strings.IndexFunc(s, unicode.IsDigit)
|
||||
if i == -1 {
|
||||
return "", "", fmt.Errorf("Could not get version from string: %q", s)
|
||||
}
|
||||
return strings.TrimSpace(s[0:i]), s[i:], nil
|
||||
}
|
||||
|
||||
// getWildcardType will return the type of wildcard that the
|
||||
// passed version contains
|
||||
func getWildcardType(vStr string) wildcardType {
|
||||
parts := strings.Split(vStr, ".")
|
||||
nparts := len(parts)
|
||||
wildcard := parts[nparts-1]
|
||||
|
||||
possibleWildcardType := wildcardTypefromInt(nparts)
|
||||
if wildcard == "x" {
|
||||
return possibleWildcardType
|
||||
}
|
||||
|
||||
return noneWildcard
|
||||
}
|
||||
|
||||
// createVersionFromWildcard will convert a wildcard version
|
||||
// into a regular version, replacing 'x's with '0's, handling
|
||||
// special cases like '1.x.x' and '1.x'
|
||||
func createVersionFromWildcard(vStr string) string {
|
||||
// handle 1.x.x
|
||||
vStr2 := strings.Replace(vStr, ".x.x", ".x", 1)
|
||||
vStr2 = strings.Replace(vStr2, ".x", ".0", 1)
|
||||
parts := strings.Split(vStr2, ".")
|
||||
|
||||
// handle 1.x
|
||||
if len(parts) == 2 {
|
||||
return vStr2 + ".0"
|
||||
}
|
||||
|
||||
return vStr2
|
||||
}
|
||||
|
||||
// incrementMajorVersion will increment the major version
|
||||
// of the passed version
|
||||
func incrementMajorVersion(vStr string) (string, error) {
|
||||
parts := strings.Split(vStr, ".")
|
||||
i, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
parts[0] = strconv.Itoa(i + 1)
|
||||
|
||||
return strings.Join(parts, "."), nil
|
||||
}
|
||||
|
||||
// incrementMajorVersion will increment the minor version
|
||||
// of the passed version
|
||||
func incrementMinorVersion(vStr string) (string, error) {
|
||||
parts := strings.Split(vStr, ".")
|
||||
i, err := strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
parts[1] = strconv.Itoa(i + 1)
|
||||
|
||||
return strings.Join(parts, "."), nil
|
||||
}
|
||||
|
||||
// expandWildcardVersion will expand wildcards inside versions
|
||||
// following these rules:
|
||||
//
|
||||
// * when dealing with patch wildcards:
|
||||
// >= 1.2.x will become >= 1.2.0
|
||||
// <= 1.2.x will become < 1.3.0
|
||||
// > 1.2.x will become >= 1.3.0
|
||||
// < 1.2.x will become < 1.2.0
|
||||
// != 1.2.x will become < 1.2.0 >= 1.3.0
|
||||
//
|
||||
// * when dealing with minor wildcards:
|
||||
// >= 1.x will become >= 1.0.0
|
||||
// <= 1.x will become < 2.0.0
|
||||
// > 1.x will become >= 2.0.0
|
||||
// < 1.0 will become < 1.0.0
|
||||
// != 1.x will become < 1.0.0 >= 2.0.0
|
||||
//
|
||||
// * when dealing with wildcards without
|
||||
// version operator:
|
||||
// 1.2.x will become >= 1.2.0 < 1.3.0
|
||||
// 1.x will become >= 1.0.0 < 2.0.0
|
||||
func expandWildcardVersion(parts [][]string) ([][]string, error) {
|
||||
var expandedParts [][]string
|
||||
for _, p := range parts {
|
||||
var newParts []string
|
||||
for _, ap := range p {
|
||||
if strings.Index(ap, "x") != -1 {
|
||||
opStr, vStr, err := splitComparatorVersion(ap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
versionWildcardType := getWildcardType(vStr)
|
||||
flatVersion := createVersionFromWildcard(vStr)
|
||||
|
||||
var resultOperator string
|
||||
var shouldIncrementVersion bool
|
||||
switch opStr {
|
||||
case ">":
|
||||
resultOperator = ">="
|
||||
shouldIncrementVersion = true
|
||||
case ">=":
|
||||
resultOperator = ">="
|
||||
case "<":
|
||||
resultOperator = "<"
|
||||
case "<=":
|
||||
resultOperator = "<"
|
||||
shouldIncrementVersion = true
|
||||
case "", "=", "==":
|
||||
newParts = append(newParts, ">="+flatVersion)
|
||||
resultOperator = "<"
|
||||
shouldIncrementVersion = true
|
||||
case "!=", "!":
|
||||
newParts = append(newParts, "<"+flatVersion)
|
||||
resultOperator = ">="
|
||||
shouldIncrementVersion = true
|
||||
}
|
||||
|
||||
var resultVersion string
|
||||
if shouldIncrementVersion {
|
||||
switch versionWildcardType {
|
||||
case patchWildcard:
|
||||
resultVersion, _ = incrementMinorVersion(flatVersion)
|
||||
case minorWildcard:
|
||||
resultVersion, _ = incrementMajorVersion(flatVersion)
|
||||
}
|
||||
} else {
|
||||
resultVersion = flatVersion
|
||||
}
|
||||
|
||||
ap = resultOperator + resultVersion
|
||||
}
|
||||
newParts = append(newParts, ap)
|
||||
}
|
||||
expandedParts = append(expandedParts, newParts)
|
||||
}
|
||||
|
||||
return expandedParts, nil
|
||||
}
|
||||
|
||||
func parseComparator(s string) comparator {
|
||||
switch s {
|
||||
case "==":
|
||||
fallthrough
|
||||
case "":
|
||||
fallthrough
|
||||
case "=":
|
||||
return compEQ
|
||||
case ">":
|
||||
return compGT
|
||||
case ">=":
|
||||
return compGE
|
||||
case "<":
|
||||
return compLT
|
||||
case "<=":
|
||||
return compLE
|
||||
case "!":
|
||||
fallthrough
|
||||
case "!=":
|
||||
return compNE
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MustParseRange is like ParseRange but panics if the range cannot be parsed.
|
||||
func MustParseRange(s string) Range {
|
||||
r, err := ParseRange(s)
|
||||
if err != nil {
|
||||
panic(`semver: ParseRange(` + s + `): ` + err.Error())
|
||||
}
|
||||
return r
|
||||
}
|
||||
-581
@@ -1,581 +0,0 @@
|
||||
package semver
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type wildcardTypeTest struct {
|
||||
input string
|
||||
wildcardType wildcardType
|
||||
}
|
||||
|
||||
type comparatorTest struct {
|
||||
input string
|
||||
comparator func(comparator) bool
|
||||
}
|
||||
|
||||
func TestParseComparator(t *testing.T) {
|
||||
compatorTests := []comparatorTest{
|
||||
{">", testGT},
|
||||
{">=", testGE},
|
||||
{"<", testLT},
|
||||
{"<=", testLE},
|
||||
{"", testEQ},
|
||||
{"=", testEQ},
|
||||
{"==", testEQ},
|
||||
{"!=", testNE},
|
||||
{"!", testNE},
|
||||
{"-", nil},
|
||||
{"<==", nil},
|
||||
{"<<", nil},
|
||||
{">>", nil},
|
||||
}
|
||||
|
||||
for _, tc := range compatorTests {
|
||||
if c := parseComparator(tc.input); c == nil {
|
||||
if tc.comparator != nil {
|
||||
t.Errorf("Comparator nil for case %q\n", tc.input)
|
||||
}
|
||||
} else if !tc.comparator(c) {
|
||||
t.Errorf("Invalid comparator for case %q\n", tc.input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
v1 = MustParse("1.2.2")
|
||||
v2 = MustParse("1.2.3")
|
||||
v3 = MustParse("1.2.4")
|
||||
)
|
||||
|
||||
func testEQ(f comparator) bool {
|
||||
return f(v1, v1) && !f(v1, v2)
|
||||
}
|
||||
|
||||
func testNE(f comparator) bool {
|
||||
return !f(v1, v1) && f(v1, v2)
|
||||
}
|
||||
|
||||
func testGT(f comparator) bool {
|
||||
return f(v2, v1) && f(v3, v2) && !f(v1, v2) && !f(v1, v1)
|
||||
}
|
||||
|
||||
func testGE(f comparator) bool {
|
||||
return f(v2, v1) && f(v3, v2) && !f(v1, v2)
|
||||
}
|
||||
|
||||
func testLT(f comparator) bool {
|
||||
return f(v1, v2) && f(v2, v3) && !f(v2, v1) && !f(v1, v1)
|
||||
}
|
||||
|
||||
func testLE(f comparator) bool {
|
||||
return f(v1, v2) && f(v2, v3) && !f(v2, v1)
|
||||
}
|
||||
|
||||
func TestSplitAndTrim(t *testing.T) {
|
||||
tests := []struct {
|
||||
i string
|
||||
s []string
|
||||
}{
|
||||
{"1.2.3 1.2.3", []string{"1.2.3", "1.2.3"}},
|
||||
{" 1.2.3 1.2.3 ", []string{"1.2.3", "1.2.3"}}, // Spaces
|
||||
{" >= 1.2.3 <= 1.2.3 ", []string{">=1.2.3", "<=1.2.3"}}, // Spaces between operator and version
|
||||
{"1.2.3 || >=1.2.3 <1.2.3", []string{"1.2.3", "||", ">=1.2.3", "<1.2.3"}},
|
||||
{" 1.2.3 || >=1.2.3 <1.2.3 ", []string{"1.2.3", "||", ">=1.2.3", "<1.2.3"}},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
p := splitAndTrim(tc.i)
|
||||
if !reflect.DeepEqual(p, tc.s) {
|
||||
t.Errorf("Invalid for case %q: Expected %q, got: %q", tc.i, tc.s, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitComparatorVersion(t *testing.T) {
|
||||
tests := []struct {
|
||||
i string
|
||||
p []string
|
||||
}{
|
||||
{">1.2.3", []string{">", "1.2.3"}},
|
||||
{">=1.2.3", []string{">=", "1.2.3"}},
|
||||
{"<1.2.3", []string{"<", "1.2.3"}},
|
||||
{"<=1.2.3", []string{"<=", "1.2.3"}},
|
||||
{"1.2.3", []string{"", "1.2.3"}},
|
||||
{"=1.2.3", []string{"=", "1.2.3"}},
|
||||
{"==1.2.3", []string{"==", "1.2.3"}},
|
||||
{"!=1.2.3", []string{"!=", "1.2.3"}},
|
||||
{"!1.2.3", []string{"!", "1.2.3"}},
|
||||
{"error", nil},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
if op, v, err := splitComparatorVersion(tc.i); err != nil {
|
||||
if tc.p != nil {
|
||||
t.Errorf("Invalid for case %q: Expected %q, got error %q", tc.i, tc.p, err)
|
||||
}
|
||||
} else if op != tc.p[0] {
|
||||
t.Errorf("Invalid operator for case %q: Expected %q, got: %q", tc.i, tc.p[0], op)
|
||||
} else if v != tc.p[1] {
|
||||
t.Errorf("Invalid version for case %q: Expected %q, got: %q", tc.i, tc.p[1], v)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildVersionRange(t *testing.T) {
|
||||
tests := []struct {
|
||||
opStr string
|
||||
vStr string
|
||||
c func(comparator) bool
|
||||
v string
|
||||
}{
|
||||
{">", "1.2.3", testGT, "1.2.3"},
|
||||
{">=", "1.2.3", testGE, "1.2.3"},
|
||||
{"<", "1.2.3", testLT, "1.2.3"},
|
||||
{"<=", "1.2.3", testLE, "1.2.3"},
|
||||
{"", "1.2.3", testEQ, "1.2.3"},
|
||||
{"=", "1.2.3", testEQ, "1.2.3"},
|
||||
{"==", "1.2.3", testEQ, "1.2.3"},
|
||||
{"!=", "1.2.3", testNE, "1.2.3"},
|
||||
{"!", "1.2.3", testNE, "1.2.3"},
|
||||
{">>", "1.2.3", nil, ""}, // Invalid comparator
|
||||
{"=", "invalid", nil, ""}, // Invalid version
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
if r, err := buildVersionRange(tc.opStr, tc.vStr); err != nil {
|
||||
if tc.c != nil {
|
||||
t.Errorf("Invalid for case %q: Expected %q, got error %q", strings.Join([]string{tc.opStr, tc.vStr}, ""), tc.v, err)
|
||||
}
|
||||
} else if r == nil {
|
||||
t.Errorf("Invalid for case %q: got nil", strings.Join([]string{tc.opStr, tc.vStr}, ""))
|
||||
} else {
|
||||
// test version
|
||||
if tv := MustParse(tc.v); !r.v.EQ(tv) {
|
||||
t.Errorf("Invalid for case %q: Expected version %q, got: %q", strings.Join([]string{tc.opStr, tc.vStr}, ""), tv, r.v)
|
||||
}
|
||||
// test comparator
|
||||
if r.c == nil {
|
||||
t.Errorf("Invalid for case %q: got nil comparator", strings.Join([]string{tc.opStr, tc.vStr}, ""))
|
||||
continue
|
||||
}
|
||||
if !tc.c(r.c) {
|
||||
t.Errorf("Invalid comparator for case %q\n", strings.Join([]string{tc.opStr, tc.vStr}, ""))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestSplitORParts(t *testing.T) {
|
||||
tests := []struct {
|
||||
i []string
|
||||
o [][]string
|
||||
}{
|
||||
{[]string{">1.2.3", "||", "<1.2.3", "||", "=1.2.3"}, [][]string{
|
||||
[]string{">1.2.3"},
|
||||
[]string{"<1.2.3"},
|
||||
[]string{"=1.2.3"},
|
||||
}},
|
||||
{[]string{">1.2.3", "<1.2.3", "||", "=1.2.3"}, [][]string{
|
||||
[]string{">1.2.3", "<1.2.3"},
|
||||
[]string{"=1.2.3"},
|
||||
}},
|
||||
{[]string{">1.2.3", "||"}, nil},
|
||||
{[]string{"||", ">1.2.3"}, nil},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
o, err := splitORParts(tc.i)
|
||||
if err != nil && tc.o != nil {
|
||||
t.Errorf("Unexpected error for case %q: %s", tc.i, err)
|
||||
}
|
||||
if !reflect.DeepEqual(tc.o, o) {
|
||||
t.Errorf("Invalid for case %q: Expected %q, got: %q", tc.i, tc.o, o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetWildcardType(t *testing.T) {
|
||||
wildcardTypeTests := []wildcardTypeTest{
|
||||
{"x", majorWildcard},
|
||||
{"1.x", minorWildcard},
|
||||
{"1.2.x", patchWildcard},
|
||||
{"fo.o.b.ar", noneWildcard},
|
||||
}
|
||||
|
||||
for _, tc := range wildcardTypeTests {
|
||||
o := getWildcardType(tc.input)
|
||||
if o != tc.wildcardType {
|
||||
t.Errorf("Invalid for case: %q: Expected %q, got: %q", tc.input, tc.wildcardType, o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateVersionFromWildcard(t *testing.T) {
|
||||
tests := []struct {
|
||||
i string
|
||||
s string
|
||||
}{
|
||||
{"1.2.x", "1.2.0"},
|
||||
{"1.x", "1.0.0"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
p := createVersionFromWildcard(tc.i)
|
||||
if p != tc.s {
|
||||
t.Errorf("Invalid for case %q: Expected %q, got: %q", tc.i, tc.s, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncrementMajorVersion(t *testing.T) {
|
||||
tests := []struct {
|
||||
i string
|
||||
s string
|
||||
}{
|
||||
{"1.2.3", "2.2.3"},
|
||||
{"1.2", "2.2"},
|
||||
{"foo.bar", ""},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
p, _ := incrementMajorVersion(tc.i)
|
||||
if p != tc.s {
|
||||
t.Errorf("Invalid for case %q: Expected %q, got: %q", tc.i, tc.s, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncrementMinorVersion(t *testing.T) {
|
||||
tests := []struct {
|
||||
i string
|
||||
s string
|
||||
}{
|
||||
{"1.2.3", "1.3.3"},
|
||||
{"1.2", "1.3"},
|
||||
{"foo.bar", ""},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
p, _ := incrementMinorVersion(tc.i)
|
||||
if p != tc.s {
|
||||
t.Errorf("Invalid for case %q: Expected %q, got: %q", tc.i, tc.s, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandWildcardVersion(t *testing.T) {
|
||||
tests := []struct {
|
||||
i [][]string
|
||||
o [][]string
|
||||
}{
|
||||
{[][]string{[]string{"foox"}}, nil},
|
||||
{[][]string{[]string{">=1.2.x"}}, [][]string{[]string{">=1.2.0"}}},
|
||||
{[][]string{[]string{"<=1.2.x"}}, [][]string{[]string{"<1.3.0"}}},
|
||||
{[][]string{[]string{">1.2.x"}}, [][]string{[]string{">=1.3.0"}}},
|
||||
{[][]string{[]string{"<1.2.x"}}, [][]string{[]string{"<1.2.0"}}},
|
||||
{[][]string{[]string{"!=1.2.x"}}, [][]string{[]string{"<1.2.0", ">=1.3.0"}}},
|
||||
{[][]string{[]string{">=1.x"}}, [][]string{[]string{">=1.0.0"}}},
|
||||
{[][]string{[]string{"<=1.x"}}, [][]string{[]string{"<2.0.0"}}},
|
||||
{[][]string{[]string{">1.x"}}, [][]string{[]string{">=2.0.0"}}},
|
||||
{[][]string{[]string{"<1.x"}}, [][]string{[]string{"<1.0.0"}}},
|
||||
{[][]string{[]string{"!=1.x"}}, [][]string{[]string{"<1.0.0", ">=2.0.0"}}},
|
||||
{[][]string{[]string{"1.2.x"}}, [][]string{[]string{">=1.2.0", "<1.3.0"}}},
|
||||
{[][]string{[]string{"1.x"}}, [][]string{[]string{">=1.0.0", "<2.0.0"}}},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
o, _ := expandWildcardVersion(tc.i)
|
||||
if !reflect.DeepEqual(tc.o, o) {
|
||||
t.Errorf("Invalid for case %q: Expected %q, got: %q", tc.i, tc.o, o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionRangeToRange(t *testing.T) {
|
||||
vr := versionRange{
|
||||
v: MustParse("1.2.3"),
|
||||
c: compLT,
|
||||
}
|
||||
rf := vr.rangeFunc()
|
||||
if !rf(MustParse("1.2.2")) || rf(MustParse("1.2.3")) {
|
||||
t.Errorf("Invalid conversion to range func")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRangeAND(t *testing.T) {
|
||||
v := MustParse("1.2.2")
|
||||
v1 := MustParse("1.2.1")
|
||||
v2 := MustParse("1.2.3")
|
||||
rf1 := Range(func(v Version) bool {
|
||||
return v.GT(v1)
|
||||
})
|
||||
rf2 := Range(func(v Version) bool {
|
||||
return v.LT(v2)
|
||||
})
|
||||
rf := rf1.AND(rf2)
|
||||
if rf(v1) {
|
||||
t.Errorf("Invalid rangefunc, accepted: %s", v1)
|
||||
}
|
||||
if rf(v2) {
|
||||
t.Errorf("Invalid rangefunc, accepted: %s", v2)
|
||||
}
|
||||
if !rf(v) {
|
||||
t.Errorf("Invalid rangefunc, did not accept: %s", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRangeOR(t *testing.T) {
|
||||
tests := []struct {
|
||||
v Version
|
||||
b bool
|
||||
}{
|
||||
{MustParse("1.2.0"), true},
|
||||
{MustParse("1.2.2"), false},
|
||||
{MustParse("1.2.4"), true},
|
||||
}
|
||||
v1 := MustParse("1.2.1")
|
||||
v2 := MustParse("1.2.3")
|
||||
rf1 := Range(func(v Version) bool {
|
||||
return v.LT(v1)
|
||||
})
|
||||
rf2 := Range(func(v Version) bool {
|
||||
return v.GT(v2)
|
||||
})
|
||||
rf := rf1.OR(rf2)
|
||||
for _, tc := range tests {
|
||||
if r := rf(tc.v); r != tc.b {
|
||||
t.Errorf("Invalid for case %q: Expected %t, got %t", tc.v, tc.b, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRange(t *testing.T) {
|
||||
type tv struct {
|
||||
v string
|
||||
b bool
|
||||
}
|
||||
tests := []struct {
|
||||
i string
|
||||
t []tv
|
||||
}{
|
||||
// Simple expressions
|
||||
{">1.2.3", []tv{
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", false},
|
||||
{"1.2.4", true},
|
||||
}},
|
||||
{">=1.2.3", []tv{
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", true},
|
||||
{"1.2.2", false},
|
||||
}},
|
||||
{"<1.2.3", []tv{
|
||||
{"1.2.2", true},
|
||||
{"1.2.3", false},
|
||||
{"1.2.4", false},
|
||||
}},
|
||||
{"<=1.2.3", []tv{
|
||||
{"1.2.2", true},
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", false},
|
||||
}},
|
||||
{"1.2.3", []tv{
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", false},
|
||||
}},
|
||||
{"=1.2.3", []tv{
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", false},
|
||||
}},
|
||||
{"==1.2.3", []tv{
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", false},
|
||||
}},
|
||||
{"!=1.2.3", []tv{
|
||||
{"1.2.2", true},
|
||||
{"1.2.3", false},
|
||||
{"1.2.4", true},
|
||||
}},
|
||||
{"!1.2.3", []tv{
|
||||
{"1.2.2", true},
|
||||
{"1.2.3", false},
|
||||
{"1.2.4", true},
|
||||
}},
|
||||
// Simple Expression errors
|
||||
{">>1.2.3", nil},
|
||||
{"!1.2.3", nil},
|
||||
{"1.0", nil},
|
||||
{"string", nil},
|
||||
{"", nil},
|
||||
{"fo.ob.ar.x", nil},
|
||||
// AND Expressions
|
||||
{">1.2.2 <1.2.4", []tv{
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", false},
|
||||
}},
|
||||
{"<1.2.2 <1.2.4", []tv{
|
||||
{"1.2.1", true},
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", false},
|
||||
{"1.2.4", false},
|
||||
}},
|
||||
{">1.2.2 <1.2.5 !=1.2.4", []tv{
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", false},
|
||||
{"1.2.5", false},
|
||||
}},
|
||||
{">1.2.2 <1.2.5 !1.2.4", []tv{
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", false},
|
||||
{"1.2.5", false},
|
||||
}},
|
||||
// OR Expressions
|
||||
{">1.2.2 || <1.2.4", []tv{
|
||||
{"1.2.2", true},
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", true},
|
||||
}},
|
||||
{"<1.2.2 || >1.2.4", []tv{
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", false},
|
||||
{"1.2.4", false},
|
||||
}},
|
||||
// Wildcard expressions
|
||||
{">1.x", []tv{
|
||||
{"0.1.9", false},
|
||||
{"1.2.6", false},
|
||||
{"1.9.0", false},
|
||||
{"2.0.0", true},
|
||||
}},
|
||||
{">1.2.x", []tv{
|
||||
{"1.1.9", false},
|
||||
{"1.2.6", false},
|
||||
{"1.3.0", true},
|
||||
}},
|
||||
// Combined Expressions
|
||||
{">1.2.2 <1.2.4 || >=2.0.0", []tv{
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", false},
|
||||
{"2.0.0", true},
|
||||
{"2.0.1", true},
|
||||
}},
|
||||
{"1.x || >=2.0.x <2.2.x", []tv{
|
||||
{"0.9.2", false},
|
||||
{"1.2.2", true},
|
||||
{"2.0.0", true},
|
||||
{"2.1.8", true},
|
||||
{"2.2.0", false},
|
||||
}},
|
||||
{">1.2.2 <1.2.4 || >=2.0.0 <3.0.0", []tv{
|
||||
{"1.2.2", false},
|
||||
{"1.2.3", true},
|
||||
{"1.2.4", false},
|
||||
{"2.0.0", true},
|
||||
{"2.0.1", true},
|
||||
{"2.9.9", true},
|
||||
{"3.0.0", false},
|
||||
}},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
r, err := ParseRange(tc.i)
|
||||
if err != nil && tc.t != nil {
|
||||
t.Errorf("Error parsing range %q: %s", tc.i, err)
|
||||
continue
|
||||
}
|
||||
for _, tvc := range tc.t {
|
||||
v := MustParse(tvc.v)
|
||||
if res := r(v); res != tvc.b {
|
||||
t.Errorf("Invalid for case %q matching %q: Expected %t, got: %t", tc.i, tvc.v, tvc.b, res)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestMustParseRange(t *testing.T) {
|
||||
testCase := ">1.2.2 <1.2.4 || >=2.0.0 <3.0.0"
|
||||
r := MustParseRange(testCase)
|
||||
if !r(MustParse("1.2.3")) {
|
||||
t.Errorf("Unexpected range behavior on MustParseRange")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMustParseRange_panic(t *testing.T) {
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Errorf("Should have panicked")
|
||||
}
|
||||
}()
|
||||
_ = MustParseRange("invalid version")
|
||||
}
|
||||
|
||||
func BenchmarkRangeParseSimple(b *testing.B) {
|
||||
const VERSION = ">1.0.0"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
ParseRange(VERSION)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRangeParseAverage(b *testing.B) {
|
||||
const VERSION = ">=1.0.0 <2.0.0"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
ParseRange(VERSION)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRangeParseComplex(b *testing.B) {
|
||||
const VERSION = ">=1.0.0 <2.0.0 || >=3.0.1 <4.0.0 !=3.0.3 || >=5.0.0"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
ParseRange(VERSION)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRangeMatchSimple(b *testing.B) {
|
||||
const VERSION = ">1.0.0"
|
||||
r, _ := ParseRange(VERSION)
|
||||
v := MustParse("2.0.0")
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
r(v)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRangeMatchAverage(b *testing.B) {
|
||||
const VERSION = ">=1.0.0 <2.0.0"
|
||||
r, _ := ParseRange(VERSION)
|
||||
v := MustParse("1.2.3")
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
r(v)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRangeMatchComplex(b *testing.B) {
|
||||
const VERSION = ">=1.0.0 <2.0.0 || >=3.0.1 <4.0.0 !=3.0.3 || >=5.0.0"
|
||||
r, _ := ParseRange(VERSION)
|
||||
v := MustParse("5.0.1")
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
r(v)
|
||||
}
|
||||
}
|
||||
-418
@@ -1,418 +0,0 @@
|
||||
package semver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
numbers string = "0123456789"
|
||||
alphas = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
|
||||
alphanum = alphas + numbers
|
||||
)
|
||||
|
||||
// SpecVersion is the latest fully supported spec version of semver
|
||||
var SpecVersion = Version{
|
||||
Major: 2,
|
||||
Minor: 0,
|
||||
Patch: 0,
|
||||
}
|
||||
|
||||
// Version represents a semver compatible version
|
||||
type Version struct {
|
||||
Major uint64
|
||||
Minor uint64
|
||||
Patch uint64
|
||||
Pre []PRVersion
|
||||
Build []string //No Precendence
|
||||
}
|
||||
|
||||
// Version to string
|
||||
func (v Version) String() string {
|
||||
b := make([]byte, 0, 5)
|
||||
b = strconv.AppendUint(b, v.Major, 10)
|
||||
b = append(b, '.')
|
||||
b = strconv.AppendUint(b, v.Minor, 10)
|
||||
b = append(b, '.')
|
||||
b = strconv.AppendUint(b, v.Patch, 10)
|
||||
|
||||
if len(v.Pre) > 0 {
|
||||
b = append(b, '-')
|
||||
b = append(b, v.Pre[0].String()...)
|
||||
|
||||
for _, pre := range v.Pre[1:] {
|
||||
b = append(b, '.')
|
||||
b = append(b, pre.String()...)
|
||||
}
|
||||
}
|
||||
|
||||
if len(v.Build) > 0 {
|
||||
b = append(b, '+')
|
||||
b = append(b, v.Build[0]...)
|
||||
|
||||
for _, build := range v.Build[1:] {
|
||||
b = append(b, '.')
|
||||
b = append(b, build...)
|
||||
}
|
||||
}
|
||||
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Equals checks if v is equal to o.
|
||||
func (v Version) Equals(o Version) bool {
|
||||
return (v.Compare(o) == 0)
|
||||
}
|
||||
|
||||
// EQ checks if v is equal to o.
|
||||
func (v Version) EQ(o Version) bool {
|
||||
return (v.Compare(o) == 0)
|
||||
}
|
||||
|
||||
// NE checks if v is not equal to o.
|
||||
func (v Version) NE(o Version) bool {
|
||||
return (v.Compare(o) != 0)
|
||||
}
|
||||
|
||||
// GT checks if v is greater than o.
|
||||
func (v Version) GT(o Version) bool {
|
||||
return (v.Compare(o) == 1)
|
||||
}
|
||||
|
||||
// GTE checks if v is greater than or equal to o.
|
||||
func (v Version) GTE(o Version) bool {
|
||||
return (v.Compare(o) >= 0)
|
||||
}
|
||||
|
||||
// GE checks if v is greater than or equal to o.
|
||||
func (v Version) GE(o Version) bool {
|
||||
return (v.Compare(o) >= 0)
|
||||
}
|
||||
|
||||
// LT checks if v is less than o.
|
||||
func (v Version) LT(o Version) bool {
|
||||
return (v.Compare(o) == -1)
|
||||
}
|
||||
|
||||
// LTE checks if v is less than or equal to o.
|
||||
func (v Version) LTE(o Version) bool {
|
||||
return (v.Compare(o) <= 0)
|
||||
}
|
||||
|
||||
// LE checks if v is less than or equal to o.
|
||||
func (v Version) LE(o Version) bool {
|
||||
return (v.Compare(o) <= 0)
|
||||
}
|
||||
|
||||
// Compare compares Versions v to o:
|
||||
// -1 == v is less than o
|
||||
// 0 == v is equal to o
|
||||
// 1 == v is greater than o
|
||||
func (v Version) Compare(o Version) int {
|
||||
if v.Major != o.Major {
|
||||
if v.Major > o.Major {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
if v.Minor != o.Minor {
|
||||
if v.Minor > o.Minor {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
if v.Patch != o.Patch {
|
||||
if v.Patch > o.Patch {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Quick comparison if a version has no prerelease versions
|
||||
if len(v.Pre) == 0 && len(o.Pre) == 0 {
|
||||
return 0
|
||||
} else if len(v.Pre) == 0 && len(o.Pre) > 0 {
|
||||
return 1
|
||||
} else if len(v.Pre) > 0 && len(o.Pre) == 0 {
|
||||
return -1
|
||||
}
|
||||
|
||||
i := 0
|
||||
for ; i < len(v.Pre) && i < len(o.Pre); i++ {
|
||||
if comp := v.Pre[i].Compare(o.Pre[i]); comp == 0 {
|
||||
continue
|
||||
} else if comp == 1 {
|
||||
return 1
|
||||
} else {
|
||||
return -1
|
||||
}
|
||||
}
|
||||
|
||||
// If all pr versions are the equal but one has further prversion, this one greater
|
||||
if i == len(v.Pre) && i == len(o.Pre) {
|
||||
return 0
|
||||
} else if i == len(v.Pre) && i < len(o.Pre) {
|
||||
return -1
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Validate validates v and returns error in case
|
||||
func (v Version) Validate() error {
|
||||
// Major, Minor, Patch already validated using uint64
|
||||
|
||||
for _, pre := range v.Pre {
|
||||
if !pre.IsNum { //Numeric prerelease versions already uint64
|
||||
if len(pre.VersionStr) == 0 {
|
||||
return fmt.Errorf("Prerelease can not be empty %q", pre.VersionStr)
|
||||
}
|
||||
if !containsOnly(pre.VersionStr, alphanum) {
|
||||
return fmt.Errorf("Invalid character(s) found in prerelease %q", pre.VersionStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, build := range v.Build {
|
||||
if len(build) == 0 {
|
||||
return fmt.Errorf("Build meta data can not be empty %q", build)
|
||||
}
|
||||
if !containsOnly(build, alphanum) {
|
||||
return fmt.Errorf("Invalid character(s) found in build meta data %q", build)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// New is an alias for Parse and returns a pointer, parses version string and returns a validated Version or error
|
||||
func New(s string) (vp *Version, err error) {
|
||||
v, err := Parse(s)
|
||||
vp = &v
|
||||
return
|
||||
}
|
||||
|
||||
// Make is an alias for Parse, parses version string and returns a validated Version or error
|
||||
func Make(s string) (Version, error) {
|
||||
return Parse(s)
|
||||
}
|
||||
|
||||
// ParseTolerant allows for certain version specifications that do not strictly adhere to semver
|
||||
// specs to be parsed by this library. It does so by normalizing versions before passing them to
|
||||
// Parse(). It currently trims spaces, removes a "v" prefix, and adds a 0 patch number to versions
|
||||
// with only major and minor components specified
|
||||
func ParseTolerant(s string) (Version, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
s = strings.TrimPrefix(s, "v")
|
||||
|
||||
// Split into major.minor.(patch+pr+meta)
|
||||
parts := strings.SplitN(s, ".", 3)
|
||||
if len(parts) < 3 {
|
||||
if strings.ContainsAny(parts[len(parts)-1], "+-") {
|
||||
return Version{}, errors.New("Short version cannot contain PreRelease/Build meta data")
|
||||
}
|
||||
for len(parts) < 3 {
|
||||
parts = append(parts, "0")
|
||||
}
|
||||
s = strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
return Parse(s)
|
||||
}
|
||||
|
||||
// Parse parses version string and returns a validated Version or error
|
||||
func Parse(s string) (Version, error) {
|
||||
if len(s) == 0 {
|
||||
return Version{}, errors.New("Version string empty")
|
||||
}
|
||||
|
||||
// Split into major.minor.(patch+pr+meta)
|
||||
parts := strings.SplitN(s, ".", 3)
|
||||
if len(parts) != 3 {
|
||||
return Version{}, errors.New("No Major.Minor.Patch elements found")
|
||||
}
|
||||
|
||||
// Major
|
||||
if !containsOnly(parts[0], numbers) {
|
||||
return Version{}, fmt.Errorf("Invalid character(s) found in major number %q", parts[0])
|
||||
}
|
||||
if hasLeadingZeroes(parts[0]) {
|
||||
return Version{}, fmt.Errorf("Major number must not contain leading zeroes %q", parts[0])
|
||||
}
|
||||
major, err := strconv.ParseUint(parts[0], 10, 64)
|
||||
if err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
|
||||
// Minor
|
||||
if !containsOnly(parts[1], numbers) {
|
||||
return Version{}, fmt.Errorf("Invalid character(s) found in minor number %q", parts[1])
|
||||
}
|
||||
if hasLeadingZeroes(parts[1]) {
|
||||
return Version{}, fmt.Errorf("Minor number must not contain leading zeroes %q", parts[1])
|
||||
}
|
||||
minor, err := strconv.ParseUint(parts[1], 10, 64)
|
||||
if err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
|
||||
v := Version{}
|
||||
v.Major = major
|
||||
v.Minor = minor
|
||||
|
||||
var build, prerelease []string
|
||||
patchStr := parts[2]
|
||||
|
||||
if buildIndex := strings.IndexRune(patchStr, '+'); buildIndex != -1 {
|
||||
build = strings.Split(patchStr[buildIndex+1:], ".")
|
||||
patchStr = patchStr[:buildIndex]
|
||||
}
|
||||
|
||||
if preIndex := strings.IndexRune(patchStr, '-'); preIndex != -1 {
|
||||
prerelease = strings.Split(patchStr[preIndex+1:], ".")
|
||||
patchStr = patchStr[:preIndex]
|
||||
}
|
||||
|
||||
if !containsOnly(patchStr, numbers) {
|
||||
return Version{}, fmt.Errorf("Invalid character(s) found in patch number %q", patchStr)
|
||||
}
|
||||
if hasLeadingZeroes(patchStr) {
|
||||
return Version{}, fmt.Errorf("Patch number must not contain leading zeroes %q", patchStr)
|
||||
}
|
||||
patch, err := strconv.ParseUint(patchStr, 10, 64)
|
||||
if err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
|
||||
v.Patch = patch
|
||||
|
||||
// Prerelease
|
||||
for _, prstr := range prerelease {
|
||||
parsedPR, err := NewPRVersion(prstr)
|
||||
if err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
v.Pre = append(v.Pre, parsedPR)
|
||||
}
|
||||
|
||||
// Build meta data
|
||||
for _, str := range build {
|
||||
if len(str) == 0 {
|
||||
return Version{}, errors.New("Build meta data is empty")
|
||||
}
|
||||
if !containsOnly(str, alphanum) {
|
||||
return Version{}, fmt.Errorf("Invalid character(s) found in build meta data %q", str)
|
||||
}
|
||||
v.Build = append(v.Build, str)
|
||||
}
|
||||
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// MustParse is like Parse but panics if the version cannot be parsed.
|
||||
func MustParse(s string) Version {
|
||||
v, err := Parse(s)
|
||||
if err != nil {
|
||||
panic(`semver: Parse(` + s + `): ` + err.Error())
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// PRVersion represents a PreRelease Version
|
||||
type PRVersion struct {
|
||||
VersionStr string
|
||||
VersionNum uint64
|
||||
IsNum bool
|
||||
}
|
||||
|
||||
// NewPRVersion creates a new valid prerelease version
|
||||
func NewPRVersion(s string) (PRVersion, error) {
|
||||
if len(s) == 0 {
|
||||
return PRVersion{}, errors.New("Prerelease is empty")
|
||||
}
|
||||
v := PRVersion{}
|
||||
if containsOnly(s, numbers) {
|
||||
if hasLeadingZeroes(s) {
|
||||
return PRVersion{}, fmt.Errorf("Numeric PreRelease version must not contain leading zeroes %q", s)
|
||||
}
|
||||
num, err := strconv.ParseUint(s, 10, 64)
|
||||
|
||||
// Might never be hit, but just in case
|
||||
if err != nil {
|
||||
return PRVersion{}, err
|
||||
}
|
||||
v.VersionNum = num
|
||||
v.IsNum = true
|
||||
} else if containsOnly(s, alphanum) {
|
||||
v.VersionStr = s
|
||||
v.IsNum = false
|
||||
} else {
|
||||
return PRVersion{}, fmt.Errorf("Invalid character(s) found in prerelease %q", s)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// IsNumeric checks if prerelease-version is numeric
|
||||
func (v PRVersion) IsNumeric() bool {
|
||||
return v.IsNum
|
||||
}
|
||||
|
||||
// Compare compares two PreRelease Versions v and o:
|
||||
// -1 == v is less than o
|
||||
// 0 == v is equal to o
|
||||
// 1 == v is greater than o
|
||||
func (v PRVersion) Compare(o PRVersion) int {
|
||||
if v.IsNum && !o.IsNum {
|
||||
return -1
|
||||
} else if !v.IsNum && o.IsNum {
|
||||
return 1
|
||||
} else if v.IsNum && o.IsNum {
|
||||
if v.VersionNum == o.VersionNum {
|
||||
return 0
|
||||
} else if v.VersionNum > o.VersionNum {
|
||||
return 1
|
||||
} else {
|
||||
return -1
|
||||
}
|
||||
} else { // both are Alphas
|
||||
if v.VersionStr == o.VersionStr {
|
||||
return 0
|
||||
} else if v.VersionStr > o.VersionStr {
|
||||
return 1
|
||||
} else {
|
||||
return -1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PreRelease version to string
|
||||
func (v PRVersion) String() string {
|
||||
if v.IsNum {
|
||||
return strconv.FormatUint(v.VersionNum, 10)
|
||||
}
|
||||
return v.VersionStr
|
||||
}
|
||||
|
||||
func containsOnly(s string, set string) bool {
|
||||
return strings.IndexFunc(s, func(r rune) bool {
|
||||
return !strings.ContainsRune(set, r)
|
||||
}) == -1
|
||||
}
|
||||
|
||||
func hasLeadingZeroes(s string) bool {
|
||||
return len(s) > 1 && s[0] == '0'
|
||||
}
|
||||
|
||||
// NewBuildVersion creates a new valid build version
|
||||
func NewBuildVersion(s string) (string, error) {
|
||||
if len(s) == 0 {
|
||||
return "", errors.New("Buildversion is empty")
|
||||
}
|
||||
if !containsOnly(s, alphanum) {
|
||||
return "", fmt.Errorf("Invalid character(s) found in build meta data %q", s)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
-458
@@ -1,458 +0,0 @@
|
||||
package semver
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func prstr(s string) PRVersion {
|
||||
return PRVersion{s, 0, false}
|
||||
}
|
||||
|
||||
func prnum(i uint64) PRVersion {
|
||||
return PRVersion{"", i, true}
|
||||
}
|
||||
|
||||
type formatTest struct {
|
||||
v Version
|
||||
result string
|
||||
}
|
||||
|
||||
var formatTests = []formatTest{
|
||||
{Version{1, 2, 3, nil, nil}, "1.2.3"},
|
||||
{Version{0, 0, 1, nil, nil}, "0.0.1"},
|
||||
{Version{0, 0, 1, []PRVersion{prstr("alpha"), prstr("preview")}, []string{"123", "456"}}, "0.0.1-alpha.preview+123.456"},
|
||||
{Version{1, 2, 3, []PRVersion{prstr("alpha"), prnum(1)}, []string{"123", "456"}}, "1.2.3-alpha.1+123.456"},
|
||||
{Version{1, 2, 3, []PRVersion{prstr("alpha"), prnum(1)}, nil}, "1.2.3-alpha.1"},
|
||||
{Version{1, 2, 3, nil, []string{"123", "456"}}, "1.2.3+123.456"},
|
||||
// Prereleases and build metadata hyphens
|
||||
{Version{1, 2, 3, []PRVersion{prstr("alpha"), prstr("b-eta")}, []string{"123", "b-uild"}}, "1.2.3-alpha.b-eta+123.b-uild"},
|
||||
{Version{1, 2, 3, nil, []string{"123", "b-uild"}}, "1.2.3+123.b-uild"},
|
||||
{Version{1, 2, 3, []PRVersion{prstr("alpha"), prstr("b-eta")}, nil}, "1.2.3-alpha.b-eta"},
|
||||
}
|
||||
|
||||
var tolerantFormatTests = []formatTest{
|
||||
{Version{1, 2, 3, nil, nil}, "v1.2.3"},
|
||||
{Version{1, 2, 3, nil, nil}, " 1.2.3 "},
|
||||
{Version{1, 2, 0, nil, nil}, "1.2"},
|
||||
{Version{1, 0, 0, nil, nil}, "1"},
|
||||
}
|
||||
|
||||
func TestStringer(t *testing.T) {
|
||||
for _, test := range formatTests {
|
||||
if res := test.v.String(); res != test.result {
|
||||
t.Errorf("Stringer, expected %q but got %q", test.result, res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
for _, test := range formatTests {
|
||||
if v, err := Parse(test.result); err != nil {
|
||||
t.Errorf("Error parsing %q: %q", test.result, err)
|
||||
} else if comp := v.Compare(test.v); comp != 0 {
|
||||
t.Errorf("Parsing, expected %q but got %q, comp: %d ", test.v, v, comp)
|
||||
} else if err := v.Validate(); err != nil {
|
||||
t.Errorf("Error validating parsed version %q: %q", test.v, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTolerant(t *testing.T) {
|
||||
for _, test := range tolerantFormatTests {
|
||||
if v, err := ParseTolerant(test.result); err != nil {
|
||||
t.Errorf("Error parsing %q: %q", test.result, err)
|
||||
} else if comp := v.Compare(test.v); comp != 0 {
|
||||
t.Errorf("Parsing, expected %q but got %q, comp: %d ", test.v, v, comp)
|
||||
} else if err := v.Validate(); err != nil {
|
||||
t.Errorf("Error validating parsed version %q: %q", test.v, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMustParse(t *testing.T) {
|
||||
_ = MustParse("32.2.1-alpha")
|
||||
}
|
||||
|
||||
func TestMustParse_panic(t *testing.T) {
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Errorf("Should have panicked")
|
||||
}
|
||||
}()
|
||||
_ = MustParse("invalid version")
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
for _, test := range formatTests {
|
||||
if err := test.v.Validate(); err != nil {
|
||||
t.Errorf("Error validating %q: %q", test.v, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type compareTest struct {
|
||||
v1 Version
|
||||
v2 Version
|
||||
result int
|
||||
}
|
||||
|
||||
var compareTests = []compareTest{
|
||||
{Version{1, 0, 0, nil, nil}, Version{1, 0, 0, nil, nil}, 0},
|
||||
{Version{2, 0, 0, nil, nil}, Version{1, 0, 0, nil, nil}, 1},
|
||||
{Version{0, 1, 0, nil, nil}, Version{0, 1, 0, nil, nil}, 0},
|
||||
{Version{0, 2, 0, nil, nil}, Version{0, 1, 0, nil, nil}, 1},
|
||||
{Version{0, 0, 1, nil, nil}, Version{0, 0, 1, nil, nil}, 0},
|
||||
{Version{0, 0, 2, nil, nil}, Version{0, 0, 1, nil, nil}, 1},
|
||||
{Version{1, 2, 3, nil, nil}, Version{1, 2, 3, nil, nil}, 0},
|
||||
{Version{2, 2, 4, nil, nil}, Version{1, 2, 4, nil, nil}, 1},
|
||||
{Version{1, 3, 3, nil, nil}, Version{1, 2, 3, nil, nil}, 1},
|
||||
{Version{1, 2, 4, nil, nil}, Version{1, 2, 3, nil, nil}, 1},
|
||||
|
||||
// Spec Examples #11
|
||||
{Version{1, 0, 0, nil, nil}, Version{2, 0, 0, nil, nil}, -1},
|
||||
{Version{2, 0, 0, nil, nil}, Version{2, 1, 0, nil, nil}, -1},
|
||||
{Version{2, 1, 0, nil, nil}, Version{2, 1, 1, nil, nil}, -1},
|
||||
|
||||
// Spec Examples #9
|
||||
{Version{1, 0, 0, nil, nil}, Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil}, 1},
|
||||
{Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil}, Version{1, 0, 0, []PRVersion{prstr("alpha"), prnum(1)}, nil}, -1},
|
||||
{Version{1, 0, 0, []PRVersion{prstr("alpha"), prnum(1)}, nil}, Version{1, 0, 0, []PRVersion{prstr("alpha"), prstr("beta")}, nil}, -1},
|
||||
{Version{1, 0, 0, []PRVersion{prstr("alpha"), prstr("beta")}, nil}, Version{1, 0, 0, []PRVersion{prstr("beta")}, nil}, -1},
|
||||
{Version{1, 0, 0, []PRVersion{prstr("beta")}, nil}, Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(2)}, nil}, -1},
|
||||
{Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(2)}, nil}, Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(11)}, nil}, -1},
|
||||
{Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(11)}, nil}, Version{1, 0, 0, []PRVersion{prstr("rc"), prnum(1)}, nil}, -1},
|
||||
{Version{1, 0, 0, []PRVersion{prstr("rc"), prnum(1)}, nil}, Version{1, 0, 0, nil, nil}, -1},
|
||||
|
||||
// Ignore Build metadata
|
||||
{Version{1, 0, 0, nil, []string{"1", "2", "3"}}, Version{1, 0, 0, nil, nil}, 0},
|
||||
}
|
||||
|
||||
func TestCompare(t *testing.T) {
|
||||
for _, test := range compareTests {
|
||||
if res := test.v1.Compare(test.v2); res != test.result {
|
||||
t.Errorf("Comparing %q : %q, expected %d but got %d", test.v1, test.v2, test.result, res)
|
||||
}
|
||||
//Test counterpart
|
||||
if res := test.v2.Compare(test.v1); res != -test.result {
|
||||
t.Errorf("Comparing %q : %q, expected %d but got %d", test.v2, test.v1, -test.result, res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type wrongformatTest struct {
|
||||
v *Version
|
||||
str string
|
||||
}
|
||||
|
||||
var wrongformatTests = []wrongformatTest{
|
||||
{nil, ""},
|
||||
{nil, "."},
|
||||
{nil, "1."},
|
||||
{nil, ".1"},
|
||||
{nil, "a.b.c"},
|
||||
{nil, "1.a.b"},
|
||||
{nil, "1.1.a"},
|
||||
{nil, "1.a.1"},
|
||||
{nil, "a.1.1"},
|
||||
{nil, ".."},
|
||||
{nil, "1.."},
|
||||
{nil, "1.1."},
|
||||
{nil, "1..1"},
|
||||
{nil, "1.1.+123"},
|
||||
{nil, "1.1.-beta"},
|
||||
{nil, "-1.1.1"},
|
||||
{nil, "1.-1.1"},
|
||||
{nil, "1.1.-1"},
|
||||
// giant numbers
|
||||
{nil, "20000000000000000000.1.1"},
|
||||
{nil, "1.20000000000000000000.1"},
|
||||
{nil, "1.1.20000000000000000000"},
|
||||
{nil, "1.1.1-20000000000000000000"},
|
||||
// Leading zeroes
|
||||
{nil, "01.1.1"},
|
||||
{nil, "001.1.1"},
|
||||
{nil, "1.01.1"},
|
||||
{nil, "1.001.1"},
|
||||
{nil, "1.1.01"},
|
||||
{nil, "1.1.001"},
|
||||
{nil, "1.1.1-01"},
|
||||
{nil, "1.1.1-001"},
|
||||
{nil, "1.1.1-beta.01"},
|
||||
{nil, "1.1.1-beta.001"},
|
||||
{&Version{0, 0, 0, []PRVersion{prstr("!")}, nil}, "0.0.0-!"},
|
||||
{&Version{0, 0, 0, nil, []string{"!"}}, "0.0.0+!"},
|
||||
// empty prversion
|
||||
{&Version{0, 0, 0, []PRVersion{prstr(""), prstr("alpha")}, nil}, "0.0.0-.alpha"},
|
||||
// empty build meta data
|
||||
{&Version{0, 0, 0, []PRVersion{prstr("alpha")}, []string{""}}, "0.0.0-alpha+"},
|
||||
{&Version{0, 0, 0, []PRVersion{prstr("alpha")}, []string{"test", ""}}, "0.0.0-alpha+test."},
|
||||
}
|
||||
|
||||
func TestWrongFormat(t *testing.T) {
|
||||
for _, test := range wrongformatTests {
|
||||
|
||||
if res, err := Parse(test.str); err == nil {
|
||||
t.Errorf("Parsing wrong format version %q, expected error but got %q", test.str, res)
|
||||
}
|
||||
|
||||
if test.v != nil {
|
||||
if err := test.v.Validate(); err == nil {
|
||||
t.Errorf("Validating wrong format version %q (%q), expected error", test.v, test.str)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var wrongTolerantFormatTests = []wrongformatTest{
|
||||
{nil, "1.0+abc"},
|
||||
{nil, "1.0-rc.1"},
|
||||
}
|
||||
|
||||
func TestWrongTolerantFormat(t *testing.T) {
|
||||
for _, test := range wrongTolerantFormatTests {
|
||||
if res, err := ParseTolerant(test.str); err == nil {
|
||||
t.Errorf("Parsing wrong format version %q, expected error but got %q", test.str, res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareHelper(t *testing.T) {
|
||||
v := Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil}
|
||||
v1 := Version{1, 0, 0, nil, nil}
|
||||
if !v.EQ(v) {
|
||||
t.Errorf("%q should be equal to %q", v, v)
|
||||
}
|
||||
if !v.Equals(v) {
|
||||
t.Errorf("%q should be equal to %q", v, v)
|
||||
}
|
||||
if !v1.NE(v) {
|
||||
t.Errorf("%q should not be equal to %q", v1, v)
|
||||
}
|
||||
if !v.GTE(v) {
|
||||
t.Errorf("%q should be greater than or equal to %q", v, v)
|
||||
}
|
||||
if !v.LTE(v) {
|
||||
t.Errorf("%q should be less than or equal to %q", v, v)
|
||||
}
|
||||
if !v.LT(v1) {
|
||||
t.Errorf("%q should be less than %q", v, v1)
|
||||
}
|
||||
if !v.LTE(v1) {
|
||||
t.Errorf("%q should be less than or equal %q", v, v1)
|
||||
}
|
||||
if !v.LE(v1) {
|
||||
t.Errorf("%q should be less than or equal %q", v, v1)
|
||||
}
|
||||
if !v1.GT(v) {
|
||||
t.Errorf("%q should be greater than %q", v1, v)
|
||||
}
|
||||
if !v1.GTE(v) {
|
||||
t.Errorf("%q should be greater than or equal %q", v1, v)
|
||||
}
|
||||
if !v1.GE(v) {
|
||||
t.Errorf("%q should be greater than or equal %q", v1, v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreReleaseVersions(t *testing.T) {
|
||||
p1, err := NewPRVersion("123")
|
||||
if !p1.IsNumeric() {
|
||||
t.Errorf("Expected numeric prversion, got %q", p1)
|
||||
}
|
||||
if p1.VersionNum != 123 {
|
||||
t.Error("Wrong prversion number")
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Not expected error %q", err)
|
||||
}
|
||||
p2, err := NewPRVersion("alpha")
|
||||
if p2.IsNumeric() {
|
||||
t.Errorf("Expected non-numeric prversion, got %q", p2)
|
||||
}
|
||||
if p2.VersionStr != "alpha" {
|
||||
t.Error("Wrong prversion string")
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Not expected error %q", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMetaDataVersions(t *testing.T) {
|
||||
_, err := NewBuildVersion("123")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error %q", err)
|
||||
}
|
||||
|
||||
_, err = NewBuildVersion("build")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error %q", err)
|
||||
}
|
||||
|
||||
_, err = NewBuildVersion("test?")
|
||||
if err == nil {
|
||||
t.Error("Expected error, got none")
|
||||
}
|
||||
|
||||
_, err = NewBuildVersion("")
|
||||
if err == nil {
|
||||
t.Error("Expected error, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewHelper(t *testing.T) {
|
||||
v, err := New("1.2.3")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error %q", err)
|
||||
}
|
||||
|
||||
// New returns pointer
|
||||
if v == nil {
|
||||
t.Fatal("Version is nil")
|
||||
}
|
||||
if v.Compare(Version{1, 2, 3, nil, nil}) != 0 {
|
||||
t.Fatal("Unexpected comparison problem")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMakeHelper(t *testing.T) {
|
||||
v, err := Make("1.2.3")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error %q", err)
|
||||
}
|
||||
if v.Compare(Version{1, 2, 3, nil, nil}) != 0 {
|
||||
t.Fatal("Unexpected comparison problem")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseSimple(b *testing.B) {
|
||||
const VERSION = "0.0.1"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
Parse(VERSION)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseComplex(b *testing.B) {
|
||||
const VERSION = "0.0.1-alpha.preview+123.456"
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
Parse(VERSION)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseAverage(b *testing.B) {
|
||||
l := len(formatTests)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
Parse(formatTests[n%l].result)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseTolerantAverage(b *testing.B) {
|
||||
l := len(tolerantFormatTests)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
ParseTolerant(tolerantFormatTests[n%l].result)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkStringSimple(b *testing.B) {
|
||||
const VERSION = "0.0.1"
|
||||
v, _ := Parse(VERSION)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
v.String()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkStringLarger(b *testing.B) {
|
||||
const VERSION = "11.15.2012"
|
||||
v, _ := Parse(VERSION)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
v.String()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkStringComplex(b *testing.B) {
|
||||
const VERSION = "0.0.1-alpha.preview+123.456"
|
||||
v, _ := Parse(VERSION)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
v.String()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkStringAverage(b *testing.B) {
|
||||
l := len(formatTests)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
formatTests[n%l].v.String()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkValidateSimple(b *testing.B) {
|
||||
const VERSION = "0.0.1"
|
||||
v, _ := Parse(VERSION)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
v.Validate()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkValidateComplex(b *testing.B) {
|
||||
const VERSION = "0.0.1-alpha.preview+123.456"
|
||||
v, _ := Parse(VERSION)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
v.Validate()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkValidateAverage(b *testing.B) {
|
||||
l := len(formatTests)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
formatTests[n%l].v.Validate()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCompareSimple(b *testing.B) {
|
||||
const VERSION = "0.0.1"
|
||||
v, _ := Parse(VERSION)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
v.Compare(v)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCompareComplex(b *testing.B) {
|
||||
const VERSION = "0.0.1-alpha.preview+123.456"
|
||||
v, _ := Parse(VERSION)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
v.Compare(v)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCompareAverage(b *testing.B) {
|
||||
l := len(compareTests)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
compareTests[n%l].v1.Compare((compareTests[n%l].v2))
|
||||
}
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
package semver
|
||||
|
||||
import (
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Versions represents multiple versions.
|
||||
type Versions []Version
|
||||
|
||||
// Len returns length of version collection
|
||||
func (s Versions) Len() int {
|
||||
return len(s)
|
||||
}
|
||||
|
||||
// Swap swaps two versions inside the collection by its indices
|
||||
func (s Versions) Swap(i, j int) {
|
||||
s[i], s[j] = s[j], s[i]
|
||||
}
|
||||
|
||||
// Less checks if version at index i is less than version at index j
|
||||
func (s Versions) Less(i, j int) bool {
|
||||
return s[i].LT(s[j])
|
||||
}
|
||||
|
||||
// Sort sorts a slice of versions
|
||||
func Sort(versions []Version) {
|
||||
sort.Sort(Versions(versions))
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package semver
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSort(t *testing.T) {
|
||||
v100, _ := Parse("1.0.0")
|
||||
v010, _ := Parse("0.1.0")
|
||||
v001, _ := Parse("0.0.1")
|
||||
versions := []Version{v010, v100, v001}
|
||||
Sort(versions)
|
||||
|
||||
correct := []Version{v001, v010, v100}
|
||||
if !reflect.DeepEqual(versions, correct) {
|
||||
t.Fatalf("Sort returned wrong order: %s", versions)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkSort(b *testing.B) {
|
||||
v100, _ := Parse("1.0.0")
|
||||
v010, _ := Parse("0.1.0")
|
||||
v001, _ := Parse("0.0.1")
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
Sort([]Version{v010, v100, v001})
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package semver
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Scan implements the database/sql.Scanner interface.
|
||||
func (v *Version) Scan(src interface{}) (err error) {
|
||||
var str string
|
||||
switch src := src.(type) {
|
||||
case string:
|
||||
str = src
|
||||
case []byte:
|
||||
str = string(src)
|
||||
default:
|
||||
return fmt.Errorf("Version.Scan: cannot convert %T to string.", src)
|
||||
}
|
||||
|
||||
if t, err := Parse(str); err == nil {
|
||||
*v = t
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Value implements the database/sql/driver.Valuer interface.
|
||||
func (v Version) Value() (driver.Value, error) {
|
||||
return v.String(), nil
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package semver
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
type scanTest struct {
|
||||
val interface{}
|
||||
shouldError bool
|
||||
expected string
|
||||
}
|
||||
|
||||
var scanTests = []scanTest{
|
||||
{"1.2.3", false, "1.2.3"},
|
||||
{[]byte("1.2.3"), false, "1.2.3"},
|
||||
{7, true, ""},
|
||||
{7e4, true, ""},
|
||||
{true, true, ""},
|
||||
}
|
||||
|
||||
func TestScanString(t *testing.T) {
|
||||
for _, tc := range scanTests {
|
||||
s := &Version{}
|
||||
err := s.Scan(tc.val)
|
||||
if tc.shouldError {
|
||||
if err == nil {
|
||||
t.Fatalf("Scan did not return an error on %v (%T)", tc.val, tc.val)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Fatalf("Scan returned an unexpected error: %s (%T) on %v (%T)", tc.val, tc.val, tc.val, tc.val)
|
||||
}
|
||||
if val, _ := s.Value(); val != tc.expected {
|
||||
t.Errorf("Wrong Value returned, expected %q, got %q", tc.expected, val)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
This Source Code Form is subject to the terms of the Mozilla Public License,
|
||||
v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
|
||||
one at http://mozilla.org/MPL/2.0/.
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
# GoCertifi: SSL Certificates for Golang
|
||||
|
||||
This Go package contains a CA bundle that you can reference in your Go code.
|
||||
This is useful for systems that do not have CA bundles that Golang can find
|
||||
itself, or where a uniform set of CAs is valuable.
|
||||
|
||||
This is the same CA bundle that ships with the
|
||||
[Python Requests](https://github.com/kennethreitz/requests) library, and is a
|
||||
Golang specific port of [certifi](https://github.com/kennethreitz/certifi). The
|
||||
CA bundle is derived from Mozilla's canonical set.
|
||||
|
||||
## Usage
|
||||
|
||||
You can use the `gocertifi` package as follows:
|
||||
|
||||
```go
|
||||
import "github.com/certifi/gocertifi"
|
||||
|
||||
cert_pool, err := gocertifi.CACerts()
|
||||
```
|
||||
|
||||
You can use the returned `*x509.CertPool` as part of an HTTP transport, for example:
|
||||
|
||||
```go
|
||||
import (
|
||||
"net/http"
|
||||
"crypto/tls"
|
||||
)
|
||||
|
||||
// Setup an HTTP client with a custom transport
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{RootCAs: cert_pool},
|
||||
}
|
||||
client := &http.Client{Transport: transport}
|
||||
|
||||
// Make an HTTP request using our custom transport
|
||||
resp, err := client.Get("https://example.com")
|
||||
```
|
||||
|
||||
## Detailed Documentation
|
||||
|
||||
Import as follows:
|
||||
|
||||
```go
|
||||
import "github.com/certifi/gocertifi"
|
||||
```
|
||||
|
||||
### Errors
|
||||
|
||||
```go
|
||||
var ErrParseFailed = errors.New("gocertifi: error when parsing certificates")
|
||||
```
|
||||
|
||||
### Functions
|
||||
|
||||
```go
|
||||
func CACerts() (*x509.CertPool, error)
|
||||
```
|
||||
CACerts builds an X.509 certificate pool containing the Mozilla CA Certificate
|
||||
bundle. Returns nil on error along with an appropriate error code.
|
||||
-5269
File diff suppressed because it is too large
Load Diff
-10
@@ -1,10 +0,0 @@
|
||||
package gocertifi
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGetCerts(t *testing.T) {
|
||||
cert_pool, err := CACerts()
|
||||
if (cert_pool == nil) || (err != nil) {
|
||||
t.Errorf("Failed to return the certificates.")
|
||||
}
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
from invoke import task
|
||||
import requests
|
||||
|
||||
@task
|
||||
def update(ctx):
|
||||
r = requests.get('https://mkcert.org/generate/')
|
||||
r.raise_for_status()
|
||||
certs = r.content
|
||||
|
||||
with open('certifi.go', 'rb') as f:
|
||||
file = f.read()
|
||||
|
||||
file = file.split('`\n')
|
||||
assert len(file) == 3
|
||||
file[1] = certs
|
||||
|
||||
ctx.run("rm certifi.go")
|
||||
|
||||
with open('certifi.go', 'wb') as f:
|
||||
f.write('`\n'.join(file))
|
||||
-1
@@ -1 +0,0 @@
|
||||
# added hound style checking
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
language: go
|
||||
go:
|
||||
- 1.6
|
||||
- tip
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
ISC license
|
||||
Copyright (c) 2014, Frank Rosquin
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
-94
@@ -1,94 +0,0 @@
|
||||
# structhash [](https://godoc.org/github.com/cnf/structhash) [](https://travis-ci.org/cnf/structhash)
|
||||
|
||||
structhash is a Go library for generating hash strings of arbitrary data structures.
|
||||
|
||||
## Features
|
||||
|
||||
* fields may be ignored or renamed (like in `json.Marshal`, but using different struct tag)
|
||||
* fields may be versioned
|
||||
* fields order in struct doesn't matter (unlike `json.Marshal`)
|
||||
* nil values are treated equally to zero values
|
||||
|
||||
## Installation
|
||||
|
||||
Standard `go get`:
|
||||
|
||||
```
|
||||
$ go get github.com/cnf/structhash
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
For usage and examples see the [Godoc](http://godoc.org/github.com/cnf/structhash).
|
||||
|
||||
## Quick start
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"github.com/cnf/structhash"
|
||||
)
|
||||
|
||||
type S struct {
|
||||
Str string
|
||||
Num int
|
||||
}
|
||||
|
||||
func main() {
|
||||
s := S{"hello", 123}
|
||||
|
||||
hash, err := structhash.Hash(s, 1)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Println(hash)
|
||||
// Prints: v1_41011bfa1a996db6d0b1075981f5aa8f
|
||||
|
||||
fmt.Println(structhash.Version(hash))
|
||||
// Prints: 1
|
||||
|
||||
fmt.Printf("%x\n", structhash.Md5(s, 1))
|
||||
// Prints: 41011bfa1a996db6d0b1075981f5aa8f
|
||||
|
||||
fmt.Printf("%x\n", structhash.Sha1(s, 1))
|
||||
// Prints: 5ff72df7212ce8c55838fb3ec6ad0c019881a772
|
||||
|
||||
fmt.Printf("%x\n", md5.Sum(structhash.Dump(s, 1)))
|
||||
// Prints: 41011bfa1a996db6d0b1075981f5aa8f
|
||||
|
||||
fmt.Printf("%x\n", sha1.Sum(structhash.Dump(s, 1)))
|
||||
// Prints: 5ff72df7212ce8c55838fb3ec6ad0c019881a772
|
||||
}
|
||||
```
|
||||
|
||||
## Struct tags
|
||||
|
||||
structhash supports struct tags in the following forms:
|
||||
|
||||
* `hash:"-"`, or
|
||||
* `hash:"name:{string} version:{number} lastversion:{number}"`
|
||||
|
||||
All fields are optional and may be ommitted. Their semantics is:
|
||||
|
||||
* `-` - ignore field
|
||||
* `name:{string}` - rename field (may be useful when you want to rename field but keep hashes unchanged for backward compatibility)
|
||||
* `version:{number}` - ignore field if version passed to structhash is smaller than given number
|
||||
* `lastversion:{number}` - ignore field if version passed to structhash is greater than given number
|
||||
|
||||
Example:
|
||||
|
||||
```go
|
||||
type MyStruct struct {
|
||||
Ignored string `hash:"-"`
|
||||
Renamed string `hash:"name:OldName version:1"`
|
||||
Legacy string `hash:"version:1 lastversion:2"`
|
||||
}
|
||||
```
|
||||
|
||||
## Nil values
|
||||
|
||||
When hash is calculated, nil pointers, nil slices, and nil maps are treated equally to zero values of corresponding type. E.g., nil pointer to string is equivalent to empty string, and nil slice is equivalent to empty slice.
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
/*
|
||||
Package structhash creates hash strings from arbitrary go data structures.
|
||||
*/
|
||||
package structhash
|
||||
-244
@@ -1,244 +0,0 @@
|
||||
package structhash
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Version returns the version of the supplied hash as an integer
|
||||
// or -1 on failure
|
||||
func Version(h string) int {
|
||||
if h == "" {
|
||||
return -1
|
||||
}
|
||||
if h[0] != 'v' {
|
||||
return -1
|
||||
}
|
||||
if spos := strings.IndexRune(h[1:], '_'); spos >= 0 {
|
||||
n, e := strconv.Atoi(h[1 : spos+1])
|
||||
if e != nil {
|
||||
return -1
|
||||
}
|
||||
return n
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Hash takes a data structure and returns a hash string of that data structure
|
||||
// at the version asked.
|
||||
//
|
||||
// This function uses md5 hashing function and default formatter. See also Dump()
|
||||
// function.
|
||||
func Hash(c interface{}, version int) (string, error) {
|
||||
return fmt.Sprintf("v%d_%x", version, Md5(c, version)), nil
|
||||
}
|
||||
|
||||
// Dump takes a data structure and returns its byte representation. This can be
|
||||
// useful if you need to use your own hashing function or formatter.
|
||||
func Dump(c interface{}, version int) []byte {
|
||||
return serialize(c, version)
|
||||
}
|
||||
|
||||
// Md5 takes a data structure and returns its md5 hash.
|
||||
// This is a shorthand for md5.Sum(Dump(c, version)).
|
||||
func Md5(c interface{}, version int) []byte {
|
||||
sum := md5.Sum(Dump(c, version))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
// Sha1 takes a data structure and returns its sha1 hash.
|
||||
// This is a shorthand for sha1.Sum(Dump(c, version)).
|
||||
func Sha1(c interface{}, version int) []byte {
|
||||
sum := sha1.Sum(Dump(c, version))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
type item struct {
|
||||
name string
|
||||
value reflect.Value
|
||||
}
|
||||
|
||||
type itemSorter []item
|
||||
|
||||
func (s itemSorter) Len() int {
|
||||
return len(s)
|
||||
}
|
||||
|
||||
func (s itemSorter) Swap(i, j int) {
|
||||
s[i], s[j] = s[j], s[i]
|
||||
}
|
||||
|
||||
func (s itemSorter) Less(i, j int) bool {
|
||||
return s[i].name < s[j].name
|
||||
}
|
||||
|
||||
type structFieldFilter func(reflect.StructField) (string, bool)
|
||||
|
||||
func writeValue(buf *bytes.Buffer, val reflect.Value, fltr structFieldFilter) {
|
||||
switch val.Kind() {
|
||||
case reflect.String:
|
||||
buf.WriteByte('"')
|
||||
buf.WriteString(val.String())
|
||||
buf.WriteByte('"')
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
buf.WriteString(strconv.FormatInt(val.Int(), 10))
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
buf.WriteString(strconv.FormatUint(val.Uint(), 10))
|
||||
case reflect.Float32, reflect.Float64:
|
||||
buf.WriteString(strconv.FormatFloat(val.Float(), 'E', -1, 64))
|
||||
case reflect.Bool:
|
||||
if val.Bool() {
|
||||
buf.WriteByte('t')
|
||||
} else {
|
||||
buf.WriteByte('f')
|
||||
}
|
||||
case reflect.Ptr:
|
||||
if !val.IsNil() || val.Type().Elem().Kind() == reflect.Struct {
|
||||
writeValue(buf, reflect.Indirect(val), fltr)
|
||||
} else {
|
||||
writeValue(buf, reflect.Zero(val.Type().Elem()), fltr)
|
||||
}
|
||||
case reflect.Array, reflect.Slice:
|
||||
buf.WriteByte('[')
|
||||
len := val.Len()
|
||||
for i := 0; i < len; i++ {
|
||||
if i != 0 {
|
||||
buf.WriteByte(',')
|
||||
}
|
||||
writeValue(buf, val.Index(i), fltr)
|
||||
}
|
||||
buf.WriteByte(']')
|
||||
case reflect.Map:
|
||||
mk := val.MapKeys()
|
||||
items := make([]item, len(mk), len(mk))
|
||||
// Get all values
|
||||
for i, _ := range items {
|
||||
items[i].name = formatValue(mk[i], fltr)
|
||||
items[i].value = val.MapIndex(mk[i])
|
||||
}
|
||||
|
||||
// Sort values by key
|
||||
sort.Sort(itemSorter(items))
|
||||
|
||||
buf.WriteByte('[')
|
||||
for i, _ := range items {
|
||||
if i != 0 {
|
||||
buf.WriteByte(',')
|
||||
}
|
||||
buf.WriteString(items[i].name)
|
||||
buf.WriteByte(':')
|
||||
writeValue(buf, items[i].value, fltr)
|
||||
}
|
||||
buf.WriteByte(']')
|
||||
case reflect.Struct:
|
||||
vtype := val.Type()
|
||||
flen := vtype.NumField()
|
||||
items := make([]item, 0, flen)
|
||||
// Get all fields
|
||||
for i := 0; i < flen; i++ {
|
||||
field := vtype.Field(i)
|
||||
it := item{field.Name, val.Field(i)}
|
||||
if fltr != nil {
|
||||
if name, ok := fltr(field); ok {
|
||||
it.name = name
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
}
|
||||
items = append(items, it)
|
||||
}
|
||||
// Sort fields by name
|
||||
sort.Sort(itemSorter(items))
|
||||
|
||||
buf.WriteByte('{')
|
||||
for i, _ := range items {
|
||||
if i != 0 {
|
||||
buf.WriteByte(',')
|
||||
}
|
||||
buf.WriteString(items[i].name)
|
||||
buf.WriteByte(':')
|
||||
writeValue(buf, items[i].value, fltr)
|
||||
}
|
||||
buf.WriteByte('}')
|
||||
case reflect.Interface:
|
||||
writeValue(buf, reflect.ValueOf(val.Interface()), fltr)
|
||||
default:
|
||||
buf.WriteString(val.String())
|
||||
}
|
||||
}
|
||||
|
||||
func formatValue(val reflect.Value, fltr structFieldFilter) string {
|
||||
if val.Kind() == reflect.String {
|
||||
return "\"" + val.String() + "\""
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
writeValue(&buf, val, fltr)
|
||||
|
||||
return string(buf.Bytes())
|
||||
}
|
||||
|
||||
func filterField(f reflect.StructField, version int) (string, bool) {
|
||||
var err error
|
||||
name := f.Name
|
||||
ver := 0
|
||||
lastver := -1
|
||||
if str := f.Tag.Get("hash"); str != "" {
|
||||
if str == "-" {
|
||||
return "", false
|
||||
}
|
||||
for _, tag := range strings.Split(str, " ") {
|
||||
args := strings.Split(strings.TrimSpace(tag), ":")
|
||||
if len(args) != 2 {
|
||||
return "", false
|
||||
}
|
||||
switch args[0] {
|
||||
case "name":
|
||||
name = args[1]
|
||||
case "version":
|
||||
if ver, err = strconv.Atoi(args[1]); err != nil {
|
||||
return "", false
|
||||
}
|
||||
case "lastversion":
|
||||
if lastver, err = strconv.Atoi(args[1]); err != nil {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if str := f.Tag.Get("lastversion"); str != "" {
|
||||
if lastver, err = strconv.Atoi(str); err != nil {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
if str := f.Tag.Get("version"); str != "" {
|
||||
if ver, err = strconv.Atoi(str); err != nil {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
}
|
||||
if lastver != -1 && lastver < version {
|
||||
return "", false
|
||||
}
|
||||
if ver > version {
|
||||
return "", false
|
||||
}
|
||||
return name, true
|
||||
}
|
||||
|
||||
func serialize(object interface{}, version int) []byte {
|
||||
var buf bytes.Buffer
|
||||
|
||||
writeValue(&buf, reflect.ValueOf(object),
|
||||
func(f reflect.StructField) (string, bool) {
|
||||
return filterField(f, version)
|
||||
})
|
||||
|
||||
return buf.Bytes()
|
||||
}
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
package structhash
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type BenchData struct {
|
||||
Bool bool
|
||||
String string
|
||||
Int int
|
||||
Uint uint
|
||||
Map map[string]*BenchData
|
||||
Slice []*BenchData
|
||||
Struct *BenchData
|
||||
}
|
||||
|
||||
type BenchTags struct {
|
||||
Bool bool `json:"f1" hash:"name:f1"`
|
||||
String string `json:"f2" hash:"name:f2"`
|
||||
Int int `json:"f3" hash:"name:f3"`
|
||||
Uint uint `json:"f4" hash:"name:f4"`
|
||||
}
|
||||
|
||||
func benchDataSimple() *BenchData {
|
||||
return &BenchData{true, "simple", -123, 321, nil, nil, nil}
|
||||
}
|
||||
|
||||
func benchDataFull() *BenchData {
|
||||
foo := benchDataSimple()
|
||||
bar := benchDataSimple()
|
||||
|
||||
m := make(map[string]*BenchData)
|
||||
m["foo"] = foo
|
||||
m["bar"] = bar
|
||||
|
||||
s := []*BenchData{
|
||||
foo,
|
||||
bar,
|
||||
}
|
||||
|
||||
return &BenchData{true, "hello", -123, 321, m, s, foo}
|
||||
}
|
||||
|
||||
func benchDataTags() *BenchTags {
|
||||
return &BenchTags{true, "tags", -123, 321}
|
||||
}
|
||||
|
||||
func BenchmarkSimpleJSON(b *testing.B) {
|
||||
s := benchDataSimple()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
json.Marshal(s)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkSimpleDump(b *testing.B) {
|
||||
s := benchDataSimple()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
Dump(s, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFullJSON(b *testing.B) {
|
||||
s := benchDataFull()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
json.Marshal(s)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFullDump(b *testing.B) {
|
||||
s := benchDataFull()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
Dump(s, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkTagsJSON(b *testing.B) {
|
||||
s := benchDataTags()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
json.Marshal(s)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkTagsDump(b *testing.B) {
|
||||
s := benchDataTags()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
Dump(s, 1)
|
||||
}
|
||||
}
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
package structhash
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func ExampleHash() {
|
||||
type Person struct {
|
||||
Name string
|
||||
Age int
|
||||
Emails []string
|
||||
Extra map[string]string
|
||||
Spouse *Person
|
||||
}
|
||||
bill := &Person{
|
||||
Name: "Bill",
|
||||
Age: 24,
|
||||
Emails: []string{"bob@foo.org", "bob@bar.org"},
|
||||
Extra: map[string]string{
|
||||
"facebook": "Bob42",
|
||||
},
|
||||
}
|
||||
bob := &Person{
|
||||
Name: "Bob",
|
||||
Age: 42,
|
||||
Emails: []string{"bob@foo.org", "bob@bar.org"},
|
||||
Extra: map[string]string{
|
||||
"facebook": "Bob42",
|
||||
},
|
||||
Spouse: bill,
|
||||
}
|
||||
|
||||
hash, err := Hash(bob, 1)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("%s", hash)
|
||||
// Output:
|
||||
// v1_6a50d73f3bd0b9ebd001a0b610f387f0
|
||||
}
|
||||
|
||||
func ExampleHash_tags() {
|
||||
type Person struct {
|
||||
Ignored string `hash:"-"`
|
||||
NewName string `hash:"name:OldName version:1"`
|
||||
Age int `hash:"version:1"`
|
||||
Emails []string `hash:"version:1"`
|
||||
Extra map[string]string `hash:"version:1 lastversion:2"`
|
||||
Spouse *Person `hash:"version:2"`
|
||||
}
|
||||
bill := &Person{
|
||||
NewName: "Bill",
|
||||
Age: 24,
|
||||
Emails: []string{"bob@foo.org", "bob@bar.org"},
|
||||
Extra: map[string]string{
|
||||
"facebook": "Bob42",
|
||||
},
|
||||
}
|
||||
bob := &Person{
|
||||
NewName: "Bob",
|
||||
Age: 42,
|
||||
Emails: []string{"bob@foo.org", "bob@bar.org"},
|
||||
Extra: map[string]string{
|
||||
"facebook": "Bob42",
|
||||
},
|
||||
Spouse: bill,
|
||||
}
|
||||
hashV1, err := Hash(bob, 1)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
hashV2, err := Hash(bob, 2)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
hashV3, err := Hash(bob, 3)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("%s\n", hashV1)
|
||||
fmt.Printf("%s\n", hashV2)
|
||||
fmt.Printf("%s\n", hashV3)
|
||||
// Output:
|
||||
// v1_45d8a54c5f5fd287f197b26d128882cd
|
||||
// v2_babd7618f29036f5564816bee6c8a037
|
||||
// v3_012b06239f942549772c9139d66c121e
|
||||
}
|
||||
|
||||
func ExampleDump() {
|
||||
type Person struct {
|
||||
Name string
|
||||
Age int
|
||||
Emails []string
|
||||
Extra map[string]string
|
||||
Spouse *Person
|
||||
}
|
||||
bill := &Person{
|
||||
Name: "Bill",
|
||||
Age: 24,
|
||||
Emails: []string{"bob@foo.org", "bob@bar.org"},
|
||||
Extra: map[string]string{
|
||||
"facebook": "Bob42",
|
||||
},
|
||||
}
|
||||
bob := &Person{
|
||||
Name: "Bob",
|
||||
Age: 42,
|
||||
Emails: []string{"bob@foo.org", "bob@bar.org"},
|
||||
Extra: map[string]string{
|
||||
"facebook": "Bob42",
|
||||
},
|
||||
Spouse: bill,
|
||||
}
|
||||
|
||||
fmt.Printf("md5: %x\n", md5.Sum(Dump(bob, 1)))
|
||||
fmt.Printf("sha1: %x\n", sha1.Sum(Dump(bob, 1)))
|
||||
// Output:
|
||||
// md5: 6a50d73f3bd0b9ebd001a0b610f387f0
|
||||
// sha1: c45f097a37366eaaf6ffbc7357c2272cd8fb64f6
|
||||
}
|
||||
|
||||
func ExampleVersion() {
|
||||
// A hash string gotten from Hash(). Returns the version as an int.
|
||||
i := Version("v1_55743877f3ffd5fc834e97bc43a6e7bd")
|
||||
fmt.Printf("%d", i)
|
||||
// Output:
|
||||
// 1
|
||||
}
|
||||
|
||||
func ExampleVersion_errors() {
|
||||
// A hash string gotten from Hash(). Returns -1 on error.
|
||||
i := Version("va_55743877f3ffd5fc834e97bc43a6e7bd")
|
||||
fmt.Printf("%d", i)
|
||||
// Output:
|
||||
// -1
|
||||
}
|
||||
-247
@@ -1,247 +0,0 @@
|
||||
package structhash
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type First struct {
|
||||
Bool bool `version:"1"`
|
||||
String string `version:"2"`
|
||||
Int int `version:"1" lastversion:"1"`
|
||||
Float float64 `version:"1"`
|
||||
Struct *Second `version:"1"`
|
||||
Uint uint `version:"1"`
|
||||
}
|
||||
|
||||
type Second struct {
|
||||
Map map[string]string `version:"1"`
|
||||
Slice []int `version:"1"`
|
||||
}
|
||||
|
||||
type Tags1 struct {
|
||||
Int int `hash:"-"`
|
||||
Str string `hash:"name:Foo version:1 lastversion:2"`
|
||||
Bar string `hash:"version:1"`
|
||||
}
|
||||
|
||||
type Tags2 struct {
|
||||
Foo string
|
||||
Bar string
|
||||
}
|
||||
|
||||
type Tags3 struct {
|
||||
Bar string
|
||||
}
|
||||
|
||||
type Nils struct {
|
||||
Str *string
|
||||
Int *int
|
||||
Bool *bool
|
||||
Map map[string]string
|
||||
Slice []string
|
||||
}
|
||||
|
||||
type unexportedTags struct {
|
||||
foo string
|
||||
bar string
|
||||
aMap map[string]string
|
||||
}
|
||||
|
||||
type interfaceStruct struct {
|
||||
Name string
|
||||
Interface1 interface{}
|
||||
InterfaceIgnore interface{} `hash:"-"`
|
||||
}
|
||||
|
||||
func dataSetup() *First {
|
||||
tmpmap := make(map[string]string)
|
||||
tmpmap["foo"] = "bar"
|
||||
tmpmap["baz"] = "go"
|
||||
tmpslice := make([]int, 3)
|
||||
tmpslice[0] = 0
|
||||
tmpslice[1] = 1
|
||||
tmpslice[2] = 2
|
||||
return &First{
|
||||
Bool: true,
|
||||
String: "test",
|
||||
Int: 123456789,
|
||||
Float: 65.3458,
|
||||
Struct: &Second{
|
||||
Map: tmpmap,
|
||||
Slice: tmpslice,
|
||||
},
|
||||
Uint: 1,
|
||||
}
|
||||
}
|
||||
|
||||
func TestHash(t *testing.T) {
|
||||
v1Hash := "v1_e8e67581aee36d7237603381a9cbd9fc"
|
||||
v2Hash := "v2_5e51490d7c24c4b7a9e63c04f55734eb"
|
||||
|
||||
data := dataSetup()
|
||||
v1, err := Hash(data, 1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
// fmt.Println(string(Dump(data, 1)))
|
||||
if v1 != v1Hash {
|
||||
t.Errorf("%s is not %s", v1, v1Hash)
|
||||
}
|
||||
v2, err := Hash(data, 2)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
// fmt.Println(string(Dump(data, 2)))
|
||||
if v2 != v2Hash {
|
||||
t.Errorf("%s is not %s", v2, v2Hash)
|
||||
}
|
||||
|
||||
v1md5 := fmt.Sprintf("v1_%x", Md5(data, 1))
|
||||
if v1md5 != v1Hash {
|
||||
t.Errorf("%s is not %s", v1md5, v1Hash[3:])
|
||||
}
|
||||
v2md5 := fmt.Sprintf("v2_%x", Md5(data, 2))
|
||||
if v2md5 != v2Hash {
|
||||
t.Errorf("%s is not %s", v2md5, v2Hash[3:])
|
||||
}
|
||||
}
|
||||
|
||||
func TestTags(t *testing.T) {
|
||||
t1 := Tags1{11, "foo", "bar"}
|
||||
t1x := Tags1{22, "foo", "bar"}
|
||||
t2 := Tags2{"foo", "bar"}
|
||||
t3 := Tags3{"bar"}
|
||||
|
||||
t1_dump := string(Dump(t1, 1))
|
||||
t1x_dump := string(Dump(t1x, 1))
|
||||
if t1_dump != t1x_dump {
|
||||
t.Errorf("%s is not %s", t1_dump, t1x_dump)
|
||||
}
|
||||
|
||||
t2_dump := string(Dump(t2, 1))
|
||||
if t1_dump != t2_dump {
|
||||
t.Errorf("%s is not %s", t1_dump, t2_dump)
|
||||
}
|
||||
|
||||
t1v3_dump := string(Dump(t1, 3))
|
||||
t3v3_dump := string(Dump(t3, 3))
|
||||
if t1v3_dump != t3v3_dump {
|
||||
t.Errorf("%s is not %s", t1v3_dump, t3v3_dump)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNils(t *testing.T) {
|
||||
s1 := Nils{
|
||||
Str: nil,
|
||||
Int: nil,
|
||||
Bool: nil,
|
||||
Map: nil,
|
||||
Slice: nil,
|
||||
}
|
||||
|
||||
s2 := Nils{
|
||||
Str: new(string),
|
||||
Int: new(int),
|
||||
Bool: new(bool),
|
||||
Map: make(map[string]string),
|
||||
Slice: make([]string, 0),
|
||||
}
|
||||
|
||||
s1_dump := string(Dump(s1, 1))
|
||||
s2_dump := string(Dump(s2, 1))
|
||||
if s1_dump != s2_dump {
|
||||
t.Errorf("%s is not %s", s1_dump, s2_dump)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnexportedFields(t *testing.T) {
|
||||
v1Hash := "v1_750efb7c919caf87f2ab0d119650c87d"
|
||||
data := unexportedTags{
|
||||
foo: "foo",
|
||||
bar: "bar",
|
||||
aMap: map[string]string{
|
||||
"key1": "val",
|
||||
},
|
||||
}
|
||||
v1, err := Hash(data, 1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if v1 != v1Hash {
|
||||
t.Errorf("%s is not %s", v1, v1Hash)
|
||||
}
|
||||
v1md5 := fmt.Sprintf("v1_%x", Md5(data, 1))
|
||||
if v1md5 != v1Hash {
|
||||
t.Errorf("%s is not %s", v1md5, v1Hash[3:])
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterfaceField(t *testing.T) {
|
||||
a := interfaceStruct{
|
||||
Name: "name",
|
||||
Interface1: "a",
|
||||
InterfaceIgnore: "b",
|
||||
}
|
||||
|
||||
b := interfaceStruct{
|
||||
Name: "name",
|
||||
Interface1: "b",
|
||||
InterfaceIgnore: "b",
|
||||
}
|
||||
|
||||
c := interfaceStruct{
|
||||
Name: "name",
|
||||
Interface1: "b",
|
||||
InterfaceIgnore: "c",
|
||||
}
|
||||
|
||||
ha, err := Hash(a, 1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
hb, err := Hash(b, 1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
hc, err := Hash(c, 1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if ha == hb {
|
||||
t.Errorf("%s equals %s", ha, hb)
|
||||
}
|
||||
|
||||
if hb != hc {
|
||||
t.Errorf("%s is not %s", hb, hc)
|
||||
}
|
||||
b.Interface1 = map[string]string{"key": "value"}
|
||||
c.Interface1 = map[string]string{"key": "value"}
|
||||
|
||||
hb, err = Hash(b, 1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
hc, err = Hash(c, 1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if hb != hc {
|
||||
t.Errorf("%s is not %s", hb, hc)
|
||||
}
|
||||
|
||||
c.Interface1 = map[string]string{"key1": "value1"}
|
||||
hc, err = Hash(c, 1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if hb == hc {
|
||||
t.Errorf("%s equals %s", hb, hc)
|
||||
}
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
Copyright (c) 2014, Elazar Leibovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
# go-bindata-assetfs
|
||||
|
||||
Serve embedded files from [jteeuwen/go-bindata](https://github.com/jteeuwen/go-bindata) with `net/http`.
|
||||
|
||||
[GoDoc](http://godoc.org/github.com/elazarl/go-bindata-assetfs)
|
||||
|
||||
### Installation
|
||||
|
||||
Install with
|
||||
|
||||
$ go get github.com/jteeuwen/go-bindata/...
|
||||
$ go get github.com/elazarl/go-bindata-assetfs/...
|
||||
|
||||
### Creating embedded data
|
||||
|
||||
Usage is identical to [jteeuwen/go-bindata](https://github.com/jteeuwen/go-bindata) usage,
|
||||
instead of running `go-bindata` run `go-bindata-assetfs`.
|
||||
|
||||
The tool will create a `bindata_assetfs.go` file, which contains the embedded data.
|
||||
|
||||
A typical use case is
|
||||
|
||||
$ go-bindata-assetfs data/...
|
||||
|
||||
### Using assetFS in your code
|
||||
|
||||
The generated file provides an `assetFS()` function that returns a `http.Filesystem`
|
||||
wrapping the embedded files. What you usually want to do is:
|
||||
|
||||
http.Handle("/", http.FileServer(assetFS()))
|
||||
|
||||
This would run an HTTP server serving the embedded files.
|
||||
|
||||
## Without running binary tool
|
||||
|
||||
You can always just run the `go-bindata` tool, and then
|
||||
|
||||
use
|
||||
|
||||
import "github.com/elazarl/go-bindata-assetfs"
|
||||
...
|
||||
http.Handle("/",
|
||||
http.FileServer(
|
||||
&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "data"}))
|
||||
|
||||
to serve files embedded from the `data` directory.
|
||||
-167
@@ -1,167 +0,0 @@
|
||||
package assetfs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
defaultFileTimestamp = time.Now()
|
||||
)
|
||||
|
||||
// FakeFile implements os.FileInfo interface for a given path and size
|
||||
type FakeFile struct {
|
||||
// Path is the path of this file
|
||||
Path string
|
||||
// Dir marks of the path is a directory
|
||||
Dir bool
|
||||
// Len is the length of the fake file, zero if it is a directory
|
||||
Len int64
|
||||
// Timestamp is the ModTime of this file
|
||||
Timestamp time.Time
|
||||
}
|
||||
|
||||
func (f *FakeFile) Name() string {
|
||||
_, name := filepath.Split(f.Path)
|
||||
return name
|
||||
}
|
||||
|
||||
func (f *FakeFile) Mode() os.FileMode {
|
||||
mode := os.FileMode(0644)
|
||||
if f.Dir {
|
||||
return mode | os.ModeDir
|
||||
}
|
||||
return mode
|
||||
}
|
||||
|
||||
func (f *FakeFile) ModTime() time.Time {
|
||||
return f.Timestamp
|
||||
}
|
||||
|
||||
func (f *FakeFile) Size() int64 {
|
||||
return f.Len
|
||||
}
|
||||
|
||||
func (f *FakeFile) IsDir() bool {
|
||||
return f.Mode().IsDir()
|
||||
}
|
||||
|
||||
func (f *FakeFile) Sys() interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// AssetFile implements http.File interface for a no-directory file with content
|
||||
type AssetFile struct {
|
||||
*bytes.Reader
|
||||
io.Closer
|
||||
FakeFile
|
||||
}
|
||||
|
||||
func NewAssetFile(name string, content []byte, timestamp time.Time) *AssetFile {
|
||||
if timestamp.IsZero() {
|
||||
timestamp = defaultFileTimestamp
|
||||
}
|
||||
return &AssetFile{
|
||||
bytes.NewReader(content),
|
||||
ioutil.NopCloser(nil),
|
||||
FakeFile{name, false, int64(len(content)), timestamp}}
|
||||
}
|
||||
|
||||
func (f *AssetFile) Readdir(count int) ([]os.FileInfo, error) {
|
||||
return nil, errors.New("not a directory")
|
||||
}
|
||||
|
||||
func (f *AssetFile) Size() int64 {
|
||||
return f.FakeFile.Size()
|
||||
}
|
||||
|
||||
func (f *AssetFile) Stat() (os.FileInfo, error) {
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// AssetDirectory implements http.File interface for a directory
|
||||
type AssetDirectory struct {
|
||||
AssetFile
|
||||
ChildrenRead int
|
||||
Children []os.FileInfo
|
||||
}
|
||||
|
||||
func NewAssetDirectory(name string, children []string, fs *AssetFS) *AssetDirectory {
|
||||
fileinfos := make([]os.FileInfo, 0, len(children))
|
||||
for _, child := range children {
|
||||
_, err := fs.AssetDir(filepath.Join(name, child))
|
||||
fileinfos = append(fileinfos, &FakeFile{child, err == nil, 0, time.Time{}})
|
||||
}
|
||||
return &AssetDirectory{
|
||||
AssetFile{
|
||||
bytes.NewReader(nil),
|
||||
ioutil.NopCloser(nil),
|
||||
FakeFile{name, true, 0, time.Time{}},
|
||||
},
|
||||
0,
|
||||
fileinfos}
|
||||
}
|
||||
|
||||
func (f *AssetDirectory) Readdir(count int) ([]os.FileInfo, error) {
|
||||
if count <= 0 {
|
||||
return f.Children, nil
|
||||
}
|
||||
if f.ChildrenRead+count > len(f.Children) {
|
||||
count = len(f.Children) - f.ChildrenRead
|
||||
}
|
||||
rv := f.Children[f.ChildrenRead : f.ChildrenRead+count]
|
||||
f.ChildrenRead += count
|
||||
return rv, nil
|
||||
}
|
||||
|
||||
func (f *AssetDirectory) Stat() (os.FileInfo, error) {
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// AssetFS implements http.FileSystem, allowing
|
||||
// embedded files to be served from net/http package.
|
||||
type AssetFS struct {
|
||||
// Asset should return content of file in path if exists
|
||||
Asset func(path string) ([]byte, error)
|
||||
// AssetDir should return list of files in the path
|
||||
AssetDir func(path string) ([]string, error)
|
||||
// AssetInfo should return the info of file in path if exists
|
||||
AssetInfo func(path string) (os.FileInfo, error)
|
||||
// Prefix would be prepended to http requests
|
||||
Prefix string
|
||||
}
|
||||
|
||||
func (fs *AssetFS) Open(name string) (http.File, error) {
|
||||
name = path.Join(fs.Prefix, name)
|
||||
if len(name) > 0 && name[0] == '/' {
|
||||
name = name[1:]
|
||||
}
|
||||
if b, err := fs.Asset(name); err == nil {
|
||||
timestamp := defaultFileTimestamp
|
||||
if fs.AssetInfo != nil {
|
||||
if info, err := fs.AssetInfo(name); err == nil {
|
||||
timestamp = info.ModTime()
|
||||
}
|
||||
}
|
||||
return NewAssetFile(name, b, timestamp), nil
|
||||
}
|
||||
if children, err := fs.AssetDir(name); err == nil {
|
||||
return NewAssetDirectory(name, children, fs), nil
|
||||
} else {
|
||||
// If the error is not found, return an error that will
|
||||
// result in a 404 error. Otherwise the server returns
|
||||
// a 500 error for files not found.
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
// assetfs allows packages to serve static content embedded
|
||||
// with the go-bindata tool with the standard net/http package.
|
||||
//
|
||||
// See https://github.com/jteeuwen/go-bindata for more information
|
||||
// about embedding binary data with go-bindata.
|
||||
//
|
||||
// Usage example, after running
|
||||
// $ go-bindata data/...
|
||||
// use:
|
||||
// http.Handle("/",
|
||||
// http.FileServer(
|
||||
// &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "data"}))
|
||||
package assetfs
|
||||
-1
@@ -1 +0,0 @@
|
||||
.git
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
*.test
|
||||
example/example
|
||||
|
||||
docs/_build
|
||||
docs/doctrees
|
||||
@@ -1,3 +0,0 @@
|
||||
[submodule "docs/_sentryext"]
|
||||
path = docs/_sentryext
|
||||
url = https://github.com/getsentry/sentry-doc-support
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
sudo: false
|
||||
language: go
|
||||
go:
|
||||
- "1.2"
|
||||
- "1.3"
|
||||
- "1.4"
|
||||
- "1.5"
|
||||
- "1.6"
|
||||
- "1.7"
|
||||
- tip
|
||||
|
||||
before_install:
|
||||
- go install -race std
|
||||
- go get golang.org/x/tools/cmd/cover
|
||||
- go get -v ./...
|
||||
|
||||
script:
|
||||
- go test -v -race ./...
|
||||
- go test -v -cover ./...
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: tip
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
FROM golang:1.7
|
||||
|
||||
RUN mkdir -p /go/src/github.com/getsentry/raven-go
|
||||
WORKDIR /go/src/github.com/getsentry/raven-go
|
||||
ENV GOPATH /go
|
||||
|
||||
RUN go install -race std && go get golang.org/x/tools/cmd/cover
|
||||
|
||||
COPY . /go/src/github.com/getsentry/raven-go
|
||||
|
||||
RUN go get -v ./...
|
||||
|
||||
CMD ["./runtests.sh"]
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
Copyright (c) 2013 Apollic Software, LLC. All rights reserved.
|
||||
Copyright (c) 2015 Functional Software, Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Apollic Software, LLC nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
# raven [](https://travis-ci.org/getsentry/raven-go)
|
||||
|
||||
raven is a Go client for the [Sentry](https://github.com/getsentry/sentry)
|
||||
event/error logging system.
|
||||
|
||||
- [**API Documentation**](https://godoc.org/github.com/getsentry/raven-go)
|
||||
- [**Usage and Examples**](https://docs.sentry.io/clients/go/)
|
||||
|
||||
## Installation
|
||||
|
||||
```text
|
||||
go get github.com/getsentry/raven-go
|
||||
```
|
||||
-900
@@ -1,900 +0,0 @@
|
||||
// Package raven implements a client for the Sentry error logging service.
|
||||
package raven
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/certifi/gocertifi"
|
||||
)
|
||||
|
||||
const (
|
||||
userAgent = "raven-go/1.0"
|
||||
timestampFormat = `"2006-01-02T15:04:05.00"`
|
||||
)
|
||||
|
||||
var (
|
||||
ErrPacketDropped = errors.New("raven: packet dropped")
|
||||
ErrUnableToUnmarshalJSON = errors.New("raven: unable to unmarshal JSON")
|
||||
ErrMissingUser = errors.New("raven: dsn missing public key and/or password")
|
||||
ErrMissingPrivateKey = errors.New("raven: dsn missing private key")
|
||||
ErrMissingProjectID = errors.New("raven: dsn missing project id")
|
||||
)
|
||||
|
||||
type Severity string
|
||||
|
||||
// http://docs.python.org/2/howto/logging.html#logging-levels
|
||||
const (
|
||||
DEBUG = Severity("debug")
|
||||
INFO = Severity("info")
|
||||
WARNING = Severity("warning")
|
||||
ERROR = Severity("error")
|
||||
FATAL = Severity("fatal")
|
||||
)
|
||||
|
||||
type Timestamp time.Time
|
||||
|
||||
func (t Timestamp) MarshalJSON() ([]byte, error) {
|
||||
return []byte(time.Time(t).UTC().Format(timestampFormat)), nil
|
||||
}
|
||||
|
||||
func (timestamp *Timestamp) UnmarshalJSON(data []byte) error {
|
||||
t, err := time.Parse(timestampFormat, string(data))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*timestamp = Timestamp(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
// An Interface is a Sentry interface that will be serialized as JSON.
|
||||
// It must implement json.Marshaler or use json struct tags.
|
||||
type Interface interface {
|
||||
// The Sentry class name. Example: sentry.interfaces.Stacktrace
|
||||
Class() string
|
||||
}
|
||||
|
||||
type Culpriter interface {
|
||||
Culprit() string
|
||||
}
|
||||
|
||||
type Transport interface {
|
||||
Send(url, authHeader string, packet *Packet) error
|
||||
}
|
||||
|
||||
type outgoingPacket struct {
|
||||
packet *Packet
|
||||
ch chan error
|
||||
}
|
||||
|
||||
type Tag struct {
|
||||
Key string
|
||||
Value string
|
||||
}
|
||||
|
||||
type Tags []Tag
|
||||
|
||||
func (tag *Tag) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal([2]string{tag.Key, tag.Value})
|
||||
}
|
||||
|
||||
func (t *Tag) UnmarshalJSON(data []byte) error {
|
||||
var tag [2]string
|
||||
if err := json.Unmarshal(data, &tag); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = Tag{tag[0], tag[1]}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Tags) UnmarshalJSON(data []byte) error {
|
||||
var tags []Tag
|
||||
|
||||
switch data[0] {
|
||||
case '[':
|
||||
// Unmarshal into []Tag
|
||||
if err := json.Unmarshal(data, &tags); err != nil {
|
||||
return err
|
||||
}
|
||||
case '{':
|
||||
// Unmarshal into map[string]string
|
||||
tagMap := make(map[string]string)
|
||||
if err := json.Unmarshal(data, &tagMap); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Convert to []Tag
|
||||
for k, v := range tagMap {
|
||||
tags = append(tags, Tag{k, v})
|
||||
}
|
||||
default:
|
||||
return ErrUnableToUnmarshalJSON
|
||||
}
|
||||
|
||||
*t = tags
|
||||
return nil
|
||||
}
|
||||
|
||||
// https://docs.getsentry.com/hosted/clientdev/#building-the-json-packet
|
||||
type Packet struct {
|
||||
// Required
|
||||
Message string `json:"message"`
|
||||
|
||||
// Required, set automatically by Client.Send/Report via Packet.Init if blank
|
||||
EventID string `json:"event_id"`
|
||||
Project string `json:"project"`
|
||||
Timestamp Timestamp `json:"timestamp"`
|
||||
Level Severity `json:"level"`
|
||||
Logger string `json:"logger"`
|
||||
|
||||
// Optional
|
||||
Platform string `json:"platform,omitempty"`
|
||||
Culprit string `json:"culprit,omitempty"`
|
||||
ServerName string `json:"server_name,omitempty"`
|
||||
Release string `json:"release,omitempty"`
|
||||
Environment string `json:"environment,omitempty"`
|
||||
Tags Tags `json:"tags,omitempty"`
|
||||
Modules map[string]string `json:"modules,omitempty"`
|
||||
Fingerprint []string `json:"fingerprint,omitempty"`
|
||||
Extra map[string]interface{} `json:"extra,omitempty"`
|
||||
|
||||
Interfaces []Interface `json:"-"`
|
||||
}
|
||||
|
||||
// NewPacket constructs a packet with the specified message and interfaces.
|
||||
func NewPacket(message string, interfaces ...Interface) *Packet {
|
||||
extra := map[string]interface{}{
|
||||
"runtime.Version": runtime.Version(),
|
||||
"runtime.NumCPU": runtime.NumCPU(),
|
||||
"runtime.GOMAXPROCS": runtime.GOMAXPROCS(0), // 0 just returns the current value
|
||||
"runtime.NumGoroutine": runtime.NumGoroutine(),
|
||||
}
|
||||
return &Packet{
|
||||
Message: message,
|
||||
Interfaces: interfaces,
|
||||
Extra: extra,
|
||||
}
|
||||
}
|
||||
|
||||
// Init initializes required fields in a packet. It is typically called by
|
||||
// Client.Send/Report automatically.
|
||||
func (packet *Packet) Init(project string) error {
|
||||
if packet.Project == "" {
|
||||
packet.Project = project
|
||||
}
|
||||
if packet.EventID == "" {
|
||||
var err error
|
||||
packet.EventID, err = uuid()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if time.Time(packet.Timestamp).IsZero() {
|
||||
packet.Timestamp = Timestamp(time.Now())
|
||||
}
|
||||
if packet.Level == "" {
|
||||
packet.Level = ERROR
|
||||
}
|
||||
if packet.Logger == "" {
|
||||
packet.Logger = "root"
|
||||
}
|
||||
if packet.ServerName == "" {
|
||||
packet.ServerName = hostname
|
||||
}
|
||||
if packet.Platform == "" {
|
||||
packet.Platform = "go"
|
||||
}
|
||||
|
||||
if packet.Culprit == "" {
|
||||
for _, inter := range packet.Interfaces {
|
||||
if c, ok := inter.(Culpriter); ok {
|
||||
packet.Culprit = c.Culprit()
|
||||
if packet.Culprit != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (packet *Packet) AddTags(tags map[string]string) {
|
||||
for k, v := range tags {
|
||||
packet.Tags = append(packet.Tags, Tag{k, v})
|
||||
}
|
||||
}
|
||||
|
||||
func uuid() (string, error) {
|
||||
id := make([]byte, 16)
|
||||
_, err := io.ReadFull(rand.Reader, id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
id[6] &= 0x0F // clear version
|
||||
id[6] |= 0x40 // set version to 4 (random uuid)
|
||||
id[8] &= 0x3F // clear variant
|
||||
id[8] |= 0x80 // set to IETF variant
|
||||
return hex.EncodeToString(id), nil
|
||||
}
|
||||
|
||||
func (packet *Packet) JSON() ([]byte, error) {
|
||||
packetJSON, err := json.Marshal(packet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
interfaces := make(map[string]Interface, len(packet.Interfaces))
|
||||
for _, inter := range packet.Interfaces {
|
||||
if inter != nil {
|
||||
interfaces[inter.Class()] = inter
|
||||
}
|
||||
}
|
||||
|
||||
if len(interfaces) > 0 {
|
||||
interfaceJSON, err := json.Marshal(interfaces)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packetJSON[len(packetJSON)-1] = ','
|
||||
packetJSON = append(packetJSON, interfaceJSON[1:]...)
|
||||
}
|
||||
|
||||
return packetJSON, nil
|
||||
}
|
||||
|
||||
type context struct {
|
||||
user *User
|
||||
http *Http
|
||||
tags map[string]string
|
||||
}
|
||||
|
||||
func (c *context) setUser(u *User) { c.user = u }
|
||||
func (c *context) setHttp(h *Http) { c.http = h }
|
||||
func (c *context) setTags(t map[string]string) {
|
||||
if c.tags == nil {
|
||||
c.tags = make(map[string]string)
|
||||
}
|
||||
for k, v := range t {
|
||||
c.tags[k] = v
|
||||
}
|
||||
}
|
||||
func (c *context) clear() {
|
||||
c.user = nil
|
||||
c.http = nil
|
||||
c.tags = nil
|
||||
}
|
||||
|
||||
// Return a list of interfaces to be used in appending with the rest
|
||||
func (c *context) interfaces() []Interface {
|
||||
len, i := 0, 0
|
||||
if c.user != nil {
|
||||
len++
|
||||
}
|
||||
if c.http != nil {
|
||||
len++
|
||||
}
|
||||
interfaces := make([]Interface, len)
|
||||
if c.user != nil {
|
||||
interfaces[i] = c.user
|
||||
i++
|
||||
}
|
||||
if c.http != nil {
|
||||
interfaces[i] = c.http
|
||||
i++
|
||||
}
|
||||
return interfaces
|
||||
}
|
||||
|
||||
// The maximum number of packets that will be buffered waiting to be delivered.
|
||||
// Packets will be dropped if the buffer is full. Used by NewClient.
|
||||
var MaxQueueBuffer = 100
|
||||
|
||||
func newTransport() Transport {
|
||||
t := &HTTPTransport{}
|
||||
rootCAs, err := gocertifi.CACerts()
|
||||
if err != nil {
|
||||
log.Println("raven: failed to load root TLS certificates:", err)
|
||||
} else {
|
||||
t.Client = &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
TLSClientConfig: &tls.Config{RootCAs: rootCAs},
|
||||
},
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func newClient(tags map[string]string) *Client {
|
||||
client := &Client{
|
||||
Transport: newTransport(),
|
||||
Tags: tags,
|
||||
context: &context{},
|
||||
queue: make(chan *outgoingPacket, MaxQueueBuffer),
|
||||
}
|
||||
client.SetDSN(os.Getenv("SENTRY_DSN"))
|
||||
return client
|
||||
}
|
||||
|
||||
// New constructs a new Sentry client instance
|
||||
func New(dsn string) (*Client, error) {
|
||||
client := newClient(nil)
|
||||
return client, client.SetDSN(dsn)
|
||||
}
|
||||
|
||||
// NewWithTags constructs a new Sentry client instance with default tags.
|
||||
func NewWithTags(dsn string, tags map[string]string) (*Client, error) {
|
||||
client := newClient(tags)
|
||||
return client, client.SetDSN(dsn)
|
||||
}
|
||||
|
||||
// NewClient constructs a Sentry client and spawns a background goroutine to
|
||||
// handle packets sent by Client.Report.
|
||||
//
|
||||
// Deprecated: use New and NewWithTags instead
|
||||
func NewClient(dsn string, tags map[string]string) (*Client, error) {
|
||||
client := newClient(tags)
|
||||
return client, client.SetDSN(dsn)
|
||||
}
|
||||
|
||||
// Client encapsulates a connection to a Sentry server. It must be initialized
|
||||
// by calling NewClient. Modification of fields concurrently with Send or after
|
||||
// calling Report for the first time is not thread-safe.
|
||||
type Client struct {
|
||||
Tags map[string]string
|
||||
|
||||
Transport Transport
|
||||
|
||||
// DropHandler is called when a packet is dropped because the buffer is full.
|
||||
DropHandler func(*Packet)
|
||||
|
||||
// Context that will get appending to all packets
|
||||
context *context
|
||||
|
||||
mu sync.RWMutex
|
||||
url string
|
||||
projectID string
|
||||
authHeader string
|
||||
release string
|
||||
environment string
|
||||
|
||||
// default logger name (leave empty for 'root')
|
||||
defaultLoggerName string
|
||||
|
||||
includePaths []string
|
||||
ignoreErrorsRegexp *regexp.Regexp
|
||||
queue chan *outgoingPacket
|
||||
|
||||
// A WaitGroup to keep track of all currently in-progress captures
|
||||
// This is intended to be used with Client.Wait() to assure that
|
||||
// all messages have been transported before exiting the process.
|
||||
wg sync.WaitGroup
|
||||
|
||||
// A Once to track only starting up the background worker once
|
||||
start sync.Once
|
||||
}
|
||||
|
||||
// Initialize a default *Client instance
|
||||
var DefaultClient = newClient(nil)
|
||||
|
||||
func (c *Client) SetIgnoreErrors(errs []string) error {
|
||||
joinedRegexp := strings.Join(errs, "|")
|
||||
r, err := regexp.Compile(joinedRegexp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to compile regexp %q for %q: %v", joinedRegexp, errs, err)
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
c.ignoreErrorsRegexp = r
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) shouldExcludeErr(errStr string) bool {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
return c.ignoreErrorsRegexp != nil && c.ignoreErrorsRegexp.MatchString(errStr)
|
||||
}
|
||||
|
||||
func SetIgnoreErrors(errs ...string) error {
|
||||
return DefaultClient.SetIgnoreErrors(errs)
|
||||
}
|
||||
|
||||
// SetDSN updates a client with a new DSN. It safe to call after and
|
||||
// concurrently with calls to Report and Send.
|
||||
func (client *Client) SetDSN(dsn string) error {
|
||||
if dsn == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
|
||||
uri, err := url.Parse(dsn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if uri.User == nil {
|
||||
return ErrMissingUser
|
||||
}
|
||||
publicKey := uri.User.Username()
|
||||
secretKey, ok := uri.User.Password()
|
||||
if !ok {
|
||||
return ErrMissingPrivateKey
|
||||
}
|
||||
uri.User = nil
|
||||
|
||||
if idx := strings.LastIndex(uri.Path, "/"); idx != -1 {
|
||||
client.projectID = uri.Path[idx+1:]
|
||||
uri.Path = uri.Path[:idx+1] + "api/" + client.projectID + "/store/"
|
||||
}
|
||||
if client.projectID == "" {
|
||||
return ErrMissingProjectID
|
||||
}
|
||||
|
||||
client.url = uri.String()
|
||||
|
||||
client.authHeader = fmt.Sprintf("Sentry sentry_version=4, sentry_key=%s, sentry_secret=%s", publicKey, secretKey)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sets the DSN for the default *Client instance
|
||||
func SetDSN(dsn string) error { return DefaultClient.SetDSN(dsn) }
|
||||
|
||||
// SetRelease sets the "release" tag.
|
||||
func (client *Client) SetRelease(release string) {
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
client.release = release
|
||||
}
|
||||
|
||||
// SetEnvironment sets the "environment" tag.
|
||||
func (client *Client) SetEnvironment(environment string) {
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
client.environment = environment
|
||||
}
|
||||
|
||||
// SetDefaultLoggerName sets the default logger name.
|
||||
func (client *Client) SetDefaultLoggerName(name string) {
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
client.defaultLoggerName = name
|
||||
}
|
||||
|
||||
// SetRelease sets the "release" tag on the default *Client
|
||||
func SetRelease(release string) { DefaultClient.SetRelease(release) }
|
||||
|
||||
// SetEnvironment sets the "environment" tag on the default *Client
|
||||
func SetEnvironment(environment string) { DefaultClient.SetEnvironment(environment) }
|
||||
|
||||
// SetDefaultLoggerName sets the "defaultLoggerName" on the default *Client
|
||||
func SetDefaultLoggerName(name string) {
|
||||
DefaultClient.SetDefaultLoggerName(name)
|
||||
}
|
||||
|
||||
func (client *Client) worker() {
|
||||
for outgoingPacket := range client.queue {
|
||||
|
||||
client.mu.RLock()
|
||||
url, authHeader := client.url, client.authHeader
|
||||
client.mu.RUnlock()
|
||||
|
||||
outgoingPacket.ch <- client.Transport.Send(url, authHeader, outgoingPacket.packet)
|
||||
client.wg.Done()
|
||||
}
|
||||
}
|
||||
|
||||
// Capture asynchronously delivers a packet to the Sentry server. It is a no-op
|
||||
// when client is nil. A channel is provided if it is important to check for a
|
||||
// send's success.
|
||||
func (client *Client) Capture(packet *Packet, captureTags map[string]string) (eventID string, ch chan error) {
|
||||
ch = make(chan error, 1)
|
||||
|
||||
if client == nil {
|
||||
// return a chan that always returns nil when the caller receives from it
|
||||
close(ch)
|
||||
return
|
||||
}
|
||||
|
||||
if client.shouldExcludeErr(packet.Message) {
|
||||
return
|
||||
}
|
||||
|
||||
// Keep track of all running Captures so that we can wait for them all to finish
|
||||
// *Must* call client.wg.Done() on any path that indicates that an event was
|
||||
// finished being acted upon, whether success or failure
|
||||
client.wg.Add(1)
|
||||
|
||||
// Merge capture tags and client tags
|
||||
packet.AddTags(captureTags)
|
||||
packet.AddTags(client.Tags)
|
||||
|
||||
// Initialize any required packet fields
|
||||
client.mu.RLock()
|
||||
packet.AddTags(client.context.tags)
|
||||
projectID := client.projectID
|
||||
release := client.release
|
||||
environment := client.environment
|
||||
defaultLoggerName := client.defaultLoggerName
|
||||
client.mu.RUnlock()
|
||||
|
||||
// set the global logger name on the packet if we must
|
||||
if packet.Logger == "" && defaultLoggerName != "" {
|
||||
packet.Logger = defaultLoggerName
|
||||
}
|
||||
|
||||
err := packet.Init(projectID)
|
||||
if err != nil {
|
||||
ch <- err
|
||||
client.wg.Done()
|
||||
return
|
||||
}
|
||||
|
||||
packet.Release = release
|
||||
packet.Environment = environment
|
||||
|
||||
outgoingPacket := &outgoingPacket{packet, ch}
|
||||
|
||||
// Lazily start background worker until we
|
||||
// do our first write into the queue.
|
||||
client.start.Do(func() {
|
||||
go client.worker()
|
||||
})
|
||||
|
||||
select {
|
||||
case client.queue <- outgoingPacket:
|
||||
default:
|
||||
// Send would block, drop the packet
|
||||
if client.DropHandler != nil {
|
||||
client.DropHandler(packet)
|
||||
}
|
||||
ch <- ErrPacketDropped
|
||||
client.wg.Done()
|
||||
}
|
||||
|
||||
return packet.EventID, ch
|
||||
}
|
||||
|
||||
// Capture asynchronously delivers a packet to the Sentry server with the default *Client.
|
||||
// It is a no-op when client is nil. A channel is provided if it is important to check for a
|
||||
// send's success.
|
||||
func Capture(packet *Packet, captureTags map[string]string) (eventID string, ch chan error) {
|
||||
return DefaultClient.Capture(packet, captureTags)
|
||||
}
|
||||
|
||||
// CaptureMessage formats and delivers a string message to the Sentry server.
|
||||
func (client *Client) CaptureMessage(message string, tags map[string]string, interfaces ...Interface) string {
|
||||
if client == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if client.shouldExcludeErr(message) {
|
||||
return ""
|
||||
}
|
||||
|
||||
packet := NewPacket(message, append(append(interfaces, client.context.interfaces()...), &Message{message, nil})...)
|
||||
eventID, _ := client.Capture(packet, tags)
|
||||
|
||||
return eventID
|
||||
}
|
||||
|
||||
// CaptureMessage formats and delivers a string message to the Sentry server with the default *Client
|
||||
func CaptureMessage(message string, tags map[string]string, interfaces ...Interface) string {
|
||||
return DefaultClient.CaptureMessage(message, tags, interfaces...)
|
||||
}
|
||||
|
||||
// CaptureMessageAndWait is identical to CaptureMessage except it blocks and waits for the message to be sent.
|
||||
func (client *Client) CaptureMessageAndWait(message string, tags map[string]string, interfaces ...Interface) string {
|
||||
if client == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if client.shouldExcludeErr(message) {
|
||||
return ""
|
||||
}
|
||||
|
||||
packet := NewPacket(message, append(append(interfaces, client.context.interfaces()...), &Message{message, nil})...)
|
||||
eventID, ch := client.Capture(packet, tags)
|
||||
<-ch
|
||||
|
||||
return eventID
|
||||
}
|
||||
|
||||
// CaptureMessageAndWait is identical to CaptureMessage except it blocks and waits for the message to be sent.
|
||||
func CaptureMessageAndWait(message string, tags map[string]string, interfaces ...Interface) string {
|
||||
return DefaultClient.CaptureMessageAndWait(message, tags, interfaces...)
|
||||
}
|
||||
|
||||
// CaptureErrors formats and delivers an error to the Sentry server.
|
||||
// Adds a stacktrace to the packet, excluding the call to this method.
|
||||
func (client *Client) CaptureError(err error, tags map[string]string, interfaces ...Interface) string {
|
||||
if client == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if client.shouldExcludeErr(err.Error()) {
|
||||
return ""
|
||||
}
|
||||
|
||||
packet := NewPacket(err.Error(), append(append(interfaces, client.context.interfaces()...), NewException(err, NewStacktrace(1, 3, client.includePaths)))...)
|
||||
eventID, _ := client.Capture(packet, tags)
|
||||
|
||||
return eventID
|
||||
}
|
||||
|
||||
// CaptureErrors formats and delivers an error to the Sentry server using the default *Client.
|
||||
// Adds a stacktrace to the packet, excluding the call to this method.
|
||||
func CaptureError(err error, tags map[string]string, interfaces ...Interface) string {
|
||||
return DefaultClient.CaptureError(err, tags, interfaces...)
|
||||
}
|
||||
|
||||
// CaptureErrorAndWait is identical to CaptureError, except it blocks and assures that the event was sent
|
||||
func (client *Client) CaptureErrorAndWait(err error, tags map[string]string, interfaces ...Interface) string {
|
||||
if client == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if client.shouldExcludeErr(err.Error()) {
|
||||
return ""
|
||||
}
|
||||
|
||||
packet := NewPacket(err.Error(), append(append(interfaces, client.context.interfaces()...), NewException(err, NewStacktrace(1, 3, client.includePaths)))...)
|
||||
eventID, ch := client.Capture(packet, tags)
|
||||
<-ch
|
||||
|
||||
return eventID
|
||||
}
|
||||
|
||||
// CaptureErrorAndWait is identical to CaptureError, except it blocks and assures that the event was sent
|
||||
func CaptureErrorAndWait(err error, tags map[string]string, interfaces ...Interface) string {
|
||||
return DefaultClient.CaptureErrorAndWait(err, tags, interfaces...)
|
||||
}
|
||||
|
||||
// CapturePanic calls f and then recovers and reports a panic to the Sentry server if it occurs.
|
||||
// If an error is captured, both the error and the reported Sentry error ID are returned.
|
||||
func (client *Client) CapturePanic(f func(), tags map[string]string, interfaces ...Interface) (err interface{}, errorID string) {
|
||||
// Note: This doesn't need to check for client, because we still want to go through the defer/recover path
|
||||
// Down the line, Capture will be noop'd, so while this does a _tiny_ bit of overhead constructing the
|
||||
// *Packet just to be thrown away, this should not be the normal case. Could be refactored to
|
||||
// be completely noop though if we cared.
|
||||
defer func() {
|
||||
var packet *Packet
|
||||
err = recover()
|
||||
switch rval := err.(type) {
|
||||
case nil:
|
||||
return
|
||||
case error:
|
||||
if client.shouldExcludeErr(rval.Error()) {
|
||||
return
|
||||
}
|
||||
packet = NewPacket(rval.Error(), append(append(interfaces, client.context.interfaces()...), NewException(rval, NewStacktrace(2, 3, client.includePaths)))...)
|
||||
default:
|
||||
rvalStr := fmt.Sprint(rval)
|
||||
if client.shouldExcludeErr(rvalStr) {
|
||||
return
|
||||
}
|
||||
packet = NewPacket(rvalStr, append(append(interfaces, client.context.interfaces()...), NewException(errors.New(rvalStr), NewStacktrace(2, 3, client.includePaths)))...)
|
||||
}
|
||||
|
||||
errorID, _ = client.Capture(packet, tags)
|
||||
}()
|
||||
|
||||
f()
|
||||
return
|
||||
}
|
||||
|
||||
// CapturePanic calls f and then recovers and reports a panic to the Sentry server if it occurs.
|
||||
// If an error is captured, both the error and the reported Sentry error ID are returned.
|
||||
func CapturePanic(f func(), tags map[string]string, interfaces ...Interface) (interface{}, string) {
|
||||
return DefaultClient.CapturePanic(f, tags, interfaces...)
|
||||
}
|
||||
|
||||
// CapturePanicAndWait is identical to CaptureError, except it blocks and assures that the event was sent
|
||||
func (client *Client) CapturePanicAndWait(f func(), tags map[string]string, interfaces ...Interface) (err interface{}, errorID string) {
|
||||
// Note: This doesn't need to check for client, because we still want to go through the defer/recover path
|
||||
// Down the line, Capture will be noop'd, so while this does a _tiny_ bit of overhead constructing the
|
||||
// *Packet just to be thrown away, this should not be the normal case. Could be refactored to
|
||||
// be completely noop though if we cared.
|
||||
defer func() {
|
||||
var packet *Packet
|
||||
err = recover()
|
||||
switch rval := err.(type) {
|
||||
case nil:
|
||||
return
|
||||
case error:
|
||||
if client.shouldExcludeErr(rval.Error()) {
|
||||
return
|
||||
}
|
||||
packet = NewPacket(rval.Error(), append(append(interfaces, client.context.interfaces()...), NewException(rval, NewStacktrace(2, 3, client.includePaths)))...)
|
||||
default:
|
||||
rvalStr := fmt.Sprint(rval)
|
||||
if client.shouldExcludeErr(rvalStr) {
|
||||
return
|
||||
}
|
||||
packet = NewPacket(rvalStr, append(append(interfaces, client.context.interfaces()...), NewException(errors.New(rvalStr), NewStacktrace(2, 3, client.includePaths)))...)
|
||||
}
|
||||
|
||||
var ch chan error
|
||||
errorID, ch = client.Capture(packet, tags)
|
||||
<-ch
|
||||
}()
|
||||
|
||||
f()
|
||||
return
|
||||
}
|
||||
|
||||
// CapturePanicAndWait is identical to CaptureError, except it blocks and assures that the event was sent
|
||||
func CapturePanicAndWait(f func(), tags map[string]string, interfaces ...Interface) (interface{}, string) {
|
||||
return DefaultClient.CapturePanicAndWait(f, tags, interfaces...)
|
||||
}
|
||||
|
||||
func (client *Client) Close() {
|
||||
close(client.queue)
|
||||
}
|
||||
|
||||
func Close() { DefaultClient.Close() }
|
||||
|
||||
// Wait blocks and waits for all events to finish being sent to Sentry server
|
||||
func (client *Client) Wait() {
|
||||
client.wg.Wait()
|
||||
}
|
||||
|
||||
// Wait blocks and waits for all events to finish being sent to Sentry server
|
||||
func Wait() { DefaultClient.Wait() }
|
||||
|
||||
func (client *Client) URL() string {
|
||||
client.mu.RLock()
|
||||
defer client.mu.RUnlock()
|
||||
|
||||
return client.url
|
||||
}
|
||||
|
||||
func URL() string { return DefaultClient.URL() }
|
||||
|
||||
func (client *Client) ProjectID() string {
|
||||
client.mu.RLock()
|
||||
defer client.mu.RUnlock()
|
||||
|
||||
return client.projectID
|
||||
}
|
||||
|
||||
func ProjectID() string { return DefaultClient.ProjectID() }
|
||||
|
||||
func (client *Client) Release() string {
|
||||
client.mu.RLock()
|
||||
defer client.mu.RUnlock()
|
||||
|
||||
return client.release
|
||||
}
|
||||
|
||||
func Release() string { return DefaultClient.Release() }
|
||||
|
||||
func IncludePaths() []string { return DefaultClient.IncludePaths() }
|
||||
|
||||
func (client *Client) IncludePaths() []string {
|
||||
client.mu.RLock()
|
||||
defer client.mu.RUnlock()
|
||||
|
||||
return client.includePaths
|
||||
}
|
||||
|
||||
func SetIncludePaths(p []string) { DefaultClient.SetIncludePaths(p) }
|
||||
|
||||
func (client *Client) SetIncludePaths(p []string) {
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
|
||||
client.includePaths = p
|
||||
}
|
||||
|
||||
func (c *Client) SetUserContext(u *User) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.context.setUser(u)
|
||||
}
|
||||
|
||||
func (c *Client) SetHttpContext(h *Http) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.context.setHttp(h)
|
||||
}
|
||||
|
||||
func (c *Client) SetTagsContext(t map[string]string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.context.setTags(t)
|
||||
}
|
||||
|
||||
func (c *Client) ClearContext() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.context.clear()
|
||||
}
|
||||
|
||||
func SetUserContext(u *User) { DefaultClient.SetUserContext(u) }
|
||||
func SetHttpContext(h *Http) { DefaultClient.SetHttpContext(h) }
|
||||
func SetTagsContext(t map[string]string) { DefaultClient.SetTagsContext(t) }
|
||||
func ClearContext() { DefaultClient.ClearContext() }
|
||||
|
||||
// HTTPTransport is the default transport, delivering packets to Sentry via the
|
||||
// HTTP API.
|
||||
type HTTPTransport struct {
|
||||
*http.Client
|
||||
}
|
||||
|
||||
func (t *HTTPTransport) Send(url, authHeader string, packet *Packet) error {
|
||||
if url == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
body, contentType, err := serializedPacket(packet)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error serializing packet: %v", err)
|
||||
}
|
||||
req, err := http.NewRequest("POST", url, body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't create new request: %v", err)
|
||||
}
|
||||
req.Header.Set("X-Sentry-Auth", authHeader)
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
res, err := t.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
io.Copy(ioutil.Discard, res.Body)
|
||||
res.Body.Close()
|
||||
if res.StatusCode != 200 {
|
||||
return fmt.Errorf("raven: got http status %d", res.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func serializedPacket(packet *Packet) (io.Reader, string, error) {
|
||||
packetJSON, err := packet.JSON()
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("error marshaling packet %+v to JSON: %v", packet, err)
|
||||
}
|
||||
|
||||
// Only deflate/base64 the packet if it is bigger than 1KB, as there is
|
||||
// overhead.
|
||||
if len(packetJSON) > 1000 {
|
||||
buf := &bytes.Buffer{}
|
||||
b64 := base64.NewEncoder(base64.StdEncoding, buf)
|
||||
deflate, _ := zlib.NewWriterLevel(b64, zlib.BestCompression)
|
||||
deflate.Write(packetJSON)
|
||||
deflate.Close()
|
||||
b64.Close()
|
||||
return buf, "application/octet-stream", nil
|
||||
}
|
||||
return bytes.NewReader(packetJSON), "application/json", nil
|
||||
}
|
||||
|
||||
var hostname string
|
||||
|
||||
func init() {
|
||||
hostname, _ = os.Hostname()
|
||||
}
|
||||
-228
@@ -1,228 +0,0 @@
|
||||
package raven
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type testInterface struct{}
|
||||
|
||||
func (t *testInterface) Class() string { return "sentry.interfaces.Test" }
|
||||
func (t *testInterface) Culprit() string { return "codez" }
|
||||
|
||||
func TestShouldExcludeErr(t *testing.T) {
|
||||
regexpStrs := []string{"ERR_TIMEOUT", "should.exclude", "(?i)^big$"}
|
||||
|
||||
client := &Client{
|
||||
Transport: newTransport(),
|
||||
Tags: nil,
|
||||
context: &context{},
|
||||
queue: make(chan *outgoingPacket, MaxQueueBuffer),
|
||||
}
|
||||
|
||||
if err := client.SetIgnoreErrors(regexpStrs); err != nil {
|
||||
t.Fatalf("invalid regexps %v: %v", regexpStrs, err)
|
||||
}
|
||||
|
||||
testCases := []string{
|
||||
"there was a ERR_TIMEOUT in handlers.go",
|
||||
"do not log should.exclude at all",
|
||||
"BIG",
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
if !client.shouldExcludeErr(tc) {
|
||||
t.Fatalf("failed to exclude err %q with regexps %v", tc, regexpStrs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketJSON(t *testing.T) {
|
||||
packet := &Packet{
|
||||
Project: "1",
|
||||
EventID: "2",
|
||||
Platform: "linux",
|
||||
Culprit: "caused_by",
|
||||
ServerName: "host1",
|
||||
Release: "721e41770371db95eee98ca2707686226b993eda",
|
||||
Environment: "production",
|
||||
Message: "test",
|
||||
Timestamp: Timestamp(time.Date(2000, 01, 01, 0, 0, 0, 0, time.UTC)),
|
||||
Level: ERROR,
|
||||
Logger: "com.getsentry.raven-go.logger-test-packet-json",
|
||||
Tags: []Tag{Tag{"foo", "bar"}},
|
||||
Modules: map[string]string{"foo": "bar"},
|
||||
Fingerprint: []string{"{{ default }}", "a-custom-fingerprint"},
|
||||
Interfaces: []Interface{&Message{Message: "foo"}},
|
||||
}
|
||||
|
||||
packet.AddTags(map[string]string{"foo": "foo"})
|
||||
packet.AddTags(map[string]string{"baz": "buzz"})
|
||||
|
||||
expected := `{"message":"test","event_id":"2","project":"1","timestamp":"2000-01-01T00:00:00.00","level":"error","logger":"com.getsentry.raven-go.logger-test-packet-json","platform":"linux","culprit":"caused_by","server_name":"host1","release":"721e41770371db95eee98ca2707686226b993eda","environment":"production","tags":[["foo","bar"],["foo","foo"],["baz","buzz"]],"modules":{"foo":"bar"},"fingerprint":["{{ default }}","a-custom-fingerprint"],"logentry":{"message":"foo"}}`
|
||||
j, err := packet.JSON()
|
||||
if err != nil {
|
||||
t.Fatalf("JSON marshalling should not fail: %v", err)
|
||||
}
|
||||
actual := string(j)
|
||||
|
||||
if actual != expected {
|
||||
t.Errorf("incorrect json; got %s, want %s", actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketJSONNilInterface(t *testing.T) {
|
||||
packet := &Packet{
|
||||
Project: "1",
|
||||
EventID: "2",
|
||||
Platform: "linux",
|
||||
Culprit: "caused_by",
|
||||
ServerName: "host1",
|
||||
Release: "721e41770371db95eee98ca2707686226b993eda",
|
||||
Environment: "production",
|
||||
Message: "test",
|
||||
Timestamp: Timestamp(time.Date(2000, 01, 01, 0, 0, 0, 0, time.UTC)),
|
||||
Level: ERROR,
|
||||
Logger: "com.getsentry.raven-go.logger-test-packet-json",
|
||||
Tags: []Tag{Tag{"foo", "bar"}},
|
||||
Modules: map[string]string{"foo": "bar"},
|
||||
Fingerprint: []string{"{{ default }}", "a-custom-fingerprint"},
|
||||
Interfaces: []Interface{&Message{Message: "foo"}, nil},
|
||||
}
|
||||
|
||||
expected := `{"message":"test","event_id":"2","project":"1","timestamp":"2000-01-01T00:00:00.00","level":"error","logger":"com.getsentry.raven-go.logger-test-packet-json","platform":"linux","culprit":"caused_by","server_name":"host1","release":"721e41770371db95eee98ca2707686226b993eda","environment":"production","tags":[["foo","bar"]],"modules":{"foo":"bar"},"fingerprint":["{{ default }}","a-custom-fingerprint"],"logentry":{"message":"foo"}}`
|
||||
j, err := packet.JSON()
|
||||
if err != nil {
|
||||
t.Fatalf("JSON marshalling should not fail: %v", err)
|
||||
}
|
||||
actual := string(j)
|
||||
|
||||
if actual != expected {
|
||||
t.Errorf("incorrect json; got %s, want %s", actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketInit(t *testing.T) {
|
||||
packet := &Packet{Message: "a", Interfaces: []Interface{&testInterface{}}}
|
||||
packet.Init("foo")
|
||||
|
||||
if packet.Project != "foo" {
|
||||
t.Error("incorrect Project:", packet.Project)
|
||||
}
|
||||
if packet.Culprit != "codez" {
|
||||
t.Error("incorrect Culprit:", packet.Culprit)
|
||||
}
|
||||
if packet.ServerName == "" {
|
||||
t.Errorf("ServerName should not be empty")
|
||||
}
|
||||
if packet.Level != ERROR {
|
||||
t.Errorf("incorrect Level: got %d, want %d", packet.Level, ERROR)
|
||||
}
|
||||
if packet.Logger != "root" {
|
||||
t.Errorf("incorrect Logger: got %s, want %s", packet.Logger, "root")
|
||||
}
|
||||
if time.Time(packet.Timestamp).IsZero() {
|
||||
t.Error("Timestamp is zero")
|
||||
}
|
||||
if len(packet.EventID) != 32 {
|
||||
t.Error("incorrect EventID:", packet.EventID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetDSN(t *testing.T) {
|
||||
client := &Client{}
|
||||
client.SetDSN("https://u:p@example.com/sentry/1")
|
||||
|
||||
if client.url != "https://example.com/sentry/api/1/store/" {
|
||||
t.Error("incorrect url:", client.url)
|
||||
}
|
||||
if client.projectID != "1" {
|
||||
t.Error("incorrect projectID:", client.projectID)
|
||||
}
|
||||
if client.authHeader != "Sentry sentry_version=4, sentry_key=u, sentry_secret=p" {
|
||||
t.Error("incorrect authHeader:", client.authHeader)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalTag(t *testing.T) {
|
||||
actual := new(Tag)
|
||||
if err := json.Unmarshal([]byte(`["foo","bar"]`), actual); err != nil {
|
||||
t.Fatal("unable to decode JSON:", err)
|
||||
}
|
||||
|
||||
expected := &Tag{Key: "foo", Value: "bar"}
|
||||
if !reflect.DeepEqual(actual, expected) {
|
||||
t.Errorf("incorrect Tag: wanted '%+v' and got '%+v'", expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalTags(t *testing.T) {
|
||||
tests := []struct {
|
||||
Input string
|
||||
Expected Tags
|
||||
}{
|
||||
{
|
||||
`{"foo":"bar"}`,
|
||||
Tags{Tag{Key: "foo", Value: "bar"}},
|
||||
},
|
||||
{
|
||||
`[["foo","bar"],["bar","baz"]]`,
|
||||
Tags{Tag{Key: "foo", Value: "bar"}, Tag{Key: "bar", Value: "baz"}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
var actual Tags
|
||||
if err := json.Unmarshal([]byte(test.Input), &actual); err != nil {
|
||||
t.Fatal("unable to decode JSON:", err)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(actual, test.Expected) {
|
||||
t.Errorf("incorrect Tags: wanted '%+v' and got '%+v'", test.Expected, actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarshalTimestamp(t *testing.T) {
|
||||
timestamp := Timestamp(time.Date(2000, 01, 02, 03, 04, 05, 0, time.UTC))
|
||||
expected := `"2000-01-02T03:04:05.00"`
|
||||
|
||||
actual, err := json.Marshal(timestamp)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if string(actual) != expected {
|
||||
t.Errorf("incorrect string; got %s, want %s", actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalTimestamp(t *testing.T) {
|
||||
timestamp := `"2000-01-02T03:04:05.00"`
|
||||
expected := Timestamp(time.Date(2000, 01, 02, 03, 04, 05, 0, time.UTC))
|
||||
|
||||
var actual Timestamp
|
||||
err := json.Unmarshal([]byte(timestamp), &actual)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if actual != expected {
|
||||
t.Errorf("incorrect string; got %s, want %s", actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilClient(t *testing.T) {
|
||||
var client *Client = nil
|
||||
eventID, ch := client.Capture(nil, nil)
|
||||
if eventID != "" {
|
||||
t.Error("expected empty eventID:", eventID)
|
||||
}
|
||||
// wait on ch: no send should succeed immediately
|
||||
err := <-ch
|
||||
if err != nil {
|
||||
t.Error("expected nil err:", err)
|
||||
}
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
package raven
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func Example() {
|
||||
// ... i.e. raisedErr is incoming error
|
||||
var raisedErr error
|
||||
// sentry DSN generated by Sentry server
|
||||
var sentryDSN string
|
||||
// r is a request performed when error occured
|
||||
var r *http.Request
|
||||
client, err := New(sentryDSN)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
trace := NewStacktrace(0, 2, nil)
|
||||
packet := NewPacket(raisedErr.Error(), NewException(raisedErr, trace), NewHttp(r))
|
||||
eventID, ch := client.Capture(packet, nil)
|
||||
if err = <-ch; err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
message := fmt.Sprintf("Captured error with id %s: %q", eventID, raisedErr)
|
||||
log.Println(message)
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
package raven
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
var errorMsgPattern = regexp.MustCompile(`\A(\w+): (.+)\z`)
|
||||
|
||||
func NewException(err error, stacktrace *Stacktrace) *Exception {
|
||||
msg := err.Error()
|
||||
ex := &Exception{
|
||||
Stacktrace: stacktrace,
|
||||
Value: msg,
|
||||
Type: reflect.TypeOf(err).String(),
|
||||
}
|
||||
if m := errorMsgPattern.FindStringSubmatch(msg); m != nil {
|
||||
ex.Module, ex.Value = m[1], m[2]
|
||||
}
|
||||
return ex
|
||||
}
|
||||
|
||||
// https://docs.getsentry.com/hosted/clientdev/interfaces/#failure-interfaces
|
||||
type Exception struct {
|
||||
// Required
|
||||
Value string `json:"value"`
|
||||
|
||||
// Optional
|
||||
Type string `json:"type,omitempty"`
|
||||
Module string `json:"module,omitempty"`
|
||||
Stacktrace *Stacktrace `json:"stacktrace,omitempty"`
|
||||
}
|
||||
|
||||
func (e *Exception) Class() string { return "exception" }
|
||||
|
||||
func (e *Exception) Culprit() string {
|
||||
if e.Stacktrace == nil {
|
||||
return ""
|
||||
}
|
||||
return e.Stacktrace.Culprit()
|
||||
}
|
||||
|
||||
// Exceptions allows for chained errors
|
||||
// https://docs.sentry.io/clientdev/interfaces/exception/
|
||||
type Exceptions struct {
|
||||
// Required
|
||||
Values []*Exception `json:"values"`
|
||||
}
|
||||
|
||||
func (es Exceptions) Class() string { return "exception" }
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package raven
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var newExceptionTests = []struct {
|
||||
err error
|
||||
Exception
|
||||
}{
|
||||
{errors.New("foobar"), Exception{Value: "foobar", Type: "*errors.errorString"}},
|
||||
{errors.New("bar: foobar"), Exception{Value: "foobar", Type: "*errors.errorString", Module: "bar"}},
|
||||
}
|
||||
|
||||
func TestNewException(t *testing.T) {
|
||||
for _, test := range newExceptionTests {
|
||||
actual := NewException(test.err, nil)
|
||||
if actual.Value != test.Value {
|
||||
t.Errorf("incorrect Value: got %s, want %s", actual.Value, test.Value)
|
||||
}
|
||||
if actual.Type != test.Type {
|
||||
t.Errorf("incorrect Type: got %s, want %s", actual.Type, test.Type)
|
||||
}
|
||||
if actual.Module != test.Module {
|
||||
t.Errorf("incorrect Module: got %s, want %s", actual.Module, test.Module)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewException_JSON(t *testing.T) {
|
||||
expected := `{"value":"foobar","type":"*errors.errorString"}`
|
||||
e := NewException(errors.New("foobar"), nil)
|
||||
b, _ := json.Marshal(e)
|
||||
if string(b) != expected {
|
||||
t.Errorf("incorrect JSON: got %s, want %s", string(b), expected)
|
||||
}
|
||||
}
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
package raven
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func NewHttp(req *http.Request) *Http {
|
||||
proto := "http"
|
||||
if req.TLS != nil || req.Header.Get("X-Forwarded-Proto") == "https" {
|
||||
proto = "https"
|
||||
}
|
||||
h := &Http{
|
||||
Method: req.Method,
|
||||
Cookies: req.Header.Get("Cookie"),
|
||||
Query: sanitizeQuery(req.URL.Query()).Encode(),
|
||||
URL: proto + "://" + req.Host + req.URL.Path,
|
||||
Headers: make(map[string]string, len(req.Header)),
|
||||
}
|
||||
if addr, port, err := net.SplitHostPort(req.RemoteAddr); err == nil {
|
||||
h.Env = map[string]string{"REMOTE_ADDR": addr, "REMOTE_PORT": port}
|
||||
}
|
||||
for k, v := range req.Header {
|
||||
h.Headers[k] = strings.Join(v, ",")
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
var querySecretFields = []string{"password", "passphrase", "passwd", "secret"}
|
||||
|
||||
func sanitizeQuery(query url.Values) url.Values {
|
||||
for _, keyword := range querySecretFields {
|
||||
for field := range query {
|
||||
if strings.Contains(field, keyword) {
|
||||
query[field] = []string{"********"}
|
||||
}
|
||||
}
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// https://docs.getsentry.com/hosted/clientdev/interfaces/#context-interfaces
|
||||
type Http struct {
|
||||
// Required
|
||||
URL string `json:"url"`
|
||||
Method string `json:"method"`
|
||||
Query string `json:"query_string,omitempty"`
|
||||
|
||||
// Optional
|
||||
Cookies string `json:"cookies,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
Env map[string]string `json:"env,omitempty"`
|
||||
|
||||
// Must be either a string or map[string]string
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func (h *Http) Class() string { return "request" }
|
||||
|
||||
// Recovery handler to wrap the stdlib net/http Mux.
|
||||
// Example:
|
||||
// http.HandleFunc("/", raven.RecoveryHandler(func(w http.ResponseWriter, r *http.Request) {
|
||||
// ...
|
||||
// }))
|
||||
func RecoveryHandler(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rval := recover(); rval != nil {
|
||||
debug.PrintStack()
|
||||
rvalStr := fmt.Sprint(rval)
|
||||
packet := NewPacket(rvalStr, NewException(errors.New(rvalStr), NewStacktrace(2, 3, nil)), NewHttp(r))
|
||||
Capture(packet, nil)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
}()
|
||||
|
||||
handler(w, r)
|
||||
}
|
||||
}
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
package raven
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type testcase struct {
|
||||
request *http.Request
|
||||
*Http
|
||||
}
|
||||
|
||||
func newBaseRequest() *http.Request {
|
||||
u, _ := url.Parse("http://example.com/")
|
||||
header := make(http.Header)
|
||||
header.Add("Foo", "bar")
|
||||
|
||||
req := &http.Request{
|
||||
Method: "GET",
|
||||
URL: u,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: header,
|
||||
Host: u.Host,
|
||||
RemoteAddr: "127.0.0.1:8000",
|
||||
}
|
||||
return req
|
||||
}
|
||||
|
||||
func newBaseHttp() *Http {
|
||||
h := &Http{
|
||||
Method: "GET",
|
||||
Cookies: "",
|
||||
Query: "",
|
||||
URL: "http://example.com/",
|
||||
Headers: map[string]string{"Foo": "bar"},
|
||||
Env: map[string]string{"REMOTE_ADDR": "127.0.0.1", "REMOTE_PORT": "8000"},
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func NewRequest() testcase {
|
||||
return testcase{newBaseRequest(), newBaseHttp()}
|
||||
}
|
||||
|
||||
func NewRequestIPV6() testcase {
|
||||
req := newBaseRequest()
|
||||
req.RemoteAddr = "[:1]:8000"
|
||||
|
||||
h := newBaseHttp()
|
||||
h.Env = map[string]string{"REMOTE_ADDR": ":1", "REMOTE_PORT": "8000"}
|
||||
return testcase{req, h}
|
||||
}
|
||||
|
||||
func NewRequestMultipleHeaders() testcase {
|
||||
req := newBaseRequest()
|
||||
req.Header.Add("Foo", "baz")
|
||||
|
||||
h := newBaseHttp()
|
||||
h.Headers["Foo"] = "bar,baz"
|
||||
return testcase{req, h}
|
||||
}
|
||||
|
||||
func NewSecureRequest() testcase {
|
||||
req := newBaseRequest()
|
||||
req.Header.Add("X-Forwarded-Proto", "https")
|
||||
|
||||
h := newBaseHttp()
|
||||
h.URL = "https://example.com/"
|
||||
h.Headers["X-Forwarded-Proto"] = "https"
|
||||
return testcase{req, h}
|
||||
}
|
||||
|
||||
func NewCookiesRequest() testcase {
|
||||
val := "foo=bar; bar=baz"
|
||||
req := newBaseRequest()
|
||||
req.Header.Add("Cookie", val)
|
||||
|
||||
h := newBaseHttp()
|
||||
h.Cookies = val
|
||||
h.Headers["Cookie"] = val
|
||||
return testcase{req, h}
|
||||
}
|
||||
|
||||
var newHttpTests = []testcase{
|
||||
NewRequest(),
|
||||
NewRequestIPV6(),
|
||||
NewRequestMultipleHeaders(),
|
||||
NewSecureRequest(),
|
||||
NewCookiesRequest(),
|
||||
}
|
||||
|
||||
func TestNewHttp(t *testing.T) {
|
||||
for _, test := range newHttpTests {
|
||||
actual := NewHttp(test.request)
|
||||
if actual.Method != test.Method {
|
||||
t.Errorf("incorrect Method: got %s, want %s", actual.Method, test.Method)
|
||||
}
|
||||
if actual.Cookies != test.Cookies {
|
||||
t.Errorf("incorrect Cookies: got %s, want %s", actual.Cookies, test.Cookies)
|
||||
}
|
||||
if actual.Query != test.Query {
|
||||
t.Errorf("incorrect Query: got %s, want %s", actual.Query, test.Query)
|
||||
}
|
||||
if actual.URL != test.URL {
|
||||
t.Errorf("incorrect URL: got %s, want %s", actual.URL, test.URL)
|
||||
}
|
||||
if !reflect.DeepEqual(actual.Headers, test.Headers) {
|
||||
t.Errorf("incorrect Headers: got %+v, want %+v", actual.Headers, test.Headers)
|
||||
}
|
||||
if !reflect.DeepEqual(actual.Env, test.Env) {
|
||||
t.Errorf("incorrect Env: got %+v, want %+v", actual.Env, test.Env)
|
||||
}
|
||||
if !reflect.DeepEqual(actual.Data, test.Data) {
|
||||
t.Errorf("incorrect Data: got %+v, want %+v", actual.Data, test.Data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var sanitizeQueryTests = []struct {
|
||||
input, output string
|
||||
}{
|
||||
{"foo=bar", "foo=bar"},
|
||||
{"password=foo", "password=********"},
|
||||
{"passphrase=foo", "passphrase=********"},
|
||||
{"passwd=foo", "passwd=********"},
|
||||
{"secret=foo", "secret=********"},
|
||||
{"secretstuff=foo", "secretstuff=********"},
|
||||
{"foo=bar&secret=foo", "foo=bar&secret=********"},
|
||||
{"secret=foo&secret=bar", "secret=********"},
|
||||
}
|
||||
|
||||
func parseQuery(q string) url.Values {
|
||||
r, _ := url.ParseQuery(q)
|
||||
return r
|
||||
}
|
||||
|
||||
func TestSanitizeQuery(t *testing.T) {
|
||||
for _, test := range sanitizeQueryTests {
|
||||
actual := sanitizeQuery(parseQuery(test.input))
|
||||
expected := parseQuery(test.output)
|
||||
if !reflect.DeepEqual(actual, expected) {
|
||||
t.Errorf("incorrect sanitization: got %+v, want %+v", actual, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
package raven
|
||||
|
||||
// https://docs.getsentry.com/hosted/clientdev/interfaces/#message-interface
|
||||
type Message struct {
|
||||
// Required
|
||||
Message string `json:"message"`
|
||||
|
||||
// Optional
|
||||
Params []interface{} `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
func (m *Message) Class() string { return "logentry" }
|
||||
|
||||
// https://docs.getsentry.com/hosted/clientdev/interfaces/#template-interface
|
||||
type Template struct {
|
||||
// Required
|
||||
Filename string `json:"filename"`
|
||||
Lineno int `json:"lineno"`
|
||||
ContextLine string `json:"context_line"`
|
||||
|
||||
// Optional
|
||||
PreContext []string `json:"pre_context,omitempty"`
|
||||
PostContext []string `json:"post_context,omitempty"`
|
||||
AbsolutePath string `json:"abs_path,omitempty"`
|
||||
}
|
||||
|
||||
func (t *Template) Class() string { return "template" }
|
||||
|
||||
// https://docs.getsentry.com/hosted/clientdev/interfaces/#context-interfaces
|
||||
type User struct {
|
||||
// All fields are optional
|
||||
ID string `json:"id,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
IP string `json:"ip_address,omitempty"`
|
||||
}
|
||||
|
||||
func (h *User) Class() string { return "user" }
|
||||
|
||||
// https://docs.getsentry.com/hosted/clientdev/interfaces/#context-interfaces
|
||||
type Query struct {
|
||||
// Required
|
||||
Query string `json:"query"`
|
||||
|
||||
// Optional
|
||||
Engine string `json:"engine,omitempty"`
|
||||
}
|
||||
|
||||
func (q *Query) Class() string { return "query" }
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
#!/bin/bash
|
||||
go test -race ./...
|
||||
go test -cover ./...
|
||||
go test -v ./...
|
||||
-223
@@ -1,223 +0,0 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
// Some code from the runtime/debug package of the Go standard library.
|
||||
|
||||
package raven
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"go/build"
|
||||
"io/ioutil"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// https://docs.getsentry.com/hosted/clientdev/interfaces/#failure-interfaces
|
||||
type Stacktrace struct {
|
||||
// Required
|
||||
Frames []*StacktraceFrame `json:"frames"`
|
||||
}
|
||||
|
||||
func (s *Stacktrace) Class() string { return "stacktrace" }
|
||||
|
||||
func (s *Stacktrace) Culprit() string {
|
||||
for i := len(s.Frames) - 1; i >= 0; i-- {
|
||||
frame := s.Frames[i]
|
||||
if frame.InApp == true && frame.Module != "" && frame.Function != "" {
|
||||
return frame.Module + "." + frame.Function
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type StacktraceFrame struct {
|
||||
// At least one required
|
||||
Filename string `json:"filename,omitempty"`
|
||||
Function string `json:"function,omitempty"`
|
||||
Module string `json:"module,omitempty"`
|
||||
|
||||
// Optional
|
||||
Lineno int `json:"lineno,omitempty"`
|
||||
Colno int `json:"colno,omitempty"`
|
||||
AbsolutePath string `json:"abs_path,omitempty"`
|
||||
ContextLine string `json:"context_line,omitempty"`
|
||||
PreContext []string `json:"pre_context,omitempty"`
|
||||
PostContext []string `json:"post_context,omitempty"`
|
||||
InApp bool `json:"in_app"`
|
||||
}
|
||||
|
||||
// Intialize and populate a new stacktrace, skipping skip frames.
|
||||
//
|
||||
// context is the number of surrounding lines that should be included for context.
|
||||
// Setting context to 3 would try to get seven lines. Setting context to -1 returns
|
||||
// one line with no surrounding context, and 0 returns no context.
|
||||
//
|
||||
// appPackagePrefixes is a list of prefixes used to check whether a package should
|
||||
// be considered "in app".
|
||||
func NewStacktrace(skip int, context int, appPackagePrefixes []string) *Stacktrace {
|
||||
var frames []*StacktraceFrame
|
||||
for i := 1 + skip; ; i++ {
|
||||
pc, file, line, ok := runtime.Caller(i)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
frame := NewStacktraceFrame(pc, file, line, context, appPackagePrefixes)
|
||||
if frame != nil {
|
||||
frames = append(frames, frame)
|
||||
}
|
||||
}
|
||||
// If there are no frames, the entire stacktrace is nil
|
||||
if len(frames) == 0 {
|
||||
return nil
|
||||
}
|
||||
// Optimize the path where there's only 1 frame
|
||||
if len(frames) == 1 {
|
||||
return &Stacktrace{frames}
|
||||
}
|
||||
// Sentry wants the frames with the oldest first, so reverse them
|
||||
for i, j := 0, len(frames)-1; i < j; i, j = i+1, j-1 {
|
||||
frames[i], frames[j] = frames[j], frames[i]
|
||||
}
|
||||
return &Stacktrace{frames}
|
||||
}
|
||||
|
||||
// Build a single frame using data returned from runtime.Caller.
|
||||
//
|
||||
// context is the number of surrounding lines that should be included for context.
|
||||
// Setting context to 3 would try to get seven lines. Setting context to -1 returns
|
||||
// one line with no surrounding context, and 0 returns no context.
|
||||
//
|
||||
// appPackagePrefixes is a list of prefixes used to check whether a package should
|
||||
// be considered "in app".
|
||||
func NewStacktraceFrame(pc uintptr, file string, line, context int, appPackagePrefixes []string) *StacktraceFrame {
|
||||
frame := &StacktraceFrame{AbsolutePath: file, Filename: trimPath(file), Lineno: line, InApp: false}
|
||||
frame.Module, frame.Function = functionName(pc)
|
||||
|
||||
// `runtime.goexit` is effectively a placeholder that comes from
|
||||
// runtime/asm_amd64.s and is meaningless.
|
||||
if frame.Module == "runtime" && frame.Function == "goexit" {
|
||||
return nil
|
||||
}
|
||||
|
||||
if frame.Module == "main" {
|
||||
frame.InApp = true
|
||||
} else {
|
||||
for _, prefix := range appPackagePrefixes {
|
||||
if strings.HasPrefix(frame.Module, prefix) && !strings.Contains(frame.Module, "vendor") && !strings.Contains(frame.Module, "third_party") {
|
||||
frame.InApp = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if context > 0 {
|
||||
contextLines, lineIdx := fileContext(file, line, context)
|
||||
if len(contextLines) > 0 {
|
||||
for i, line := range contextLines {
|
||||
switch {
|
||||
case i < lineIdx:
|
||||
frame.PreContext = append(frame.PreContext, string(line))
|
||||
case i == lineIdx:
|
||||
frame.ContextLine = string(line)
|
||||
default:
|
||||
frame.PostContext = append(frame.PostContext, string(line))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if context == -1 {
|
||||
contextLine, _ := fileContext(file, line, 0)
|
||||
if len(contextLine) > 0 {
|
||||
frame.ContextLine = string(contextLine[0])
|
||||
}
|
||||
}
|
||||
return frame
|
||||
}
|
||||
|
||||
// Retrieve the name of the package and function containing the PC.
|
||||
func functionName(pc uintptr) (pack string, name string) {
|
||||
fn := runtime.FuncForPC(pc)
|
||||
if fn == nil {
|
||||
return
|
||||
}
|
||||
name = fn.Name()
|
||||
// We get this:
|
||||
// runtime/debug.*T·ptrmethod
|
||||
// and want this:
|
||||
// pack = runtime/debug
|
||||
// name = *T.ptrmethod
|
||||
if idx := strings.LastIndex(name, "."); idx != -1 {
|
||||
pack = name[:idx]
|
||||
name = name[idx+1:]
|
||||
}
|
||||
name = strings.Replace(name, "·", ".", -1)
|
||||
return
|
||||
}
|
||||
|
||||
var fileCacheLock sync.Mutex
|
||||
var fileCache = make(map[string][][]byte)
|
||||
|
||||
func fileContext(filename string, line, context int) ([][]byte, int) {
|
||||
fileCacheLock.Lock()
|
||||
defer fileCacheLock.Unlock()
|
||||
lines, ok := fileCache[filename]
|
||||
if !ok {
|
||||
data, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
// cache errors as nil slice: code below handles it correctly
|
||||
// otherwise when missing the source or running as a different user, we try
|
||||
// reading the file on each error which is unnecessary
|
||||
fileCache[filename] = nil
|
||||
return nil, 0
|
||||
}
|
||||
lines = bytes.Split(data, []byte{'\n'})
|
||||
fileCache[filename] = lines
|
||||
}
|
||||
|
||||
if lines == nil {
|
||||
// cached error from ReadFile: return no lines
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
line-- // stack trace lines are 1-indexed
|
||||
start := line - context
|
||||
var idx int
|
||||
if start < 0 {
|
||||
start = 0
|
||||
idx = line
|
||||
} else {
|
||||
idx = context
|
||||
}
|
||||
end := line + context + 1
|
||||
if line >= len(lines) {
|
||||
return nil, 0
|
||||
}
|
||||
if end > len(lines) {
|
||||
end = len(lines)
|
||||
}
|
||||
return lines[start:end], idx
|
||||
}
|
||||
|
||||
var trimPaths []string
|
||||
|
||||
// Try to trim the GOROOT or GOPATH prefix off of a filename
|
||||
func trimPath(filename string) string {
|
||||
for _, prefix := range trimPaths {
|
||||
if trimmed := strings.TrimPrefix(filename, prefix); len(trimmed) < len(filename) {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
return filename
|
||||
}
|
||||
|
||||
func init() {
|
||||
// Collect all source directories, and make sure they
|
||||
// end in a trailing "separator"
|
||||
for _, prefix := range build.Default.SrcDirs() {
|
||||
if prefix[len(prefix)-1] != filepath.Separator {
|
||||
prefix += string(filepath.Separator)
|
||||
}
|
||||
trimPaths = append(trimPaths, prefix)
|
||||
}
|
||||
}
|
||||
-188
@@ -1,188 +0,0 @@
|
||||
package raven
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/build"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type FunctionNameTest struct {
|
||||
skip int
|
||||
pack string
|
||||
name string
|
||||
}
|
||||
|
||||
var (
|
||||
thisFile string
|
||||
thisPackage string
|
||||
functionNameTests []FunctionNameTest
|
||||
)
|
||||
|
||||
func TestFunctionName(t *testing.T) {
|
||||
for _, test := range functionNameTests {
|
||||
pc, _, _, _ := runtime.Caller(test.skip)
|
||||
pack, name := functionName(pc)
|
||||
|
||||
if pack != test.pack {
|
||||
t.Errorf("incorrect package; got %s, want %s", pack, test.pack)
|
||||
}
|
||||
if name != test.name {
|
||||
t.Errorf("incorrect function; got %s, want %s", name, test.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStacktrace(t *testing.T) {
|
||||
st := trace()
|
||||
if st == nil {
|
||||
t.Error("got nil stacktrace")
|
||||
}
|
||||
if len(st.Frames) == 0 {
|
||||
t.Error("got zero frames")
|
||||
}
|
||||
|
||||
f := st.Frames[len(st.Frames)-1]
|
||||
if f.Filename != thisFile {
|
||||
t.Errorf("incorrect Filename; got %s, want %s", f.Filename, thisFile)
|
||||
}
|
||||
if !strings.HasSuffix(f.AbsolutePath, thisFile) {
|
||||
t.Error("incorrect AbsolutePath:", f.AbsolutePath)
|
||||
}
|
||||
if f.Function != "trace" {
|
||||
t.Error("incorrect Function:", f.Function)
|
||||
}
|
||||
if f.Module != thisPackage {
|
||||
t.Error("incorrect Module:", f.Module)
|
||||
}
|
||||
if f.Lineno != 87 {
|
||||
t.Error("incorrect Lineno:", f.Lineno)
|
||||
}
|
||||
if f.ContextLine != "\treturn NewStacktrace(0, 2, []string{thisPackage})" {
|
||||
t.Errorf("incorrect ContextLine: %#v", f.ContextLine)
|
||||
}
|
||||
if len(f.PreContext) != 2 || f.PreContext[0] != "// a" || f.PreContext[1] != "func trace() *Stacktrace {" {
|
||||
t.Errorf("incorrect PreContext %#v", f.PreContext)
|
||||
}
|
||||
if len(f.PostContext) != 2 || f.PostContext[0] != "\t// b" || f.PostContext[1] != "}" {
|
||||
t.Errorf("incorrect PostContext %#v", f.PostContext)
|
||||
}
|
||||
_, filename, _, _ := runtime.Caller(0)
|
||||
runningInVendored := strings.Contains(filename, "vendor")
|
||||
if f.InApp != !runningInVendored {
|
||||
t.Error("expected InApp to be true")
|
||||
}
|
||||
|
||||
if f.InApp && st.Culprit() != fmt.Sprintf("%s.trace", thisPackage) {
|
||||
t.Error("incorrect Culprit:", st.Culprit())
|
||||
}
|
||||
}
|
||||
|
||||
// a
|
||||
func trace() *Stacktrace {
|
||||
return NewStacktrace(0, 2, []string{thisPackage})
|
||||
// b
|
||||
}
|
||||
|
||||
func derivePackage() (file, pack string) {
|
||||
// Get file name by seeking caller's file name.
|
||||
_, callerFile, _, ok := runtime.Caller(1)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Trim file name
|
||||
file = callerFile
|
||||
for _, dir := range build.Default.SrcDirs() {
|
||||
dir := dir + string(filepath.Separator)
|
||||
if trimmed := strings.TrimPrefix(callerFile, dir); len(trimmed) < len(file) {
|
||||
file = trimmed
|
||||
}
|
||||
}
|
||||
|
||||
// Now derive package name
|
||||
dir := filepath.Dir(callerFile)
|
||||
|
||||
dirPkg, err := build.ImportDir(dir, build.AllowBinary)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
pack = dirPkg.ImportPath
|
||||
return
|
||||
}
|
||||
|
||||
func init() {
|
||||
thisFile, thisPackage = derivePackage()
|
||||
functionNameTests = []FunctionNameTest{
|
||||
{0, thisPackage, "TestFunctionName"},
|
||||
{1, "testing", "tRunner"},
|
||||
{2, "runtime", "goexit"},
|
||||
{100, "", ""},
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewStacktrace_outOfBounds verifies that a context exceeding the number
|
||||
// of lines in a file does not cause a panic.
|
||||
func TestNewStacktrace_outOfBounds(t *testing.T) {
|
||||
st := NewStacktrace(0, 1000000, []string{thisPackage})
|
||||
f := st.Frames[len(st.Frames)-1]
|
||||
if f.ContextLine != "\tst := NewStacktrace(0, 1000000, []string{thisPackage})" {
|
||||
t.Errorf("incorrect ContextLine: %#v", f.ContextLine)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewStacktrace_noFrames(t *testing.T) {
|
||||
st := NewStacktrace(999999999, 0, []string{})
|
||||
if st != nil {
|
||||
t.Errorf("expected st.Frames to be nil:", st)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileContext(t *testing.T) {
|
||||
// reset the cache
|
||||
fileCache = make(map[string][][]byte)
|
||||
|
||||
tempdir, err := ioutil.TempDir("", "")
|
||||
if err != nil {
|
||||
t.Fatal("failed to create temporary directory:", err)
|
||||
}
|
||||
defer os.RemoveAll(tempdir)
|
||||
|
||||
okPath := filepath.Join(tempdir, "ok")
|
||||
missingPath := filepath.Join(tempdir, "missing")
|
||||
noPermissionPath := filepath.Join(tempdir, "noperms")
|
||||
|
||||
err = ioutil.WriteFile(okPath, []byte("hello\nworld\n"), 0600)
|
||||
if err != nil {
|
||||
t.Fatal("failed writing file:", err)
|
||||
}
|
||||
err = ioutil.WriteFile(noPermissionPath, []byte("no access\n"), 0000)
|
||||
if err != nil {
|
||||
t.Fatal("failed writing file:", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
path string
|
||||
expectedLines int
|
||||
expectedIndex int
|
||||
}{
|
||||
{okPath, 1, 0},
|
||||
{missingPath, 0, 0},
|
||||
{noPermissionPath, 0, 0},
|
||||
}
|
||||
for i, test := range tests {
|
||||
lines, index := fileContext(test.path, 1, 0)
|
||||
if !(len(lines) == test.expectedLines && index == test.expectedIndex) {
|
||||
t.Errorf("%d: fileContext(%#v, 1, 0) = %v, %v; expected len()=%d, %d",
|
||||
i, test.path, lines, index, test.expectedLines, test.expectedIndex)
|
||||
}
|
||||
if len(fileCache) != i+1 {
|
||||
t.Errorf("%d: result was not cached; len(fileCached)=%d", i, len(fileCache))
|
||||
}
|
||||
}
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package raven
|
||||
|
||||
type Writer struct {
|
||||
Client *Client
|
||||
Level Severity
|
||||
Logger string // Logger name reported to Sentry
|
||||
}
|
||||
|
||||
// Write formats the byte slice p into a string, and sends a message to
|
||||
// Sentry at the severity level indicated by the Writer w.
|
||||
func (w *Writer) Write(p []byte) (int, error) {
|
||||
message := string(p)
|
||||
|
||||
packet := NewPacket(message, &Message{message, nil})
|
||||
packet.Level = w.Level
|
||||
packet.Logger = w.Logger
|
||||
w.Client.Capture(packet, nil)
|
||||
|
||||
return len(p), nil
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
language: go
|
||||
sudo: false
|
||||
go:
|
||||
- 1.6.4
|
||||
- 1.7.4
|
||||
- tip
|
||||
|
||||
git:
|
||||
depth: 3
|
||||
|
||||
script:
|
||||
- go test -v -covermode=count -coverprofile=coverage.out
|
||||
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Manuel Martínez-Almeida
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
# Server-Sent Events
|
||||
|
||||
[](https://godoc.org/github.com/gin-contrib/sse)
|
||||
[](https://travis-ci.org/gin-contrib/sse)
|
||||
[](https://codecov.io/gh/gin-contrib/sse)
|
||||
[](https://goreportcard.com/report/github.com/gin-contrib/sse)
|
||||
|
||||
Server-sent events (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is [standardized as part of HTML5[1] by the W3C](http://www.w3.org/TR/2009/WD-eventsource-20091029/).
|
||||
|
||||
- [Read this great SSE introduction by the HTML5Rocks guys](http://www.html5rocks.com/en/tutorials/eventsource/basics/)
|
||||
- [Browser support](http://caniuse.com/#feat=eventsource)
|
||||
|
||||
## Sample code
|
||||
|
||||
```go
|
||||
import "github.com/gin-contrib/sse"
|
||||
|
||||
func httpHandler(w http.ResponseWriter, req *http.Request) {
|
||||
// data can be a primitive like a string, an integer or a float
|
||||
sse.Encode(w, sse.Event{
|
||||
Event: "message",
|
||||
Data: "some data\nmore data",
|
||||
})
|
||||
|
||||
// also a complex type, like a map, a struct or a slice
|
||||
sse.Encode(w, sse.Event{
|
||||
Id: "124",
|
||||
Event: "message",
|
||||
Data: map[string]interface{}{
|
||||
"user": "manu",
|
||||
"date": time.Now().Unix(),
|
||||
"content": "hi!",
|
||||
},
|
||||
})
|
||||
}
|
||||
```
|
||||
```
|
||||
event: message
|
||||
data: some data\\nmore data
|
||||
|
||||
id: 124
|
||||
event: message
|
||||
data: {"content":"hi!","date":1431540810,"user":"manu"}
|
||||
|
||||
```
|
||||
|
||||
## Content-Type
|
||||
|
||||
```go
|
||||
fmt.Println(sse.ContentType)
|
||||
```
|
||||
```
|
||||
text/event-stream
|
||||
```
|
||||
|
||||
## Decoding support
|
||||
|
||||
There is a client-side implementation of SSE coming soon.
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package sse
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
type decoder struct {
|
||||
events []Event
|
||||
}
|
||||
|
||||
func Decode(r io.Reader) ([]Event, error) {
|
||||
var dec decoder
|
||||
return dec.decode(r)
|
||||
}
|
||||
|
||||
func (d *decoder) dispatchEvent(event Event, data string) {
|
||||
dataLength := len(data)
|
||||
if dataLength > 0 {
|
||||
//If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer.
|
||||
data = data[:dataLength-1]
|
||||
dataLength--
|
||||
}
|
||||
if dataLength == 0 && event.Event == "" {
|
||||
return
|
||||
}
|
||||
if event.Event == "" {
|
||||
event.Event = "message"
|
||||
}
|
||||
event.Data = data
|
||||
d.events = append(d.events, event)
|
||||
}
|
||||
|
||||
func (d *decoder) decode(r io.Reader) ([]Event, error) {
|
||||
buf, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var currentEvent Event
|
||||
var dataBuffer *bytes.Buffer = new(bytes.Buffer)
|
||||
// TODO (and unit tests)
|
||||
// Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair,
|
||||
// a single U+000A LINE FEED (LF) character,
|
||||
// or a single U+000D CARRIAGE RETURN (CR) character.
|
||||
lines := bytes.Split(buf, []byte{'\n'})
|
||||
for _, line := range lines {
|
||||
if len(line) == 0 {
|
||||
// If the line is empty (a blank line). Dispatch the event.
|
||||
d.dispatchEvent(currentEvent, dataBuffer.String())
|
||||
|
||||
// reset current event and data buffer
|
||||
currentEvent = Event{}
|
||||
dataBuffer.Reset()
|
||||
continue
|
||||
}
|
||||
if line[0] == byte(':') {
|
||||
// If the line starts with a U+003A COLON character (:), ignore the line.
|
||||
continue
|
||||
}
|
||||
|
||||
var field, value []byte
|
||||
colonIndex := bytes.IndexRune(line, ':')
|
||||
if colonIndex != -1 {
|
||||
// If the line contains a U+003A COLON character character (:)
|
||||
// Collect the characters on the line before the first U+003A COLON character (:),
|
||||
// and let field be that string.
|
||||
field = line[:colonIndex]
|
||||
// Collect the characters on the line after the first U+003A COLON character (:),
|
||||
// and let value be that string.
|
||||
value = line[colonIndex+1:]
|
||||
// If value starts with a single U+0020 SPACE character, remove it from value.
|
||||
if len(value) > 0 && value[0] == ' ' {
|
||||
value = value[1:]
|
||||
}
|
||||
} else {
|
||||
// Otherwise, the string is not empty but does not contain a U+003A COLON character character (:)
|
||||
// Use the whole line as the field name, and the empty string as the field value.
|
||||
field = line
|
||||
value = []byte{}
|
||||
}
|
||||
// The steps to process the field given a field name and a field value depend on the field name,
|
||||
// as given in the following list. Field names must be compared literally,
|
||||
// with no case folding performed.
|
||||
switch string(field) {
|
||||
case "event":
|
||||
// Set the event name buffer to field value.
|
||||
currentEvent.Event = string(value)
|
||||
case "id":
|
||||
// Set the event stream's last event ID to the field value.
|
||||
currentEvent.Id = string(value)
|
||||
case "retry":
|
||||
// If the field value consists of only characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9),
|
||||
// then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer.
|
||||
// Otherwise, ignore the field.
|
||||
currentEvent.Id = string(value)
|
||||
case "data":
|
||||
// Append the field value to the data buffer,
|
||||
dataBuffer.Write(value)
|
||||
// then append a single U+000A LINE FEED (LF) character to the data buffer.
|
||||
dataBuffer.WriteString("\n")
|
||||
default:
|
||||
//Otherwise. The field is ignored.
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Once the end of the file is reached, the user agent must dispatch the event one final time.
|
||||
d.dispatchEvent(currentEvent, dataBuffer.String())
|
||||
|
||||
return d.events, nil
|
||||
}
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package sse
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestDecodeSingle1(t *testing.T) {
|
||||
events, err := Decode(bytes.NewBufferString(
|
||||
`data: this is a text
|
||||
event: message
|
||||
fake:
|
||||
id: 123456789010
|
||||
: we can append data
|
||||
: and multiple comments should not break it
|
||||
data: a very nice one`))
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, events, 1)
|
||||
assert.Equal(t, events[0].Event, "message")
|
||||
assert.Equal(t, events[0].Id, "123456789010")
|
||||
}
|
||||
|
||||
func TestDecodeSingle2(t *testing.T) {
|
||||
events, err := Decode(bytes.NewBufferString(
|
||||
`: starting with a comment
|
||||
fake:
|
||||
|
||||
data:this is a \ntext
|
||||
event:a message\n\n
|
||||
fake
|
||||
:and multiple comments\n should not break it\n\n
|
||||
id:1234567890\n10
|
||||
:we can append data
|
||||
data:a very nice one\n!
|
||||
|
||||
|
||||
`))
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, events, 1)
|
||||
assert.Equal(t, events[0].Event, "a message\\n\\n")
|
||||
assert.Equal(t, events[0].Id, "1234567890\\n10")
|
||||
}
|
||||
|
||||
func TestDecodeSingle3(t *testing.T) {
|
||||
events, err := Decode(bytes.NewBufferString(
|
||||
`
|
||||
id:123456ABCabc789010
|
||||
event: message123
|
||||
: we can append data
|
||||
data:this is a text
|
||||
data: a very nice one
|
||||
data:
|
||||
data
|
||||
: ending with a comment`))
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, events, 1)
|
||||
assert.Equal(t, events[0].Event, "message123")
|
||||
assert.Equal(t, events[0].Id, "123456ABCabc789010")
|
||||
}
|
||||
|
||||
func TestDecodeMulti1(t *testing.T) {
|
||||
events, err := Decode(bytes.NewBufferString(
|
||||
`
|
||||
id:
|
||||
event: weird event
|
||||
data:this is a text
|
||||
:data: this should NOT APER
|
||||
data: second line
|
||||
|
||||
: a comment
|
||||
event: message
|
||||
id:123
|
||||
data:this is a text
|
||||
:data: this should NOT APER
|
||||
data: second line
|
||||
|
||||
|
||||
: a comment
|
||||
event: message
|
||||
id:123
|
||||
data:this is a text
|
||||
data: second line
|
||||
|
||||
:hola
|
||||
|
||||
data
|
||||
|
||||
event:
|
||||
|
||||
id`))
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, events, 3)
|
||||
assert.Equal(t, events[0].Event, "weird event")
|
||||
assert.Equal(t, events[0].Id, "")
|
||||
}
|
||||
|
||||
func TestDecodeW3C(t *testing.T) {
|
||||
events, err := Decode(bytes.NewBufferString(
|
||||
`data
|
||||
|
||||
data
|
||||
data
|
||||
|
||||
data:
|
||||
`))
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, events, 1)
|
||||
}
|
||||
-110
@@ -1,110 +0,0 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package sse
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Server-Sent Events
|
||||
// W3C Working Draft 29 October 2009
|
||||
// http://www.w3.org/TR/2009/WD-eventsource-20091029/
|
||||
|
||||
const ContentType = "text/event-stream"
|
||||
|
||||
var contentType = []string{ContentType}
|
||||
var noCache = []string{"no-cache"}
|
||||
|
||||
var fieldReplacer = strings.NewReplacer(
|
||||
"\n", "\\n",
|
||||
"\r", "\\r")
|
||||
|
||||
var dataReplacer = strings.NewReplacer(
|
||||
"\n", "\ndata:",
|
||||
"\r", "\\r")
|
||||
|
||||
type Event struct {
|
||||
Event string
|
||||
Id string
|
||||
Retry uint
|
||||
Data interface{}
|
||||
}
|
||||
|
||||
func Encode(writer io.Writer, event Event) error {
|
||||
w := checkWriter(writer)
|
||||
writeId(w, event.Id)
|
||||
writeEvent(w, event.Event)
|
||||
writeRetry(w, event.Retry)
|
||||
return writeData(w, event.Data)
|
||||
}
|
||||
|
||||
func writeId(w stringWriter, id string) {
|
||||
if len(id) > 0 {
|
||||
w.WriteString("id:")
|
||||
fieldReplacer.WriteString(w, id)
|
||||
w.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
func writeEvent(w stringWriter, event string) {
|
||||
if len(event) > 0 {
|
||||
w.WriteString("event:")
|
||||
fieldReplacer.WriteString(w, event)
|
||||
w.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
func writeRetry(w stringWriter, retry uint) {
|
||||
if retry > 0 {
|
||||
w.WriteString("retry:")
|
||||
w.WriteString(strconv.FormatUint(uint64(retry), 10))
|
||||
w.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
func writeData(w stringWriter, data interface{}) error {
|
||||
w.WriteString("data:")
|
||||
switch kindOfData(data) {
|
||||
case reflect.Struct, reflect.Slice, reflect.Map:
|
||||
err := json.NewEncoder(w).Encode(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.WriteString("\n")
|
||||
default:
|
||||
dataReplacer.WriteString(w, fmt.Sprint(data))
|
||||
w.WriteString("\n\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Event) Render(w http.ResponseWriter) error {
|
||||
r.WriteContentType(w)
|
||||
return Encode(w, r)
|
||||
}
|
||||
|
||||
func (r Event) WriteContentType(w http.ResponseWriter) {
|
||||
header := w.Header()
|
||||
header["Content-Type"] = contentType
|
||||
|
||||
if _, exist := header["Cache-Control"]; !exist {
|
||||
header["Cache-Control"] = noCache
|
||||
}
|
||||
}
|
||||
|
||||
func kindOfData(data interface{}) reflect.Kind {
|
||||
value := reflect.ValueOf(data)
|
||||
valueType := value.Kind()
|
||||
if valueType == reflect.Ptr {
|
||||
valueType = value.Elem().Kind()
|
||||
}
|
||||
return valueType
|
||||
}
|
||||
-255
@@ -1,255 +0,0 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package sse
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestEncodeOnlyData(t *testing.T) {
|
||||
w := new(bytes.Buffer)
|
||||
event := Event{
|
||||
Data: "junk\n\njk\nid:fake",
|
||||
}
|
||||
err := Encode(w, event)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(),
|
||||
`data:junk
|
||||
data:
|
||||
data:jk
|
||||
data:id:fake
|
||||
|
||||
`)
|
||||
|
||||
decoded, _ := Decode(w)
|
||||
assert.Equal(t, decoded, []Event{event})
|
||||
}
|
||||
|
||||
func TestEncodeWithEvent(t *testing.T) {
|
||||
w := new(bytes.Buffer)
|
||||
event := Event{
|
||||
Event: "t\n:<>\r\test",
|
||||
Data: "junk\n\njk\nid:fake",
|
||||
}
|
||||
err := Encode(w, event)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(),
|
||||
`event:t\n:<>\r est
|
||||
data:junk
|
||||
data:
|
||||
data:jk
|
||||
data:id:fake
|
||||
|
||||
`)
|
||||
|
||||
decoded, _ := Decode(w)
|
||||
assert.Equal(t, decoded, []Event{event})
|
||||
}
|
||||
|
||||
func TestEncodeWithId(t *testing.T) {
|
||||
w := new(bytes.Buffer)
|
||||
err := Encode(w, Event{
|
||||
Id: "t\n:<>\r\test",
|
||||
Data: "junk\n\njk\nid:fa\rke",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(),
|
||||
`id:t\n:<>\r est
|
||||
data:junk
|
||||
data:
|
||||
data:jk
|
||||
data:id:fa\rke
|
||||
|
||||
`)
|
||||
}
|
||||
|
||||
func TestEncodeWithRetry(t *testing.T) {
|
||||
w := new(bytes.Buffer)
|
||||
err := Encode(w, Event{
|
||||
Retry: 11,
|
||||
Data: "junk\n\njk\nid:fake\n",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(),
|
||||
`retry:11
|
||||
data:junk
|
||||
data:
|
||||
data:jk
|
||||
data:id:fake
|
||||
data:
|
||||
|
||||
`)
|
||||
}
|
||||
|
||||
func TestEncodeWithEverything(t *testing.T) {
|
||||
w := new(bytes.Buffer)
|
||||
err := Encode(w, Event{
|
||||
Event: "abc",
|
||||
Id: "12345",
|
||||
Retry: 10,
|
||||
Data: "some data",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(), "id:12345\nevent:abc\nretry:10\ndata:some data\n\n")
|
||||
}
|
||||
|
||||
func TestEncodeMap(t *testing.T) {
|
||||
w := new(bytes.Buffer)
|
||||
err := Encode(w, Event{
|
||||
Event: "a map",
|
||||
Data: map[string]interface{}{
|
||||
"foo": "b\n\rar",
|
||||
"bar": "id: 2",
|
||||
},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(), "event:a map\ndata:{\"bar\":\"id: 2\",\"foo\":\"b\\n\\rar\"}\n\n")
|
||||
}
|
||||
|
||||
func TestEncodeSlice(t *testing.T) {
|
||||
w := new(bytes.Buffer)
|
||||
err := Encode(w, Event{
|
||||
Event: "a slice",
|
||||
Data: []interface{}{1, "text", map[string]interface{}{"foo": "bar"}},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(), "event:a slice\ndata:[1,\"text\",{\"foo\":\"bar\"}]\n\n")
|
||||
}
|
||||
|
||||
func TestEncodeStruct(t *testing.T) {
|
||||
myStruct := struct {
|
||||
A int
|
||||
B string `json:"value"`
|
||||
}{1, "number"}
|
||||
|
||||
w := new(bytes.Buffer)
|
||||
err := Encode(w, Event{
|
||||
Event: "a struct",
|
||||
Data: myStruct,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(), "event:a struct\ndata:{\"A\":1,\"value\":\"number\"}\n\n")
|
||||
|
||||
w.Reset()
|
||||
err = Encode(w, Event{
|
||||
Event: "a struct",
|
||||
Data: &myStruct,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(), "event:a struct\ndata:{\"A\":1,\"value\":\"number\"}\n\n")
|
||||
}
|
||||
|
||||
func TestEncodeInteger(t *testing.T) {
|
||||
w := new(bytes.Buffer)
|
||||
err := Encode(w, Event{
|
||||
Event: "an integer",
|
||||
Data: 1,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(), "event:an integer\ndata:1\n\n")
|
||||
}
|
||||
|
||||
func TestEncodeFloat(t *testing.T) {
|
||||
w := new(bytes.Buffer)
|
||||
err := Encode(w, Event{
|
||||
Event: "Float",
|
||||
Data: 1.5,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.String(), "event:Float\ndata:1.5\n\n")
|
||||
}
|
||||
|
||||
func TestEncodeStream(t *testing.T) {
|
||||
w := new(bytes.Buffer)
|
||||
|
||||
Encode(w, Event{
|
||||
Event: "float",
|
||||
Data: 1.5,
|
||||
})
|
||||
|
||||
Encode(w, Event{
|
||||
Id: "123",
|
||||
Data: map[string]interface{}{"foo": "bar", "bar": "foo"},
|
||||
})
|
||||
|
||||
Encode(w, Event{
|
||||
Id: "124",
|
||||
Event: "chat",
|
||||
Data: "hi! dude",
|
||||
})
|
||||
assert.Equal(t, w.String(), "event:float\ndata:1.5\n\nid:123\ndata:{\"bar\":\"foo\",\"foo\":\"bar\"}\n\nid:124\nevent:chat\ndata:hi! dude\n\n")
|
||||
}
|
||||
|
||||
func TestRenderSSE(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
err := (Event{
|
||||
Event: "msg",
|
||||
Data: "hi! how are you?",
|
||||
}).Render(w)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, w.Body.String(), "event:msg\ndata:hi! how are you?\n\n")
|
||||
assert.Equal(t, w.Header().Get("Content-Type"), "text/event-stream")
|
||||
assert.Equal(t, w.Header().Get("Cache-Control"), "no-cache")
|
||||
}
|
||||
|
||||
func BenchmarkResponseWriter(b *testing.B) {
|
||||
w := httptest.NewRecorder()
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
(Event{
|
||||
Event: "new_message",
|
||||
Data: "hi! how are you? I am fine. this is a long stupid message!!!",
|
||||
}).Render(w)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFullSSE(b *testing.B) {
|
||||
buf := new(bytes.Buffer)
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Encode(buf, Event{
|
||||
Event: "new_message",
|
||||
Id: "13435",
|
||||
Retry: 10,
|
||||
Data: "hi! how are you? I am fine. this is a long stupid message!!!",
|
||||
})
|
||||
buf.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkNoRetrySSE(b *testing.B) {
|
||||
buf := new(bytes.Buffer)
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Encode(buf, Event{
|
||||
Event: "new_message",
|
||||
Id: "13435",
|
||||
Data: "hi! how are you? I am fine. this is a long stupid message!!!",
|
||||
})
|
||||
buf.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkSimpleSSE(b *testing.B) {
|
||||
buf := new(bytes.Buffer)
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Encode(buf, Event{
|
||||
Event: "new_message",
|
||||
Data: "hi! how are you? I am fine. this is a long stupid message!!!",
|
||||
})
|
||||
buf.Reset()
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package sse
|
||||
|
||||
import "io"
|
||||
|
||||
type stringWriter interface {
|
||||
io.Writer
|
||||
WriteString(string) (int, error)
|
||||
}
|
||||
|
||||
type stringWrapper struct {
|
||||
io.Writer
|
||||
}
|
||||
|
||||
func (w stringWrapper) WriteString(str string) (int, error) {
|
||||
return w.Writer.Write([]byte(str))
|
||||
}
|
||||
|
||||
func checkWriter(writer io.Writer) stringWriter {
|
||||
if w, ok := writer.(stringWriter); ok {
|
||||
return w
|
||||
} else {
|
||||
return stringWrapper{writer}
|
||||
}
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
coverage.out
|
||||
dump.rdb
|
||||
*/vendor/*
|
||||
!*/vendor/vendor.json
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
language: go
|
||||
sudo: false
|
||||
|
||||
go:
|
||||
- 1.6.x
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- tip
|
||||
|
||||
install:
|
||||
- echo "ignore go get"
|
||||
- go get -u github.com/kardianos/govendor
|
||||
- go get github.com/campoy/embedmd
|
||||
- govendor sync
|
||||
|
||||
script:
|
||||
- embedmd -d *.md
|
||||
- go test -v -covermode=atomic -coverprofile=coverage.out
|
||||
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
||||
|
||||
notifications:
|
||||
webhooks:
|
||||
urls:
|
||||
- https://webhooks.gitter.im/e/acc2c57482e94b44f557
|
||||
on_success: change
|
||||
on_failure: always
|
||||
on_start: false
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2016 gin-contrib
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
# static middleware
|
||||
|
||||
[](https://travis-ci.org/gin-contrib/static)
|
||||
[](https://codecov.io/gh/gin-contrib/static)
|
||||
[](https://goreportcard.com/report/github.com/gin-contrib/static)
|
||||
[](https://godoc.org/github.com/gin-contrib/static)
|
||||
|
||||
Static middleware
|
||||
|
||||
## Usage
|
||||
|
||||
### Start using it
|
||||
|
||||
Download and install it:
|
||||
|
||||
```sh
|
||||
$ go get github.com/gin-contrib/static
|
||||
```
|
||||
|
||||
Import it in your code:
|
||||
|
||||
```go
|
||||
import "github.com/gin-contrib/static"
|
||||
```
|
||||
|
||||
### Canonical example:
|
||||
|
||||
See the [example](example)
|
||||
|
||||
[embedmd]:# (example/simple/example.go go)
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gin-contrib/static"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// if Allow DirectoryIndex
|
||||
//r.Use(static.Serve("/", static.LocalFile("/tmp", true)))
|
||||
// set prefix
|
||||
//r.Use(static.Serve("/static", static.LocalFile("/tmp", true)))
|
||||
|
||||
r.Use(static.Serve("/", static.LocalFile("/tmp", false)))
|
||||
r.GET("/ping", func(c *gin.Context) {
|
||||
c.String(200, "test")
|
||||
})
|
||||
// Listen and Server in 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
package static
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type ServeFileSystem interface {
|
||||
http.FileSystem
|
||||
Exists(prefix string, path string) bool
|
||||
}
|
||||
|
||||
type localFileSystem struct {
|
||||
http.FileSystem
|
||||
root string
|
||||
indexes bool
|
||||
}
|
||||
|
||||
func LocalFile(root string, indexes bool) *localFileSystem {
|
||||
return &localFileSystem{
|
||||
FileSystem: gin.Dir(root, indexes),
|
||||
root: root,
|
||||
indexes: indexes,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *localFileSystem) Exists(prefix string, filepath string) bool {
|
||||
if p := strings.TrimPrefix(filepath, prefix); len(p) < len(filepath) {
|
||||
name := path.Join(l.root, p)
|
||||
stats, err := os.Stat(name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if !l.indexes && stats.IsDir() {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ServeRoot(urlPrefix, root string) gin.HandlerFunc {
|
||||
return Serve(urlPrefix, LocalFile(root, false))
|
||||
}
|
||||
|
||||
// Static returns a middleware handler that serves static files in the given directory.
|
||||
func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
|
||||
fileserver := http.FileServer(fs)
|
||||
if urlPrefix != "" {
|
||||
fileserver = http.StripPrefix(urlPrefix, fileserver)
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
if fs.Exists(urlPrefix, c.Request.URL.Path) {
|
||||
fileserver.ServeHTTP(c.Writer, c.Request)
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package static
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
|
||||
req, _ := http.NewRequest(method, path, nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestEmptyDirectory(t *testing.T) {
|
||||
// SETUP file
|
||||
testRoot, _ := os.Getwd()
|
||||
f, err := ioutil.TempFile(testRoot, "")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
f.WriteString("Gin Web Framework")
|
||||
f.Close()
|
||||
|
||||
dir, filename := filepath.Split(f.Name())
|
||||
|
||||
router := gin.New()
|
||||
router.Use(ServeRoot("/", dir))
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
c.String(200, "index")
|
||||
})
|
||||
router.GET("/a", func(c *gin.Context) {
|
||||
c.String(200, "a")
|
||||
})
|
||||
router.GET("/"+filename, func(c *gin.Context) {
|
||||
c.String(200, "this is not printed")
|
||||
})
|
||||
w := performRequest(router, "GET", "/")
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "index")
|
||||
|
||||
w = performRequest(router, "GET", "/"+filename)
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "Gin Web Framework")
|
||||
|
||||
w = performRequest(router, "GET", "/"+filename+"a")
|
||||
assert.Equal(t, w.Code, 404)
|
||||
|
||||
w = performRequest(router, "GET", "/a")
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "a")
|
||||
|
||||
router2 := gin.New()
|
||||
router2.Use(ServeRoot("/static", dir))
|
||||
router2.GET("/"+filename, func(c *gin.Context) {
|
||||
c.String(200, "this is printed")
|
||||
})
|
||||
|
||||
w = performRequest(router2, "GET", "/")
|
||||
assert.Equal(t, w.Code, 404)
|
||||
|
||||
w = performRequest(router2, "GET", "/static")
|
||||
assert.Equal(t, w.Code, 404)
|
||||
router2.GET("/static", func(c *gin.Context) {
|
||||
c.String(200, "index")
|
||||
})
|
||||
|
||||
w = performRequest(router2, "GET", "/static")
|
||||
assert.Equal(t, w.Code, 200)
|
||||
|
||||
w = performRequest(router2, "GET", "/"+filename)
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "this is printed")
|
||||
|
||||
w = performRequest(router2, "GET", "/static/"+filename)
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "Gin Web Framework")
|
||||
}
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
*/Godeps/*
|
||||
!*/Godeps/Godeps.json
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
language: go
|
||||
go:
|
||||
- 1.6.x
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- tip
|
||||
|
||||
services:
|
||||
- memcache
|
||||
- redis-server
|
||||
|
||||
notifications:
|
||||
webhooks:
|
||||
urls:
|
||||
- https://webhooks.gitter.im/e/acc2c57482e94b44f557
|
||||
on_success: change
|
||||
on_failure: always
|
||||
on_start: false
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
# gin-gonic/contrib
|
||||
|
||||
[](https://travis-ci.org/gin-gonic/contrib)
|
||||
|
||||
Here you'll find middleware ready to use with [Gin Framework](https://github.com/gin-gonic/gin). Submit your pull request, either with the package in a folder, or by adding a link to this `README.md`.
|
||||
|
||||
If adding a package directly, don't forget to create a `README.md` inside with author name.
|
||||
If adding a link to your own repository, please follow this example:
|
||||
|
||||
```
|
||||
+ nameOfMiddleware (https://github.com/yourusername/yourrepo)
|
||||
```
|
||||
|
||||
Each author is responsible of maintaining his own code, although if you submit as a package, you allow the community to fix it. You can also submit a pull request to fix an existing package.
|
||||
|
||||
## List of external middleware
|
||||
|
||||
+ [RestGate](https://github.com/pjebs/restgate) - Secure authentication for REST API endpoints
|
||||
+ [staticbin](https://github.com/olebedev/staticbin) - middleware/handler for serving static files from binary data
|
||||
+ [gin-cors](https://github.com/gin-contrib/cors) - Official CORS gin's middleware
|
||||
+ [gin-csrf](https://github.com/utrack/gin-csrf) - CSRF protection
|
||||
+ [gin-health](https://github.com/utrack/gin-health) - middleware that simplifies stat reporting via [gocraft/health](https://github.com/gocraft/health)
|
||||
+ [gin-merry](https://github.com/utrack/gin-merry) - middleware for pretty-printing [merry](https://github.com/ansel1/merry) errors with context
|
||||
+ [gin-revision](https://github.com/appleboy/gin-revision-middleware) - Revision middleware for Gin framework
|
||||
+ [gin-jwt](https://github.com/appleboy/gin-jwt) - JWT Middleware for Gin Framework
|
||||
+ [gin-sessions](https://github.com/kimiazhu/ginweb-contrib/tree/master/sessions) - session middleware based on mongodb and mysql
|
||||
+ [gin-location](https://github.com/drone/gin-location) - middleware for exposing the server's hostname and scheme
|
||||
+ [gin-nice-recovery](https://github.com/ekyoung/gin-nice-recovery) - panic recovery middleware that let's you build a nicer user experience
|
||||
+ [gin-limit](https://github.com/aviddiviner/gin-limit) - limits simultaneous requests; can help with high traffic load
|
||||
+ [ez-gin-template](https://github.com/michelloworld/ez-gin-template) - easy template wrap for gin
|
||||
+ [gin-hydra](https://github.com/janekolszak/gin-hydra) - [Hydra](https://github.com/ory-am/hydra) middleware for Gin
|
||||
+ [gin-glog](https://github.com/zalando/gin-glog) - meant as drop-in replacement for Gin's default logger
|
||||
+ [gin-gomonitor](https://github.com/zalando/gin-gomonitor) - for exposing metrics with Go-Monitor
|
||||
+ [gin-oauth2](https://github.com/zalando/gin-oauth2) - for working with OAuth2
|
||||
+ [static](https://github.com/hyperboloide/static) An alternative static assets handler for the gin framework.
|
||||
+ [xss-mw](https://github.com/dvwright/xss-mw) - XssMw is a middleware designed to "auto remove XSS" from user submitted input
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
# sentry
|
||||
|
||||
Middleware to integrate with [sentry](https://getsentry.com/) crash reporting. Middleware version of `raven.RecoveryHandler()`.
|
||||
|
||||
## EOL-warning
|
||||
|
||||
**This package has been abandoned on 2017-01-13. Please use [gin-contrib/sentry](https://github.com/gin-contrib/sentry) instead.**
|
||||
|
||||
## Example
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/getsentry/raven-go"
|
||||
"github.com/gin-gonic/contrib/sentry"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func init() {
|
||||
raven.SetDSN("https://<key>:<secret>@app.getsentry.com/<project>")
|
||||
}
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
r.Use(sentry.Recovery(raven.DefaultClient, false))
|
||||
// ...
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/getsentry/raven-go"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Recovery(client *raven.Client, onlyCrashes bool) gin.HandlerFunc {
|
||||
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
flags := map[string]string{
|
||||
"endpoint": c.Request.RequestURI,
|
||||
}
|
||||
if rval := recover(); rval != nil {
|
||||
debug.PrintStack()
|
||||
rvalStr := fmt.Sprint(rval)
|
||||
packet := raven.NewPacket(rvalStr,
|
||||
raven.NewException(errors.New(rvalStr), raven.NewStacktrace(2, 3, nil)),
|
||||
raven.NewHttp(c.Request))
|
||||
client.Capture(packet, flags)
|
||||
c.AbortWithStatus(http.StatusInternalServerError)
|
||||
}
|
||||
if !onlyCrashes {
|
||||
for _, item := range c.Errors {
|
||||
packet := raven.NewPacket(item.Error(),
|
||||
&raven.Message{
|
||||
Message: item.Error(),
|
||||
Params: []interface{}{item.Meta},
|
||||
},
|
||||
raven.NewHttp(c.Request))
|
||||
client.Capture(packet, flags)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
vendor/*
|
||||
!vendor/vendor.json
|
||||
coverage.out
|
||||
count.out
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
language: go
|
||||
sudo: false
|
||||
go:
|
||||
- 1.6.x
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- master
|
||||
|
||||
git:
|
||||
depth: 3
|
||||
|
||||
install:
|
||||
- make install
|
||||
|
||||
script:
|
||||
- make vet
|
||||
- make fmt-check
|
||||
- make embedmd
|
||||
- make misspell-check
|
||||
- make test
|
||||
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
||||
|
||||
notifications:
|
||||
webhooks:
|
||||
urls:
|
||||
- https://webhooks.gitter.im/e/7f95bf605c4d356372f4
|
||||
on_success: change # options: [always|never|change] default: always
|
||||
on_failure: always # options: [always|never|change] default: always
|
||||
on_start: false # default: false
|
||||
-227
@@ -1,227 +0,0 @@
|
||||
List of all the awesome people working to make Gin the best Web Framework in Go.
|
||||
|
||||
## gin 0.x series authors
|
||||
|
||||
**Maintainer:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho)
|
||||
|
||||
People and companies, who have contributed, in alphabetical order.
|
||||
|
||||
**@858806258 (杰哥)**
|
||||
- Fix typo in example
|
||||
|
||||
|
||||
**@achedeuzot (Klemen Sever)**
|
||||
- Fix newline debug printing
|
||||
|
||||
|
||||
**@adammck (Adam Mckaig)**
|
||||
- Add MIT license
|
||||
|
||||
|
||||
**@AlexanderChen1989 (Alexander)**
|
||||
- Typos in README
|
||||
|
||||
|
||||
**@alexanderdidenko (Aleksandr Didenko)**
|
||||
- Add support multipart/form-data
|
||||
|
||||
|
||||
**@alexandernyquist (Alexander Nyquist)**
|
||||
- Using template.Must to fix multiple return issue
|
||||
- ★ Added support for OPTIONS verb
|
||||
- ★ Setting response headers before calling WriteHeader
|
||||
- Improved documentation for model binding
|
||||
- ★ Added Content.Redirect()
|
||||
- ★ Added tons of Unit tests
|
||||
|
||||
|
||||
**@austinheap (Austin Heap)**
|
||||
- Added travis CI integration
|
||||
|
||||
|
||||
**@andredublin (Andre Dublin)**
|
||||
- Fix typo in comment
|
||||
|
||||
|
||||
**@bredov (Ludwig Valda Vasquez)**
|
||||
- Fix html templating in debug mode
|
||||
|
||||
|
||||
**@bluele (Jun Kimura)**
|
||||
- Fixes code examples in README
|
||||
|
||||
|
||||
**@chad-russell**
|
||||
- ★ Support for serializing gin.H into XML
|
||||
|
||||
|
||||
**@dickeyxxx (Jeff Dickey)**
|
||||
- Typos in README
|
||||
- Add example about serving static files
|
||||
|
||||
|
||||
**@donileo (Adonis)**
|
||||
- Add NoMethod handler
|
||||
|
||||
|
||||
**@dutchcoders (DutchCoders)**
|
||||
- ★ Fix security bug that allows client to spoof ip
|
||||
- Fix typo. r.HTMLTemplates -> SetHTMLTemplate
|
||||
|
||||
|
||||
**@el3ctro- (Joshua Loper)**
|
||||
- Fix typo in example
|
||||
|
||||
|
||||
**@ethankan (Ethan Kan)**
|
||||
- Unsigned integers in binding
|
||||
|
||||
|
||||
**(Evgeny Persienko)**
|
||||
- Validate sub structures
|
||||
|
||||
|
||||
**@frankbille (Frank Bille)**
|
||||
- Add support for HTTP Realm Auth
|
||||
|
||||
|
||||
**@fmd (Fareed Dudhia)**
|
||||
- Fix typo. SetHTTPTemplate -> SetHTMLTemplate
|
||||
|
||||
|
||||
**@ironiridis (Christopher Harrington)**
|
||||
- Remove old reference
|
||||
|
||||
|
||||
**@jammie-stackhouse (Jamie Stackhouse)**
|
||||
- Add more shortcuts for router methods
|
||||
|
||||
|
||||
**@jasonrhansen**
|
||||
- Fix spelling and grammar errors in documentation
|
||||
|
||||
|
||||
**@JasonSoft (Jason Lee)**
|
||||
- Fix typo in comment
|
||||
|
||||
|
||||
**@joiggama (Ignacio Galindo)**
|
||||
- Add utf-8 charset header on renders
|
||||
|
||||
|
||||
**@julienschmidt (Julien Schmidt)**
|
||||
- gofmt the code examples
|
||||
|
||||
|
||||
**@kelcecil (Kel Cecil)**
|
||||
- Fix readme typo
|
||||
|
||||
|
||||
**@kyledinh (Kyle Dinh)**
|
||||
- Adds RunTLS()
|
||||
|
||||
|
||||
**@LinusU (Linus Unnebäck)**
|
||||
- Small fixes in README
|
||||
|
||||
|
||||
**@loongmxbt (Saint Asky)**
|
||||
- Fix typo in example
|
||||
|
||||
|
||||
**@lucas-clemente (Lucas Clemente)**
|
||||
- ★ work around path.Join removing trailing slashes from routes
|
||||
|
||||
|
||||
**@mattn (Yasuhiro Matsumoto)**
|
||||
- Improve color logger
|
||||
|
||||
|
||||
**@mdigger (Dmitry Sedykh)**
|
||||
- Fixes Form binding when content-type is x-www-form-urlencoded
|
||||
- No repeat call c.Writer.Status() in gin.Logger
|
||||
- Fixes Content-Type for json render
|
||||
|
||||
|
||||
**@mirzac (Mirza Ceric)**
|
||||
- Fix debug printing
|
||||
|
||||
|
||||
**@mopemope (Yutaka Matsubara)**
|
||||
- ★ Adds Godep support (Dependencies Manager)
|
||||
- Fix variadic parameter in the flexible render API
|
||||
- Fix Corrupted plain render
|
||||
- Add Pluggable View Renderer Example
|
||||
|
||||
|
||||
**@msemenistyi (Mykyta Semenistyi)**
|
||||
- update Readme.md. Add code to String method
|
||||
|
||||
|
||||
**@msoedov (Sasha Myasoedov)**
|
||||
- ★ Adds tons of unit tests.
|
||||
|
||||
|
||||
**@ngerakines (Nick Gerakines)**
|
||||
- ★ Improves API, c.GET() doesn't panic
|
||||
- Adds MustGet() method
|
||||
|
||||
|
||||
**@r8k (Rajiv Kilaparti)**
|
||||
- Fix Port usage in README.
|
||||
|
||||
|
||||
**@rayrod2030 (Ray Rodriguez)**
|
||||
- Fix typo in example
|
||||
|
||||
|
||||
**@rns**
|
||||
- Fix typo in example
|
||||
|
||||
|
||||
**@RobAWilkinson (Robert Wilkinson)**
|
||||
- Add example of forms and params
|
||||
|
||||
|
||||
**@rogierlommers (Rogier Lommers)**
|
||||
- Add updated static serve example
|
||||
|
||||
|
||||
**@se77en (Damon Zhao)**
|
||||
- Improve color logging
|
||||
|
||||
|
||||
**@silasb (Silas Baronda)**
|
||||
- Fixing quotes in README
|
||||
|
||||
|
||||
**@SkuliOskarsson (Skuli Oskarsson)**
|
||||
- Fixes some texts in README II
|
||||
|
||||
|
||||
**@slimmy (Jimmy Pettersson)**
|
||||
- Added messages for required bindings
|
||||
|
||||
|
||||
**@smira (Andrey Smirnov)**
|
||||
- Add support for ignored/unexported fields in binding
|
||||
|
||||
|
||||
**@superalsrk (SRK.Lyu)**
|
||||
- Update httprouter godeps
|
||||
|
||||
|
||||
**@tebeka (Miki Tebeka)**
|
||||
- Use net/http constants instead of numeric values
|
||||
|
||||
|
||||
**@techjanitor**
|
||||
- Update context.go reserved IPs
|
||||
|
||||
|
||||
**@yosssi (Keiji Yoshida)**
|
||||
- Fix link in README
|
||||
|
||||
|
||||
**@yuyabee**
|
||||
- Fixed README
|
||||
-298
@@ -1,298 +0,0 @@
|
||||
**Machine:** intel i7 ivy bridge quad-core. 8GB RAM.
|
||||
**Date:** June 4th, 2015
|
||||
[https://github.com/gin-gonic/go-http-routing-benchmark](https://github.com/gin-gonic/go-http-routing-benchmark)
|
||||
|
||||
```
|
||||
BenchmarkAce_Param 5000000 372 ns/op 32 B/op 1 allocs/op
|
||||
BenchmarkBear_Param 1000000 1165 ns/op 424 B/op 5 allocs/op
|
||||
BenchmarkBeego_Param 1000000 2440 ns/op 720 B/op 10 allocs/op
|
||||
BenchmarkBone_Param 1000000 1067 ns/op 384 B/op 3 allocs/op
|
||||
BenchmarkDenco_Param 5000000 240 ns/op 32 B/op 1 allocs/op
|
||||
BenchmarkEcho_Param 10000000 130 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGin_Param 10000000 133 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_Param 1000000 1826 ns/op 656 B/op 9 allocs/op
|
||||
BenchmarkGoji_Param 2000000 957 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkGoJsonRest_Param 1000000 2021 ns/op 657 B/op 14 allocs/op
|
||||
BenchmarkGoRestful_Param 200000 8825 ns/op 2496 B/op 31 allocs/op
|
||||
BenchmarkGorillaMux_Param 500000 3340 ns/op 784 B/op 9 allocs/op
|
||||
BenchmarkHttpRouter_Param 10000000 152 ns/op 32 B/op 1 allocs/op
|
||||
BenchmarkHttpTreeMux_Param 2000000 717 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkKocha_Param 3000000 423 ns/op 56 B/op 3 allocs/op
|
||||
BenchmarkMacaron_Param 1000000 3410 ns/op 1104 B/op 11 allocs/op
|
||||
BenchmarkMartini_Param 200000 7101 ns/op 1152 B/op 12 allocs/op
|
||||
BenchmarkPat_Param 1000000 2040 ns/op 656 B/op 14 allocs/op
|
||||
BenchmarkPossum_Param 1000000 2048 ns/op 624 B/op 7 allocs/op
|
||||
BenchmarkR2router_Param 1000000 1144 ns/op 432 B/op 6 allocs/op
|
||||
BenchmarkRevel_Param 200000 6725 ns/op 1672 B/op 28 allocs/op
|
||||
BenchmarkRivet_Param 1000000 1121 ns/op 464 B/op 5 allocs/op
|
||||
BenchmarkTango_Param 1000000 1479 ns/op 256 B/op 10 allocs/op
|
||||
BenchmarkTigerTonic_Param 1000000 3393 ns/op 992 B/op 19 allocs/op
|
||||
BenchmarkTraffic_Param 300000 5525 ns/op 1984 B/op 23 allocs/op
|
||||
BenchmarkVulcan_Param 2000000 924 ns/op 98 B/op 3 allocs/op
|
||||
BenchmarkZeus_Param 1000000 1084 ns/op 368 B/op 3 allocs/op
|
||||
BenchmarkAce_Param5 3000000 614 ns/op 160 B/op 1 allocs/op
|
||||
BenchmarkBear_Param5 1000000 1617 ns/op 469 B/op 5 allocs/op
|
||||
BenchmarkBeego_Param5 1000000 3373 ns/op 992 B/op 13 allocs/op
|
||||
BenchmarkBone_Param5 1000000 1478 ns/op 432 B/op 3 allocs/op
|
||||
BenchmarkDenco_Param5 3000000 570 ns/op 160 B/op 1 allocs/op
|
||||
BenchmarkEcho_Param5 5000000 256 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGin_Param5 10000000 222 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_Param5 1000000 2789 ns/op 928 B/op 12 allocs/op
|
||||
BenchmarkGoji_Param5 1000000 1287 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkGoJsonRest_Param5 1000000 3670 ns/op 1105 B/op 17 allocs/op
|
||||
BenchmarkGoRestful_Param5 200000 10756 ns/op 2672 B/op 31 allocs/op
|
||||
BenchmarkGorillaMux_Param5 300000 5543 ns/op 912 B/op 9 allocs/op
|
||||
BenchmarkHttpRouter_Param5 5000000 403 ns/op 160 B/op 1 allocs/op
|
||||
BenchmarkHttpTreeMux_Param5 1000000 1089 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkKocha_Param5 1000000 1682 ns/op 440 B/op 10 allocs/op
|
||||
BenchmarkMacaron_Param5 300000 4596 ns/op 1376 B/op 14 allocs/op
|
||||
BenchmarkMartini_Param5 100000 15703 ns/op 1280 B/op 12 allocs/op
|
||||
BenchmarkPat_Param5 300000 5320 ns/op 1008 B/op 42 allocs/op
|
||||
BenchmarkPossum_Param5 1000000 2155 ns/op 624 B/op 7 allocs/op
|
||||
BenchmarkR2router_Param5 1000000 1559 ns/op 432 B/op 6 allocs/op
|
||||
BenchmarkRevel_Param5 200000 8184 ns/op 2024 B/op 35 allocs/op
|
||||
BenchmarkRivet_Param5 1000000 1914 ns/op 528 B/op 9 allocs/op
|
||||
BenchmarkTango_Param5 1000000 3280 ns/op 944 B/op 18 allocs/op
|
||||
BenchmarkTigerTonic_Param5 200000 11638 ns/op 2519 B/op 53 allocs/op
|
||||
BenchmarkTraffic_Param5 200000 8941 ns/op 2280 B/op 31 allocs/op
|
||||
BenchmarkVulcan_Param5 1000000 1279 ns/op 98 B/op 3 allocs/op
|
||||
BenchmarkZeus_Param5 1000000 1574 ns/op 416 B/op 3 allocs/op
|
||||
BenchmarkAce_Param20 1000000 1528 ns/op 640 B/op 1 allocs/op
|
||||
BenchmarkBear_Param20 300000 4906 ns/op 1633 B/op 5 allocs/op
|
||||
BenchmarkBeego_Param20 200000 10529 ns/op 3868 B/op 17 allocs/op
|
||||
BenchmarkBone_Param20 300000 7362 ns/op 2539 B/op 5 allocs/op
|
||||
BenchmarkDenco_Param20 1000000 1884 ns/op 640 B/op 1 allocs/op
|
||||
BenchmarkEcho_Param20 2000000 689 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGin_Param20 3000000 545 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_Param20 200000 9437 ns/op 3804 B/op 16 allocs/op
|
||||
BenchmarkGoji_Param20 500000 3987 ns/op 1246 B/op 2 allocs/op
|
||||
BenchmarkGoJsonRest_Param20 100000 12799 ns/op 4492 B/op 21 allocs/op
|
||||
BenchmarkGoRestful_Param20 100000 19451 ns/op 5244 B/op 33 allocs/op
|
||||
BenchmarkGorillaMux_Param20 100000 12456 ns/op 3275 B/op 11 allocs/op
|
||||
BenchmarkHttpRouter_Param20 1000000 1333 ns/op 640 B/op 1 allocs/op
|
||||
BenchmarkHttpTreeMux_Param20 300000 6490 ns/op 2187 B/op 4 allocs/op
|
||||
BenchmarkKocha_Param20 300000 5335 ns/op 1808 B/op 27 allocs/op
|
||||
BenchmarkMacaron_Param20 200000 11325 ns/op 4252 B/op 18 allocs/op
|
||||
BenchmarkMartini_Param20 20000 64419 ns/op 3644 B/op 14 allocs/op
|
||||
BenchmarkPat_Param20 50000 24672 ns/op 4888 B/op 151 allocs/op
|
||||
BenchmarkPossum_Param20 1000000 2085 ns/op 624 B/op 7 allocs/op
|
||||
BenchmarkR2router_Param20 300000 6809 ns/op 2283 B/op 8 allocs/op
|
||||
BenchmarkRevel_Param20 100000 16600 ns/op 5551 B/op 54 allocs/op
|
||||
BenchmarkRivet_Param20 200000 8428 ns/op 2620 B/op 26 allocs/op
|
||||
BenchmarkTango_Param20 100000 16302 ns/op 8224 B/op 48 allocs/op
|
||||
BenchmarkTigerTonic_Param20 30000 46828 ns/op 10538 B/op 178 allocs/op
|
||||
BenchmarkTraffic_Param20 50000 28871 ns/op 7998 B/op 66 allocs/op
|
||||
BenchmarkVulcan_Param20 1000000 2267 ns/op 98 B/op 3 allocs/op
|
||||
BenchmarkZeus_Param20 300000 6828 ns/op 2507 B/op 5 allocs/op
|
||||
BenchmarkAce_ParamWrite 3000000 502 ns/op 40 B/op 2 allocs/op
|
||||
BenchmarkBear_ParamWrite 1000000 1303 ns/op 424 B/op 5 allocs/op
|
||||
BenchmarkBeego_ParamWrite 1000000 2489 ns/op 728 B/op 11 allocs/op
|
||||
BenchmarkBone_ParamWrite 1000000 1181 ns/op 384 B/op 3 allocs/op
|
||||
BenchmarkDenco_ParamWrite 5000000 315 ns/op 32 B/op 1 allocs/op
|
||||
BenchmarkEcho_ParamWrite 10000000 237 ns/op 8 B/op 1 allocs/op
|
||||
BenchmarkGin_ParamWrite 5000000 336 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_ParamWrite 1000000 2079 ns/op 664 B/op 10 allocs/op
|
||||
BenchmarkGoji_ParamWrite 1000000 1092 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkGoJsonRest_ParamWrite 1000000 3329 ns/op 1136 B/op 19 allocs/op
|
||||
BenchmarkGoRestful_ParamWrite 200000 9273 ns/op 2504 B/op 32 allocs/op
|
||||
BenchmarkGorillaMux_ParamWrite 500000 3919 ns/op 792 B/op 10 allocs/op
|
||||
BenchmarkHttpRouter_ParamWrite 10000000 223 ns/op 32 B/op 1 allocs/op
|
||||
BenchmarkHttpTreeMux_ParamWrite 2000000 788 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkKocha_ParamWrite 3000000 549 ns/op 56 B/op 3 allocs/op
|
||||
BenchmarkMacaron_ParamWrite 500000 4558 ns/op 1216 B/op 16 allocs/op
|
||||
BenchmarkMartini_ParamWrite 200000 8850 ns/op 1256 B/op 16 allocs/op
|
||||
BenchmarkPat_ParamWrite 500000 3679 ns/op 1088 B/op 19 allocs/op
|
||||
BenchmarkPossum_ParamWrite 1000000 2114 ns/op 624 B/op 7 allocs/op
|
||||
BenchmarkR2router_ParamWrite 1000000 1320 ns/op 432 B/op 6 allocs/op
|
||||
BenchmarkRevel_ParamWrite 200000 8048 ns/op 2128 B/op 33 allocs/op
|
||||
BenchmarkRivet_ParamWrite 1000000 1393 ns/op 472 B/op 6 allocs/op
|
||||
BenchmarkTango_ParamWrite 2000000 819 ns/op 136 B/op 5 allocs/op
|
||||
BenchmarkTigerTonic_ParamWrite 300000 5860 ns/op 1440 B/op 25 allocs/op
|
||||
BenchmarkTraffic_ParamWrite 200000 7429 ns/op 2400 B/op 27 allocs/op
|
||||
BenchmarkVulcan_ParamWrite 2000000 972 ns/op 98 B/op 3 allocs/op
|
||||
BenchmarkZeus_ParamWrite 1000000 1226 ns/op 368 B/op 3 allocs/op
|
||||
BenchmarkAce_GithubStatic 5000000 294 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkBear_GithubStatic 3000000 575 ns/op 88 B/op 3 allocs/op
|
||||
BenchmarkBeego_GithubStatic 1000000 1561 ns/op 368 B/op 7 allocs/op
|
||||
BenchmarkBone_GithubStatic 200000 12301 ns/op 2880 B/op 60 allocs/op
|
||||
BenchmarkDenco_GithubStatic 20000000 74.6 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkEcho_GithubStatic 10000000 176 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGin_GithubStatic 10000000 159 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_GithubStatic 1000000 1116 ns/op 304 B/op 6 allocs/op
|
||||
BenchmarkGoji_GithubStatic 5000000 413 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGoRestful_GithubStatic 30000 55200 ns/op 3520 B/op 36 allocs/op
|
||||
BenchmarkGoJsonRest_GithubStatic 1000000 1504 ns/op 337 B/op 12 allocs/op
|
||||
BenchmarkGorillaMux_GithubStatic 100000 23620 ns/op 464 B/op 8 allocs/op
|
||||
BenchmarkHttpRouter_GithubStatic 20000000 78.3 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkHttpTreeMux_GithubStatic 20000000 84.9 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkKocha_GithubStatic 20000000 111 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkMacaron_GithubStatic 1000000 2686 ns/op 752 B/op 8 allocs/op
|
||||
BenchmarkMartini_GithubStatic 100000 22244 ns/op 832 B/op 11 allocs/op
|
||||
BenchmarkPat_GithubStatic 100000 13278 ns/op 3648 B/op 76 allocs/op
|
||||
BenchmarkPossum_GithubStatic 1000000 1429 ns/op 480 B/op 4 allocs/op
|
||||
BenchmarkR2router_GithubStatic 2000000 726 ns/op 144 B/op 5 allocs/op
|
||||
BenchmarkRevel_GithubStatic 300000 6271 ns/op 1288 B/op 25 allocs/op
|
||||
BenchmarkRivet_GithubStatic 3000000 474 ns/op 112 B/op 2 allocs/op
|
||||
BenchmarkTango_GithubStatic 1000000 1842 ns/op 256 B/op 10 allocs/op
|
||||
BenchmarkTigerTonic_GithubStatic 5000000 361 ns/op 48 B/op 1 allocs/op
|
||||
BenchmarkTraffic_GithubStatic 30000 47197 ns/op 18920 B/op 149 allocs/op
|
||||
BenchmarkVulcan_GithubStatic 1000000 1415 ns/op 98 B/op 3 allocs/op
|
||||
BenchmarkZeus_GithubStatic 1000000 2522 ns/op 512 B/op 11 allocs/op
|
||||
BenchmarkAce_GithubParam 3000000 578 ns/op 96 B/op 1 allocs/op
|
||||
BenchmarkBear_GithubParam 1000000 1592 ns/op 464 B/op 5 allocs/op
|
||||
BenchmarkBeego_GithubParam 1000000 2891 ns/op 784 B/op 11 allocs/op
|
||||
BenchmarkBone_GithubParam 300000 6440 ns/op 1456 B/op 16 allocs/op
|
||||
BenchmarkDenco_GithubParam 3000000 514 ns/op 128 B/op 1 allocs/op
|
||||
BenchmarkEcho_GithubParam 5000000 292 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGin_GithubParam 10000000 242 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_GithubParam 1000000 2343 ns/op 720 B/op 10 allocs/op
|
||||
BenchmarkGoji_GithubParam 1000000 1566 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkGoJsonRest_GithubParam 1000000 2828 ns/op 721 B/op 15 allocs/op
|
||||
BenchmarkGoRestful_GithubParam 10000 177711 ns/op 2816 B/op 35 allocs/op
|
||||
BenchmarkGorillaMux_GithubParam 100000 13591 ns/op 816 B/op 9 allocs/op
|
||||
BenchmarkHttpRouter_GithubParam 5000000 352 ns/op 96 B/op 1 allocs/op
|
||||
BenchmarkHttpTreeMux_GithubParam 2000000 973 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkKocha_GithubParam 2000000 889 ns/op 128 B/op 5 allocs/op
|
||||
BenchmarkMacaron_GithubParam 500000 4047 ns/op 1168 B/op 12 allocs/op
|
||||
BenchmarkMartini_GithubParam 50000 28982 ns/op 1184 B/op 12 allocs/op
|
||||
BenchmarkPat_GithubParam 200000 8747 ns/op 2480 B/op 56 allocs/op
|
||||
BenchmarkPossum_GithubParam 1000000 2158 ns/op 624 B/op 7 allocs/op
|
||||
BenchmarkR2router_GithubParam 1000000 1352 ns/op 432 B/op 6 allocs/op
|
||||
BenchmarkRevel_GithubParam 200000 7673 ns/op 1784 B/op 30 allocs/op
|
||||
BenchmarkRivet_GithubParam 1000000 1573 ns/op 480 B/op 6 allocs/op
|
||||
BenchmarkTango_GithubParam 1000000 2418 ns/op 480 B/op 13 allocs/op
|
||||
BenchmarkTigerTonic_GithubParam 300000 6048 ns/op 1440 B/op 28 allocs/op
|
||||
BenchmarkTraffic_GithubParam 100000 20143 ns/op 6024 B/op 55 allocs/op
|
||||
BenchmarkVulcan_GithubParam 1000000 2224 ns/op 98 B/op 3 allocs/op
|
||||
BenchmarkZeus_GithubParam 500000 4156 ns/op 1312 B/op 12 allocs/op
|
||||
BenchmarkAce_GithubAll 10000 109482 ns/op 13792 B/op 167 allocs/op
|
||||
BenchmarkBear_GithubAll 10000 287490 ns/op 79952 B/op 943 allocs/op
|
||||
BenchmarkBeego_GithubAll 3000 562184 ns/op 146272 B/op 2092 allocs/op
|
||||
BenchmarkBone_GithubAll 500 2578716 ns/op 648016 B/op 8119 allocs/op
|
||||
BenchmarkDenco_GithubAll 20000 94955 ns/op 20224 B/op 167 allocs/op
|
||||
BenchmarkEcho_GithubAll 30000 58705 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGin_GithubAll 30000 50991 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_GithubAll 5000 449648 ns/op 133280 B/op 1889 allocs/op
|
||||
BenchmarkGoji_GithubAll 2000 689748 ns/op 56113 B/op 334 allocs/op
|
||||
BenchmarkGoJsonRest_GithubAll 5000 537769 ns/op 135995 B/op 2940 allocs/op
|
||||
BenchmarkGoRestful_GithubAll 100 18410628 ns/op 797236 B/op 7725 allocs/op
|
||||
BenchmarkGorillaMux_GithubAll 200 8036360 ns/op 153137 B/op 1791 allocs/op
|
||||
BenchmarkHttpRouter_GithubAll 20000 63506 ns/op 13792 B/op 167 allocs/op
|
||||
BenchmarkHttpTreeMux_GithubAll 10000 165927 ns/op 56112 B/op 334 allocs/op
|
||||
BenchmarkKocha_GithubAll 10000 171362 ns/op 23304 B/op 843 allocs/op
|
||||
BenchmarkMacaron_GithubAll 2000 817008 ns/op 224960 B/op 2315 allocs/op
|
||||
BenchmarkMartini_GithubAll 100 12609209 ns/op 237952 B/op 2686 allocs/op
|
||||
BenchmarkPat_GithubAll 300 4830398 ns/op 1504101 B/op 32222 allocs/op
|
||||
BenchmarkPossum_GithubAll 10000 301716 ns/op 97440 B/op 812 allocs/op
|
||||
BenchmarkR2router_GithubAll 10000 270691 ns/op 77328 B/op 1182 allocs/op
|
||||
BenchmarkRevel_GithubAll 1000 1491919 ns/op 345553 B/op 5918 allocs/op
|
||||
BenchmarkRivet_GithubAll 10000 283860 ns/op 84272 B/op 1079 allocs/op
|
||||
BenchmarkTango_GithubAll 5000 473821 ns/op 87078 B/op 2470 allocs/op
|
||||
BenchmarkTigerTonic_GithubAll 2000 1120131 ns/op 241088 B/op 6052 allocs/op
|
||||
BenchmarkTraffic_GithubAll 200 8708979 ns/op 2664762 B/op 22390 allocs/op
|
||||
BenchmarkVulcan_GithubAll 5000 353392 ns/op 19894 B/op 609 allocs/op
|
||||
BenchmarkZeus_GithubAll 2000 944234 ns/op 300688 B/op 2648 allocs/op
|
||||
BenchmarkAce_GPlusStatic 5000000 251 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkBear_GPlusStatic 3000000 415 ns/op 72 B/op 3 allocs/op
|
||||
BenchmarkBeego_GPlusStatic 1000000 1416 ns/op 352 B/op 7 allocs/op
|
||||
BenchmarkBone_GPlusStatic 10000000 192 ns/op 32 B/op 1 allocs/op
|
||||
BenchmarkDenco_GPlusStatic 30000000 47.6 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkEcho_GPlusStatic 10000000 131 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGin_GPlusStatic 10000000 131 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_GPlusStatic 1000000 1035 ns/op 288 B/op 6 allocs/op
|
||||
BenchmarkGoji_GPlusStatic 5000000 304 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGoJsonRest_GPlusStatic 1000000 1286 ns/op 337 B/op 12 allocs/op
|
||||
BenchmarkGoRestful_GPlusStatic 200000 9649 ns/op 2160 B/op 30 allocs/op
|
||||
BenchmarkGorillaMux_GPlusStatic 1000000 2346 ns/op 464 B/op 8 allocs/op
|
||||
BenchmarkHttpRouter_GPlusStatic 30000000 42.7 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkHttpTreeMux_GPlusStatic 30000000 49.5 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkKocha_GPlusStatic 20000000 74.8 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkMacaron_GPlusStatic 1000000 2520 ns/op 736 B/op 8 allocs/op
|
||||
BenchmarkMartini_GPlusStatic 300000 5310 ns/op 832 B/op 11 allocs/op
|
||||
BenchmarkPat_GPlusStatic 5000000 398 ns/op 96 B/op 2 allocs/op
|
||||
BenchmarkPossum_GPlusStatic 1000000 1434 ns/op 480 B/op 4 allocs/op
|
||||
BenchmarkR2router_GPlusStatic 2000000 646 ns/op 144 B/op 5 allocs/op
|
||||
BenchmarkRevel_GPlusStatic 300000 6172 ns/op 1272 B/op 25 allocs/op
|
||||
BenchmarkRivet_GPlusStatic 3000000 444 ns/op 112 B/op 2 allocs/op
|
||||
BenchmarkTango_GPlusStatic 1000000 1400 ns/op 208 B/op 10 allocs/op
|
||||
BenchmarkTigerTonic_GPlusStatic 10000000 213 ns/op 32 B/op 1 allocs/op
|
||||
BenchmarkTraffic_GPlusStatic 1000000 3091 ns/op 1208 B/op 16 allocs/op
|
||||
BenchmarkVulcan_GPlusStatic 2000000 863 ns/op 98 B/op 3 allocs/op
|
||||
BenchmarkZeus_GPlusStatic 10000000 237 ns/op 16 B/op 1 allocs/op
|
||||
BenchmarkAce_GPlusParam 3000000 435 ns/op 64 B/op 1 allocs/op
|
||||
BenchmarkBear_GPlusParam 1000000 1205 ns/op 448 B/op 5 allocs/op
|
||||
BenchmarkBeego_GPlusParam 1000000 2494 ns/op 720 B/op 10 allocs/op
|
||||
BenchmarkBone_GPlusParam 1000000 1126 ns/op 384 B/op 3 allocs/op
|
||||
BenchmarkDenco_GPlusParam 5000000 325 ns/op 64 B/op 1 allocs/op
|
||||
BenchmarkEcho_GPlusParam 10000000 168 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGin_GPlusParam 10000000 170 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_GPlusParam 1000000 1895 ns/op 656 B/op 9 allocs/op
|
||||
BenchmarkGoji_GPlusParam 1000000 1071 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkGoJsonRest_GPlusParam 1000000 2282 ns/op 657 B/op 14 allocs/op
|
||||
BenchmarkGoRestful_GPlusParam 100000 19400 ns/op 2560 B/op 33 allocs/op
|
||||
BenchmarkGorillaMux_GPlusParam 500000 5001 ns/op 784 B/op 9 allocs/op
|
||||
BenchmarkHttpRouter_GPlusParam 10000000 240 ns/op 64 B/op 1 allocs/op
|
||||
BenchmarkHttpTreeMux_GPlusParam 2000000 797 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkKocha_GPlusParam 3000000 505 ns/op 56 B/op 3 allocs/op
|
||||
BenchmarkMacaron_GPlusParam 1000000 3668 ns/op 1104 B/op 11 allocs/op
|
||||
BenchmarkMartini_GPlusParam 200000 10672 ns/op 1152 B/op 12 allocs/op
|
||||
BenchmarkPat_GPlusParam 1000000 2376 ns/op 704 B/op 14 allocs/op
|
||||
BenchmarkPossum_GPlusParam 1000000 2090 ns/op 624 B/op 7 allocs/op
|
||||
BenchmarkR2router_GPlusParam 1000000 1233 ns/op 432 B/op 6 allocs/op
|
||||
BenchmarkRevel_GPlusParam 200000 6778 ns/op 1704 B/op 28 allocs/op
|
||||
BenchmarkRivet_GPlusParam 1000000 1279 ns/op 464 B/op 5 allocs/op
|
||||
BenchmarkTango_GPlusParam 1000000 1981 ns/op 272 B/op 10 allocs/op
|
||||
BenchmarkTigerTonic_GPlusParam 500000 3893 ns/op 1064 B/op 19 allocs/op
|
||||
BenchmarkTraffic_GPlusParam 200000 6585 ns/op 2000 B/op 23 allocs/op
|
||||
BenchmarkVulcan_GPlusParam 1000000 1233 ns/op 98 B/op 3 allocs/op
|
||||
BenchmarkZeus_GPlusParam 1000000 1350 ns/op 368 B/op 3 allocs/op
|
||||
BenchmarkAce_GPlus2Params 3000000 512 ns/op 64 B/op 1 allocs/op
|
||||
BenchmarkBear_GPlus2Params 1000000 1564 ns/op 464 B/op 5 allocs/op
|
||||
BenchmarkBeego_GPlus2Params 1000000 3043 ns/op 784 B/op 11 allocs/op
|
||||
BenchmarkBone_GPlus2Params 1000000 3152 ns/op 736 B/op 7 allocs/op
|
||||
BenchmarkDenco_GPlus2Params 3000000 431 ns/op 64 B/op 1 allocs/op
|
||||
BenchmarkEcho_GPlus2Params 5000000 247 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGin_GPlus2Params 10000000 219 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_GPlus2Params 1000000 2363 ns/op 720 B/op 10 allocs/op
|
||||
BenchmarkGoji_GPlus2Params 1000000 1540 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkGoJsonRest_GPlus2Params 1000000 2872 ns/op 721 B/op 15 allocs/op
|
||||
BenchmarkGoRestful_GPlus2Params 100000 23030 ns/op 2720 B/op 35 allocs/op
|
||||
BenchmarkGorillaMux_GPlus2Params 200000 10516 ns/op 816 B/op 9 allocs/op
|
||||
BenchmarkHttpRouter_GPlus2Params 5000000 273 ns/op 64 B/op 1 allocs/op
|
||||
BenchmarkHttpTreeMux_GPlus2Params 2000000 939 ns/op 336 B/op 2 allocs/op
|
||||
BenchmarkKocha_GPlus2Params 2000000 844 ns/op 128 B/op 5 allocs/op
|
||||
BenchmarkMacaron_GPlus2Params 500000 3914 ns/op 1168 B/op 12 allocs/op
|
||||
BenchmarkMartini_GPlus2Params 50000 35759 ns/op 1280 B/op 16 allocs/op
|
||||
BenchmarkPat_GPlus2Params 200000 7089 ns/op 2304 B/op 41 allocs/op
|
||||
BenchmarkPossum_GPlus2Params 1000000 2093 ns/op 624 B/op 7 allocs/op
|
||||
BenchmarkR2router_GPlus2Params 1000000 1320 ns/op 432 B/op 6 allocs/op
|
||||
BenchmarkRevel_GPlus2Params 200000 7351 ns/op 1800 B/op 30 allocs/op
|
||||
BenchmarkRivet_GPlus2Params 1000000 1485 ns/op 480 B/op 6 allocs/op
|
||||
BenchmarkTango_GPlus2Params 1000000 2111 ns/op 448 B/op 12 allocs/op
|
||||
BenchmarkTigerTonic_GPlus2Params 300000 6271 ns/op 1528 B/op 28 allocs/op
|
||||
BenchmarkTraffic_GPlus2Params 100000 14886 ns/op 3312 B/op 34 allocs/op
|
||||
BenchmarkVulcan_GPlus2Params 1000000 1883 ns/op 98 B/op 3 allocs/op
|
||||
BenchmarkZeus_GPlus2Params 1000000 2686 ns/op 784 B/op 6 allocs/op
|
||||
BenchmarkAce_GPlusAll 300000 5912 ns/op 640 B/op 11 allocs/op
|
||||
BenchmarkBear_GPlusAll 100000 16448 ns/op 5072 B/op 61 allocs/op
|
||||
BenchmarkBeego_GPlusAll 50000 32916 ns/op 8976 B/op 129 allocs/op
|
||||
BenchmarkBone_GPlusAll 50000 25836 ns/op 6992 B/op 76 allocs/op
|
||||
BenchmarkDenco_GPlusAll 500000 4462 ns/op 672 B/op 11 allocs/op
|
||||
BenchmarkEcho_GPlusAll 500000 2806 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGin_GPlusAll 500000 2579 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkGocraftWeb_GPlusAll 50000 25223 ns/op 8144 B/op 116 allocs/op
|
||||
BenchmarkGoji_GPlusAll 100000 14237 ns/op 3696 B/op 22 allocs/op
|
||||
BenchmarkGoJsonRest_GPlusAll 50000 29227 ns/op 8221 B/op 183 allocs/op
|
||||
BenchmarkGoRestful_GPlusAll 10000 203144 ns/op 36064 B/op 441 allocs/op
|
||||
BenchmarkGorillaMux_GPlusAll 20000 80906 ns/op 9712 B/op 115 allocs/op
|
||||
BenchmarkHttpRouter_GPlusAll 500000 3040 ns/op 640 B/op 11 allocs/op
|
||||
BenchmarkHttpTreeMux_GPlusAll 200000 9627 ns/op 3696 B/op 22 allocs/op
|
||||
BenchmarkKocha_GPlusAll 200000 8108 ns/op 976 B/op 43 allocs/op
|
||||
BenchmarkMacaron_GPlusAll 30000 48083 ns/op 13968 B/op 142 allocs/op
|
||||
BenchmarkMartini_GPlusAll 10000 196978 ns/op 15072 B/op 178 allocs/op
|
||||
BenchmarkPat_GPlusAll 30000 58865 ns/op 16880 B/op 343 allocs/op
|
||||
BenchmarkPossum_GPlusAll 100000 19685 ns/op 6240 B/op 52 allocs/op
|
||||
BenchmarkR2router_GPlusAll 100000 16251 ns/op 5040 B/op 76 allocs/op
|
||||
BenchmarkRevel_GPlusAll 20000 93489 ns/op 21656 B/op 368 allocs/op
|
||||
BenchmarkRivet_GPlusAll 100000 16907 ns/op 5408 B/op 64 allocs/op
|
||||
```
|
||||
-191
@@ -1,191 +0,0 @@
|
||||
# CHANGELOG
|
||||
|
||||
### Gin 1.2
|
||||
|
||||
- [NEW] Switch from godeps to govendor
|
||||
- [NEW] Add support for Let's Encrypt via gin-gonic/autotls
|
||||
- [NEW] Improve README examples and add extra at examples folder
|
||||
- [NEW] Improved support with App Engine
|
||||
- [NEW] Add custom template delimiters, see #860
|
||||
- [NEW] Add Template Func Maps, see #962
|
||||
- [NEW] Add \*context.Handler(), see #928
|
||||
- [NEW] Add \*context.GetRawData()
|
||||
- [NEW] Add \*context.GetHeader() (request)
|
||||
- [NEW] Add \*context.AbortWithStatusJSON() (JSON content type)
|
||||
- [NEW] Add \*context.Keys type cast helpers
|
||||
- [NEW] Add \*context.ShouldBindWith()
|
||||
- [NEW] Add \*context.MustBindWith()
|
||||
- [NEW] Add \*engine.SetFuncMap()
|
||||
- [DEPRECATE] On next release: \*context.BindWith(), see #855
|
||||
- [FIX] Refactor render
|
||||
- [FIX] Reworked tests
|
||||
- [FIX] logger now supports cygwin
|
||||
- [FIX] Use X-Forwarded-For before X-Real-Ip
|
||||
- [FIX] time.Time binding (#904)
|
||||
|
||||
### Gin 1.1.4
|
||||
|
||||
- [NEW] Support google appengine for IsTerminal func
|
||||
|
||||
### Gin 1.1.3
|
||||
|
||||
- [FIX] Reverted Logger: skip ANSI color commands
|
||||
|
||||
### Gin 1.1
|
||||
|
||||
- [NEW] Implement QueryArray and PostArray methods
|
||||
- [NEW] Refactor GetQuery and GetPostForm
|
||||
- [NEW] Add contribution guide
|
||||
- [FIX] Corrected typos in README
|
||||
- [FIX] Removed additional Iota
|
||||
- [FIX] Changed imports to gopkg instead of github in README (#733)
|
||||
- [FIX] Logger: skip ANSI color commands if output is not a tty
|
||||
|
||||
### Gin 1.0rc2 (...)
|
||||
|
||||
- [PERFORMANCE] Fast path for writing Content-Type.
|
||||
- [PERFORMANCE] Much faster 404 routing
|
||||
- [PERFORMANCE] Allocation optimizations
|
||||
- [PERFORMANCE] Faster root tree lookup
|
||||
- [PERFORMANCE] Zero overhead, String() and JSON() rendering.
|
||||
- [PERFORMANCE] Faster ClientIP parsing
|
||||
- [PERFORMANCE] Much faster SSE implementation
|
||||
- [NEW] Benchmarks suite
|
||||
- [NEW] Bind validation can be disabled and replaced with custom validators.
|
||||
- [NEW] More flexible HTML render
|
||||
- [NEW] Multipart and PostForm bindings
|
||||
- [NEW] Adds method to return all the registered routes
|
||||
- [NEW] Context.HandlerName() returns the main handler's name
|
||||
- [NEW] Adds Error.IsType() helper
|
||||
- [FIX] Binding multipart form
|
||||
- [FIX] Integration tests
|
||||
- [FIX] Crash when binding non struct object in Context.
|
||||
- [FIX] RunTLS() implementation
|
||||
- [FIX] Logger() unit tests
|
||||
- [FIX] Adds SetHTMLTemplate() warning
|
||||
- [FIX] Context.IsAborted()
|
||||
- [FIX] More unit tests
|
||||
- [FIX] JSON, XML, HTML renders accept custom content-types
|
||||
- [FIX] gin.AbortIndex is unexported
|
||||
- [FIX] Better approach to avoid directory listing in StaticFS()
|
||||
- [FIX] Context.ClientIP() always returns the IP with trimmed spaces.
|
||||
- [FIX] Better warning when running in debug mode.
|
||||
- [FIX] Google App Engine integration. debugPrint does not use os.Stdout
|
||||
- [FIX] Fixes integer overflow in error type
|
||||
- [FIX] Error implements the json.Marshaller interface
|
||||
- [FIX] MIT license in every file
|
||||
|
||||
|
||||
### Gin 1.0rc1 (May 22, 2015)
|
||||
|
||||
- [PERFORMANCE] Zero allocation router
|
||||
- [PERFORMANCE] Faster JSON, XML and text rendering
|
||||
- [PERFORMANCE] Custom hand optimized HttpRouter for Gin
|
||||
- [PERFORMANCE] Misc code optimizations. Inlining, tail call optimizations
|
||||
- [NEW] Built-in support for golang.org/x/net/context
|
||||
- [NEW] Any(path, handler). Create a route that matches any path
|
||||
- [NEW] Refactored rendering pipeline (faster and static typeded)
|
||||
- [NEW] Refactored errors API
|
||||
- [NEW] IndentedJSON() prints pretty JSON
|
||||
- [NEW] Added gin.DefaultWriter
|
||||
- [NEW] UNIX socket support
|
||||
- [NEW] RouterGroup.BasePath is exposed
|
||||
- [NEW] JSON validation using go-validate-yourself (very powerful options)
|
||||
- [NEW] Completed suite of unit tests
|
||||
- [NEW] HTTP streaming with c.Stream()
|
||||
- [NEW] StaticFile() creates a router for serving just one file.
|
||||
- [NEW] StaticFS() has an option to disable directory listing.
|
||||
- [NEW] StaticFS() for serving static files through virtual filesystems
|
||||
- [NEW] Server-Sent Events native support
|
||||
- [NEW] WrapF() and WrapH() helpers for wrapping http.HandlerFunc and http.Handler
|
||||
- [NEW] Added LoggerWithWriter() middleware
|
||||
- [NEW] Added RecoveryWithWriter() middleware
|
||||
- [NEW] Added DefaultPostFormValue()
|
||||
- [NEW] Added DefaultFormValue()
|
||||
- [NEW] Added DefaultParamValue()
|
||||
- [FIX] BasicAuth() when using custom realm
|
||||
- [FIX] Bug when serving static files in nested routing group
|
||||
- [FIX] Redirect using built-in http.Redirect()
|
||||
- [FIX] Logger when printing the requested path
|
||||
- [FIX] Documentation typos
|
||||
- [FIX] Context.Engine renamed to Context.engine
|
||||
- [FIX] Better debugging messages
|
||||
- [FIX] ErrorLogger
|
||||
- [FIX] Debug HTTP render
|
||||
- [FIX] Refactored binding and render modules
|
||||
- [FIX] Refactored Context initialization
|
||||
- [FIX] Refactored BasicAuth()
|
||||
- [FIX] NoMethod/NoRoute handlers
|
||||
- [FIX] Hijacking http
|
||||
- [FIX] Better support for Google App Engine (using log instead of fmt)
|
||||
|
||||
|
||||
### Gin 0.6 (Mar 9, 2015)
|
||||
|
||||
- [NEW] Support multipart/form-data
|
||||
- [NEW] NoMethod handler
|
||||
- [NEW] Validate sub structures
|
||||
- [NEW] Support for HTTP Realm Auth
|
||||
- [FIX] Unsigned integers in binding
|
||||
- [FIX] Improve color logger
|
||||
|
||||
|
||||
### Gin 0.5 (Feb 7, 2015)
|
||||
|
||||
- [NEW] Content Negotiation
|
||||
- [FIX] Solved security bug that allow a client to spoof ip
|
||||
- [FIX] Fix unexported/ignored fields in binding
|
||||
|
||||
|
||||
### Gin 0.4 (Aug 21, 2014)
|
||||
|
||||
- [NEW] Development mode
|
||||
- [NEW] Unit tests
|
||||
- [NEW] Add Content.Redirect()
|
||||
- [FIX] Deferring WriteHeader()
|
||||
- [FIX] Improved documentation for model binding
|
||||
|
||||
|
||||
### Gin 0.3 (Jul 18, 2014)
|
||||
|
||||
- [PERFORMANCE] Normal log and error log are printed in the same call.
|
||||
- [PERFORMANCE] Improve performance of NoRouter()
|
||||
- [PERFORMANCE] Improve context's memory locality, reduce CPU cache faults.
|
||||
- [NEW] Flexible rendering API
|
||||
- [NEW] Add Context.File()
|
||||
- [NEW] Add shorcut RunTLS() for http.ListenAndServeTLS
|
||||
- [FIX] Rename NotFound404() to NoRoute()
|
||||
- [FIX] Errors in context are purged
|
||||
- [FIX] Adds HEAD method in Static file serving
|
||||
- [FIX] Refactors Static() file serving
|
||||
- [FIX] Using keyed initialization to fix app-engine integration
|
||||
- [FIX] Can't unmarshal JSON array, #63
|
||||
- [FIX] Renaming Context.Req to Context.Request
|
||||
- [FIX] Check application/x-www-form-urlencoded when parsing form
|
||||
|
||||
|
||||
### Gin 0.2b (Jul 08, 2014)
|
||||
- [PERFORMANCE] Using sync.Pool to allocatio/gc overhead
|
||||
- [NEW] Travis CI integration
|
||||
- [NEW] Completely new logger
|
||||
- [NEW] New API for serving static files. gin.Static()
|
||||
- [NEW] gin.H() can be serialized into XML
|
||||
- [NEW] Typed errors. Errors can be typed. Internet/external/custom.
|
||||
- [NEW] Support for Godeps
|
||||
- [NEW] Travis/Godocs badges in README
|
||||
- [NEW] New Bind() and BindWith() methods for parsing request body.
|
||||
- [NEW] Add Content.Copy()
|
||||
- [NEW] Add context.LastError()
|
||||
- [NEW] Add shorcut for OPTIONS HTTP method
|
||||
- [FIX] Tons of README fixes
|
||||
- [FIX] Header is written before body
|
||||
- [FIX] BasicAuth() and changes API a little bit
|
||||
- [FIX] Recovery() middleware only prints panics
|
||||
- [FIX] Context.Get() does not panic anymore. Use MustGet() instead.
|
||||
- [FIX] Multiple http.WriteHeader() in NotFound handlers
|
||||
- [FIX] Engine.Run() panics if http server can't be setted up
|
||||
- [FIX] Crash when route path doesn't start with '/'
|
||||
- [FIX] Do not update header when status code is negative
|
||||
- [FIX] Setting response headers before calling WriteHeader in context.String()
|
||||
- [FIX] Add MIT license
|
||||
- [FIX] Changes behaviour of ErrorLogger() and Logger()
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Manuel Martínez-Almeida
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
GOFMT ?= gofmt "-s"
|
||||
PACKAGES ?= $(shell go list ./... | grep -v /vendor/)
|
||||
GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*")
|
||||
|
||||
all: build
|
||||
|
||||
install: deps
|
||||
govendor sync
|
||||
|
||||
.PHONY: test
|
||||
test:
|
||||
go test -v -covermode=count -coverprofile=coverage.out
|
||||
|
||||
.PHONY: fmt
|
||||
fmt:
|
||||
$(GOFMT) -w $(GOFILES)
|
||||
|
||||
.PHONY: fmt-check
|
||||
fmt-check:
|
||||
# get all go files and run go fmt on them
|
||||
@diff=$$($(GOFMT) -d $(GOFILES)); \
|
||||
if [ -n "$$diff" ]; then \
|
||||
echo "Please run 'make fmt' and commit the result:"; \
|
||||
echo "$${diff}"; \
|
||||
exit 1; \
|
||||
fi;
|
||||
|
||||
vet:
|
||||
go vet $(PACKAGES)
|
||||
|
||||
deps:
|
||||
@hash govendor > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
|
||||
go get -u github.com/kardianos/govendor; \
|
||||
fi
|
||||
@hash embedmd > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
|
||||
go get -u github.com/campoy/embedmd; \
|
||||
fi
|
||||
|
||||
embedmd:
|
||||
embedmd -d *.md
|
||||
|
||||
.PHONY: lint
|
||||
lint:
|
||||
@hash golint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
|
||||
go get -u github.com/golang/lint/golint; \
|
||||
fi
|
||||
for PKG in $(PACKAGES); do golint -set_exit_status $$PKG || exit 1; done;
|
||||
|
||||
.PHONY: misspell-check
|
||||
misspell-check:
|
||||
@hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
|
||||
go get -u github.com/client9/misspell/cmd/misspell; \
|
||||
fi
|
||||
misspell -error $(GOFILES)
|
||||
|
||||
.PHONY: misspell
|
||||
misspell:
|
||||
@hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
|
||||
go get -u github.com/client9/misspell/cmd/misspell; \
|
||||
fi
|
||||
misspell -w $(GOFILES)
|
||||
-977
@@ -1,977 +0,0 @@
|
||||
# Gin Web Framework
|
||||
|
||||
<img align="right" src="https://raw.githubusercontent.com/gin-gonic/gin/master/logo.jpg">
|
||||
|
||||
[](https://travis-ci.org/gin-gonic/gin)
|
||||
[](https://codecov.io/gh/gin-gonic/gin)
|
||||
[](https://goreportcard.com/report/github.com/gin-gonic/gin)
|
||||
[](https://godoc.org/github.com/gin-gonic/gin)
|
||||
[](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin.
|
||||
|
||||

|
||||
|
||||
```sh
|
||||
$ cat test.go
|
||||
```
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
r.GET("/ping", func(c *gin.Context) {
|
||||
c.JSON(200, gin.H{
|
||||
"message": "pong",
|
||||
})
|
||||
})
|
||||
r.Run() // listen and serve on 0.0.0.0:8080
|
||||
}
|
||||
```
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter)
|
||||
|
||||
[See all benchmarks](/BENCHMARKS.md)
|
||||
|
||||
|
||||
Benchmark name | (1) | (2) | (3) | (4)
|
||||
--------------------------------|----------:|----------:|----------:|------:
|
||||
BenchmarkAce_GithubAll | 10000 | 109482 | 13792 | 167
|
||||
BenchmarkBear_GithubAll | 10000 | 287490 | 79952 | 943
|
||||
BenchmarkBeego_GithubAll | 3000 | 562184 | 146272 | 2092
|
||||
BenchmarkBone_GithubAll | 500 | 2578716 | 648016 | 8119
|
||||
BenchmarkDenco_GithubAll | 20000 | 94955 | 20224 | 167
|
||||
BenchmarkEcho_GithubAll | 30000 | 58705 | 0 | 0
|
||||
**BenchmarkGin_GithubAll** | **30000** | **50991** | **0** | **0**
|
||||
BenchmarkGocraftWeb_GithubAll | 5000 | 449648 | 133280 | 1889
|
||||
BenchmarkGoji_GithubAll | 2000 | 689748 | 56113 | 334
|
||||
BenchmarkGoJsonRest_GithubAll | 5000 | 537769 | 135995 | 2940
|
||||
BenchmarkGoRestful_GithubAll | 100 | 18410628 | 797236 | 7725
|
||||
BenchmarkGorillaMux_GithubAll | 200 | 8036360 | 153137 | 1791
|
||||
BenchmarkHttpRouter_GithubAll | 20000 | 63506 | 13792 | 167
|
||||
BenchmarkHttpTreeMux_GithubAll | 10000 | 165927 | 56112 | 334
|
||||
BenchmarkKocha_GithubAll | 10000 | 171362 | 23304 | 843
|
||||
BenchmarkMacaron_GithubAll | 2000 | 817008 | 224960 | 2315
|
||||
BenchmarkMartini_GithubAll | 100 | 12609209 | 237952 | 2686
|
||||
BenchmarkPat_GithubAll | 300 | 4830398 | 1504101 | 32222
|
||||
BenchmarkPossum_GithubAll | 10000 | 301716 | 97440 | 812
|
||||
BenchmarkR2router_GithubAll | 10000 | 270691 | 77328 | 1182
|
||||
BenchmarkRevel_GithubAll | 1000 | 1491919 | 345553 | 5918
|
||||
BenchmarkRivet_GithubAll | 10000 | 283860 | 84272 | 1079
|
||||
BenchmarkTango_GithubAll | 5000 | 473821 | 87078 | 2470
|
||||
BenchmarkTigerTonic_GithubAll | 2000 | 1120131 | 241088 | 6052
|
||||
BenchmarkTraffic_GithubAll | 200 | 8708979 | 2664762 | 22390
|
||||
BenchmarkVulcan_GithubAll | 5000 | 353392 | 19894 | 609
|
||||
BenchmarkZeus_GithubAll | 2000 | 944234 | 300688 | 2648
|
||||
|
||||
(1): Total Repetitions
|
||||
(2): Single Repetition Duration (ns/op)
|
||||
(3): Heap Memory (B/op)
|
||||
(4): Average Allocations per Repetition (allocs/op)
|
||||
|
||||
## Gin v1. stable
|
||||
|
||||
- [x] Zero allocation router.
|
||||
- [x] Still the fastest http router and framework. From routing to writing.
|
||||
- [x] Complete suite of unit tests
|
||||
- [x] Battle tested
|
||||
- [x] API frozen, new releases will not break your code.
|
||||
|
||||
|
||||
## Start using it
|
||||
|
||||
1. Download and install it:
|
||||
|
||||
```sh
|
||||
$ go get github.com/gin-gonic/gin
|
||||
```
|
||||
|
||||
2. Import it in your code:
|
||||
|
||||
```go
|
||||
import "github.com/gin-gonic/gin"
|
||||
```
|
||||
|
||||
3. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`.
|
||||
|
||||
```go
|
||||
import "net/http"
|
||||
```
|
||||
|
||||
## API Examples
|
||||
|
||||
### Using GET, POST, PUT, PATCH, DELETE and OPTIONS
|
||||
|
||||
```go
|
||||
func main() {
|
||||
// Disable Console Color
|
||||
// gin.DisableConsoleColor()
|
||||
|
||||
// Creates a gin router with default middleware:
|
||||
// logger and recovery (crash-free) middleware
|
||||
router := gin.Default()
|
||||
|
||||
router.GET("/someGet", getting)
|
||||
router.POST("/somePost", posting)
|
||||
router.PUT("/somePut", putting)
|
||||
router.DELETE("/someDelete", deleting)
|
||||
router.PATCH("/somePatch", patching)
|
||||
router.HEAD("/someHead", head)
|
||||
router.OPTIONS("/someOptions", options)
|
||||
|
||||
// By default it serves on :8080 unless a
|
||||
// PORT environment variable was defined.
|
||||
router.Run()
|
||||
// router.Run(":3000") for a hard coded port
|
||||
}
|
||||
```
|
||||
|
||||
### Parameters in path
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
|
||||
// This handler will match /user/john but will not match neither /user/ or /user
|
||||
router.GET("/user/:name", func(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
c.String(http.StatusOK, "Hello %s", name)
|
||||
})
|
||||
|
||||
// However, this one will match /user/john/ and also /user/john/send
|
||||
// If no other routers match /user/john, it will redirect to /user/john/
|
||||
router.GET("/user/:name/*action", func(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
action := c.Param("action")
|
||||
message := name + " is " + action
|
||||
c.String(http.StatusOK, message)
|
||||
})
|
||||
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### Querystring parameters
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
|
||||
// Query string parameters are parsed using the existing underlying request object.
|
||||
// The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe
|
||||
router.GET("/welcome", func(c *gin.Context) {
|
||||
firstname := c.DefaultQuery("firstname", "Guest")
|
||||
lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
|
||||
|
||||
c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
|
||||
})
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### Multipart/Urlencoded Form
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
|
||||
router.POST("/form_post", func(c *gin.Context) {
|
||||
message := c.PostForm("message")
|
||||
nick := c.DefaultPostForm("nick", "anonymous")
|
||||
|
||||
c.JSON(200, gin.H{
|
||||
"status": "posted",
|
||||
"message": message,
|
||||
"nick": nick,
|
||||
})
|
||||
})
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### Another example: query + post form
|
||||
|
||||
```
|
||||
POST /post?id=1234&page=1 HTTP/1.1
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
name=manu&message=this_is_great
|
||||
```
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
|
||||
router.POST("/post", func(c *gin.Context) {
|
||||
|
||||
id := c.Query("id")
|
||||
page := c.DefaultQuery("page", "0")
|
||||
name := c.PostForm("name")
|
||||
message := c.PostForm("message")
|
||||
|
||||
fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
|
||||
})
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
```
|
||||
id: 1234; page: 1; name: manu; message: this_is_great
|
||||
```
|
||||
|
||||
### Upload files
|
||||
|
||||
#### Single file
|
||||
|
||||
References issue [#774](https://github.com/gin-gonic/gin/issues/774) and detail [example code](examples/upload-file/single).
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
router.POST("/upload", func(c *gin.Context) {
|
||||
// single file
|
||||
file, _ := c.FormFile("file")
|
||||
log.Println(file.Filename)
|
||||
|
||||
c.String(http.StatusOK, fmt.Printf("'%s' uploaded!", file.Filename))
|
||||
})
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
How to `curl`:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8080/upload \
|
||||
-F "file=@/Users/appleboy/test.zip" \
|
||||
-H "Content-Type: multipart/form-data"
|
||||
```
|
||||
|
||||
#### Multiple files
|
||||
|
||||
See the detail [example code](examples/upload-file/multiple).
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
router.POST("/upload", func(c *gin.Context) {
|
||||
// Multipart form
|
||||
form, _ := c.MultipartForm()
|
||||
files := form.File["upload[]"]
|
||||
|
||||
for _, file := range files {
|
||||
log.Println(file.Filename)
|
||||
}
|
||||
c.String(http.StatusOK, fmt.Printf("%d files uploaded!", len(files)))
|
||||
})
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
How to `curl`:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8080/upload \
|
||||
-F "upload[]=@/Users/appleboy/test1.zip" \
|
||||
-F "upload[]=@/Users/appleboy/test2.zip" \
|
||||
-H "Content-Type: multipart/form-data"
|
||||
```
|
||||
|
||||
### Grouping routes
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
|
||||
// Simple group: v1
|
||||
v1 := router.Group("/v1")
|
||||
{
|
||||
v1.POST("/login", loginEndpoint)
|
||||
v1.POST("/submit", submitEndpoint)
|
||||
v1.POST("/read", readEndpoint)
|
||||
}
|
||||
|
||||
// Simple group: v2
|
||||
v2 := router.Group("/v2")
|
||||
{
|
||||
v2.POST("/login", loginEndpoint)
|
||||
v2.POST("/submit", submitEndpoint)
|
||||
v2.POST("/read", readEndpoint)
|
||||
}
|
||||
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### Blank Gin without middleware by default
|
||||
|
||||
Use
|
||||
|
||||
```go
|
||||
r := gin.New()
|
||||
```
|
||||
|
||||
instead of
|
||||
|
||||
```go
|
||||
r := gin.Default()
|
||||
```
|
||||
|
||||
|
||||
### Using middleware
|
||||
```go
|
||||
func main() {
|
||||
// Creates a router without any middleware by default
|
||||
r := gin.New()
|
||||
|
||||
// Global middleware
|
||||
r.Use(gin.Logger())
|
||||
r.Use(gin.Recovery())
|
||||
|
||||
// Per route middleware, you can add as many as you desire.
|
||||
r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
|
||||
|
||||
// Authorization group
|
||||
// authorized := r.Group("/", AuthRequired())
|
||||
// exactly the same as:
|
||||
authorized := r.Group("/")
|
||||
// per group middleware! in this case we use the custom created
|
||||
// AuthRequired() middleware just in the "authorized" group.
|
||||
authorized.Use(AuthRequired())
|
||||
{
|
||||
authorized.POST("/login", loginEndpoint)
|
||||
authorized.POST("/submit", submitEndpoint)
|
||||
authorized.POST("/read", readEndpoint)
|
||||
|
||||
// nested group
|
||||
testing := authorized.Group("testing")
|
||||
testing.GET("/analytics", analyticsEndpoint)
|
||||
}
|
||||
|
||||
// Listen and serve on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### Model binding and validation
|
||||
|
||||
To bind a request body into a type, use model binding. We currently support binding of JSON, XML and standard form values (foo=bar&boo=baz).
|
||||
|
||||
Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set `json:"fieldname"`.
|
||||
|
||||
When using the Bind-method, Gin tries to infer the binder depending on the Content-Type header. If you are sure what you are binding, you can use BindWith.
|
||||
|
||||
You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, the current request will fail with an error.
|
||||
|
||||
```go
|
||||
// Binding from JSON
|
||||
type Login struct {
|
||||
User string `form:"user" json:"user" binding:"required"`
|
||||
Password string `form:"password" json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
|
||||
// Example for binding JSON ({"user": "manu", "password": "123"})
|
||||
router.POST("/loginJSON", func(c *gin.Context) {
|
||||
var json Login
|
||||
if c.BindJSON(&json) == nil {
|
||||
if json.User == "manu" && json.Password == "123" {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
|
||||
} else {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Example for binding a HTML form (user=manu&password=123)
|
||||
router.POST("/loginForm", func(c *gin.Context) {
|
||||
var form Login
|
||||
// This will infer what binder to use depending on the content-type header.
|
||||
if c.Bind(&form) == nil {
|
||||
if form.User == "manu" && form.Password == "123" {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
|
||||
} else {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Listen and serve on 0.0.0.0:8080
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### Bind Query String
|
||||
|
||||
See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "log"
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
type Person struct {
|
||||
Name string `form:"name"`
|
||||
Address string `form:"address"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
route := gin.Default()
|
||||
route.GET("/testing", startPage)
|
||||
route.Run(":8085")
|
||||
}
|
||||
|
||||
func startPage(c *gin.Context) {
|
||||
var person Person
|
||||
// If `GET`, only `Form` binding engine (`query`) used.
|
||||
// If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).
|
||||
// See more at https://github.com/gin-gonic/gin/blob/develop/binding/binding.go#L45
|
||||
if c.Bind(&person) == nil {
|
||||
log.Println(person.Name)
|
||||
log.Println(person.Address)
|
||||
}
|
||||
|
||||
c.String(200, "Success")
|
||||
}
|
||||
```
|
||||
|
||||
### Multipart/Urlencoded binding
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type LoginForm struct {
|
||||
User string `form:"user" binding:"required"`
|
||||
Password string `form:"password" binding:"required"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
router.POST("/login", func(c *gin.Context) {
|
||||
// you can bind multipart form with explicit binding declaration:
|
||||
// c.MustBindWith(&form, binding.Form)
|
||||
// or you can simply use autobinding with Bind method:
|
||||
var form LoginForm
|
||||
// in this case proper binding will be automatically selected
|
||||
if c.Bind(&form) == nil {
|
||||
if form.User == "user" && form.Password == "password" {
|
||||
c.JSON(200, gin.H{"status": "you are logged in"})
|
||||
} else {
|
||||
c.JSON(401, gin.H{"status": "unauthorized"})
|
||||
}
|
||||
}
|
||||
})
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
Test it with:
|
||||
```sh
|
||||
$ curl -v --form user=user --form password=password http://localhost:8080/login
|
||||
```
|
||||
|
||||
### XML, JSON and YAML rendering
|
||||
|
||||
```go
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// gin.H is a shortcut for map[string]interface{}
|
||||
r.GET("/someJSON", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
|
||||
})
|
||||
|
||||
r.GET("/moreJSON", func(c *gin.Context) {
|
||||
// You also can use a struct
|
||||
var msg struct {
|
||||
Name string `json:"user"`
|
||||
Message string
|
||||
Number int
|
||||
}
|
||||
msg.Name = "Lena"
|
||||
msg.Message = "hey"
|
||||
msg.Number = 123
|
||||
// Note that msg.Name becomes "user" in the JSON
|
||||
// Will output : {"user": "Lena", "Message": "hey", "Number": 123}
|
||||
c.JSON(http.StatusOK, msg)
|
||||
})
|
||||
|
||||
r.GET("/someXML", func(c *gin.Context) {
|
||||
c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
|
||||
})
|
||||
|
||||
r.GET("/someYAML", func(c *gin.Context) {
|
||||
c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
|
||||
})
|
||||
|
||||
// Listen and serve on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### Serving static files
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
router.Static("/assets", "./assets")
|
||||
router.StaticFS("/more_static", http.Dir("my_file_system"))
|
||||
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
|
||||
|
||||
// Listen and serve on 0.0.0.0:8080
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### HTML rendering
|
||||
|
||||
Using LoadHTMLGlob() or LoadHTMLFiles()
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
router.LoadHTMLGlob("templates/*")
|
||||
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
|
||||
router.GET("/index", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "index.tmpl", gin.H{
|
||||
"title": "Main website",
|
||||
})
|
||||
})
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
templates/index.tmpl
|
||||
|
||||
```html
|
||||
<html>
|
||||
<h1>
|
||||
{{ .title }}
|
||||
</h1>
|
||||
</html>
|
||||
```
|
||||
|
||||
Using templates with same name in different directories
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
router.LoadHTMLGlob("templates/**/*")
|
||||
router.GET("/posts/index", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
|
||||
"title": "Posts",
|
||||
})
|
||||
})
|
||||
router.GET("/users/index", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
|
||||
"title": "Users",
|
||||
})
|
||||
})
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
templates/posts/index.tmpl
|
||||
|
||||
```html
|
||||
{{ define "posts/index.tmpl" }}
|
||||
<html><h1>
|
||||
{{ .title }}
|
||||
</h1>
|
||||
<p>Using posts/index.tmpl</p>
|
||||
</html>
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
templates/users/index.tmpl
|
||||
|
||||
```html
|
||||
{{ define "users/index.tmpl" }}
|
||||
<html><h1>
|
||||
{{ .title }}
|
||||
</h1>
|
||||
<p>Using users/index.tmpl</p>
|
||||
</html>
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
You can also use your own html template render
|
||||
|
||||
```go
|
||||
import "html/template"
|
||||
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
html := template.Must(template.ParseFiles("file1", "file2"))
|
||||
router.SetHTMLTemplate(html)
|
||||
router.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
You may use custom delims
|
||||
|
||||
```go
|
||||
r := gin.Default()
|
||||
r.Delims("{[{", "}]}")
|
||||
r.LoadHTMLGlob("/path/to/templates"))
|
||||
```
|
||||
|
||||
#### Add custom template funcs
|
||||
|
||||
main.go
|
||||
|
||||
```go
|
||||
...
|
||||
|
||||
func formatAsDate(t time.Time) string {
|
||||
year, month, day := t.Date()
|
||||
return fmt.Sprintf("%d/%02d/%02d", year, month, day)
|
||||
}
|
||||
|
||||
...
|
||||
|
||||
router.SetFuncMap(template.FuncMap{
|
||||
"formatAsDate": formatAsDate,
|
||||
})
|
||||
|
||||
...
|
||||
|
||||
router.GET("/raw", func(c *Context) {
|
||||
c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
|
||||
"now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
|
||||
})
|
||||
})
|
||||
|
||||
...
|
||||
```
|
||||
|
||||
raw.tmpl
|
||||
|
||||
```html
|
||||
Date: {[{.now | formatAsDate}]}
|
||||
```
|
||||
|
||||
Result:
|
||||
```
|
||||
Date: 2017/07/01
|
||||
```
|
||||
|
||||
### Multitemplate
|
||||
|
||||
Gin allow by default use only one html.Template. Check [a multitemplate render](https://github.com/gin-contrib/multitemplate) for using features like go 1.6 `block template`.
|
||||
|
||||
### Redirects
|
||||
|
||||
Issuing a HTTP redirect is easy:
|
||||
|
||||
```go
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
|
||||
})
|
||||
```
|
||||
Both internal and external locations are supported.
|
||||
|
||||
|
||||
### Custom Middleware
|
||||
|
||||
```go
|
||||
func Logger() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
t := time.Now()
|
||||
|
||||
// Set example variable
|
||||
c.Set("example", "12345")
|
||||
|
||||
// before request
|
||||
|
||||
c.Next()
|
||||
|
||||
// after request
|
||||
latency := time.Since(t)
|
||||
log.Print(latency)
|
||||
|
||||
// access the status we are sending
|
||||
status := c.Writer.Status()
|
||||
log.Println(status)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
r := gin.New()
|
||||
r.Use(Logger())
|
||||
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
example := c.MustGet("example").(string)
|
||||
|
||||
// it would print: "12345"
|
||||
log.Println(example)
|
||||
})
|
||||
|
||||
// Listen and serve on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### Using BasicAuth() middleware
|
||||
|
||||
```go
|
||||
// simulate some private data
|
||||
var secrets = gin.H{
|
||||
"foo": gin.H{"email": "foo@bar.com", "phone": "123433"},
|
||||
"austin": gin.H{"email": "austin@example.com", "phone": "666"},
|
||||
"lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},
|
||||
}
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// Group using gin.BasicAuth() middleware
|
||||
// gin.Accounts is a shortcut for map[string]string
|
||||
authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
|
||||
"foo": "bar",
|
||||
"austin": "1234",
|
||||
"lena": "hello2",
|
||||
"manu": "4321",
|
||||
}))
|
||||
|
||||
// /admin/secrets endpoint
|
||||
// hit "localhost:8080/admin/secrets
|
||||
authorized.GET("/secrets", func(c *gin.Context) {
|
||||
// get user, it was set by the BasicAuth middleware
|
||||
user := c.MustGet(gin.AuthUserKey).(string)
|
||||
if secret, ok := secrets[user]; ok {
|
||||
c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
|
||||
} else {
|
||||
c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
|
||||
}
|
||||
})
|
||||
|
||||
// Listen and serve on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### Goroutines inside a middleware
|
||||
|
||||
When starting inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy.
|
||||
|
||||
```go
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
r.GET("/long_async", func(c *gin.Context) {
|
||||
// create copy to be used inside the goroutine
|
||||
cCp := c.Copy()
|
||||
go func() {
|
||||
// simulate a long task with time.Sleep(). 5 seconds
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// note that you are using the copied context "cCp", IMPORTANT
|
||||
log.Println("Done! in path " + cCp.Request.URL.Path)
|
||||
}()
|
||||
})
|
||||
|
||||
r.GET("/long_sync", func(c *gin.Context) {
|
||||
// simulate a long task with time.Sleep(). 5 seconds
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// since we are NOT using a goroutine, we do not have to copy the context
|
||||
log.Println("Done! in path " + c.Request.URL.Path)
|
||||
})
|
||||
|
||||
// Listen and serve on 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
### Custom HTTP configuration
|
||||
|
||||
Use `http.ListenAndServe()` directly, like this:
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
http.ListenAndServe(":8080", router)
|
||||
}
|
||||
```
|
||||
or
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
|
||||
s := &http.Server{
|
||||
Addr: ":8080",
|
||||
Handler: router,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20,
|
||||
}
|
||||
s.ListenAndServe()
|
||||
}
|
||||
```
|
||||
|
||||
### Support Let's Encrypt
|
||||
|
||||
example for 1-line LetsEncrypt HTTPS servers.
|
||||
|
||||
[embedmd]:# (examples/auto-tls/example1.go go)
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/gin-gonic/autotls"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// Ping handler
|
||||
r.GET("/ping", func(c *gin.Context) {
|
||||
c.String(200, "pong")
|
||||
})
|
||||
|
||||
log.Fatal(autotls.Run(r, "example1.com", "example2.com"))
|
||||
}
|
||||
```
|
||||
|
||||
example for custom autocert manager.
|
||||
|
||||
[embedmd]:# (examples/auto-tls/example2.go go)
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/gin-gonic/autotls"
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/acme/autocert"
|
||||
)
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// Ping handler
|
||||
r.GET("/ping", func(c *gin.Context) {
|
||||
c.String(200, "pong")
|
||||
})
|
||||
|
||||
m := autocert.Manager{
|
||||
Prompt: autocert.AcceptTOS,
|
||||
HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),
|
||||
Cache: autocert.DirCache("/var/www/.cache"),
|
||||
}
|
||||
|
||||
log.Fatal(autotls.RunWithManager(r, m))
|
||||
}
|
||||
```
|
||||
|
||||
### Graceful restart or stop
|
||||
|
||||
Do you want to graceful restart or stop your web server?
|
||||
There are some ways this can be done.
|
||||
|
||||
We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details.
|
||||
|
||||
```go
|
||||
router := gin.Default()
|
||||
router.GET("/", handler)
|
||||
// [...]
|
||||
endless.ListenAndServe(":4242", router)
|
||||
```
|
||||
|
||||
An alternative to endless:
|
||||
|
||||
* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.
|
||||
* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server.
|
||||
* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers.
|
||||
|
||||
If you are using Go 1.8, you may not need to use this library! Consider using http.Server's built-in [Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown) method for graceful shutdowns. See the full [graceful-shutdown](./examples/graceful-shutdown) example with gin.
|
||||
|
||||
[embedmd]:# (examples/graceful-shutdown/graceful-shutdown/server.go go)
|
||||
```go
|
||||
// +build go1.8
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
time.Sleep(5 * time.Second)
|
||||
c.String(http.StatusOK, "Welcome Gin Server")
|
||||
})
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: ":8080",
|
||||
Handler: router,
|
||||
}
|
||||
|
||||
go func() {
|
||||
// service connections
|
||||
if err := srv.ListenAndServe(); err != nil {
|
||||
log.Printf("listen: %s\n", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for interrupt signal to gracefully shutdown the server with
|
||||
// a timeout of 5 seconds.
|
||||
quit := make(chan os.Signal)
|
||||
signal.Notify(quit, os.Interrupt)
|
||||
<-quit
|
||||
log.Println("Shutdown Server ...")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
log.Fatal("Server Shutdown:", err)
|
||||
}
|
||||
log.Println("Server exist")
|
||||
}
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
- With issues:
|
||||
- Use the search tool before opening a new issue.
|
||||
- Please provide source code and commit sha if you found a bug.
|
||||
- Review existing issues and provide feedback or react to them.
|
||||
- With pull requests:
|
||||
- Open your pull request against develop
|
||||
- Your pull request should have no more than two commits, if not you should squash them.
|
||||
- It should pass all tests in the available continuous integrations systems such as TravisCI.
|
||||
- You should add/modify tests to cover your proposed code changes.
|
||||
- If your pull request contains a new feature, please document it on the README.
|
||||
|
||||
## Users
|
||||
|
||||
Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework.
|
||||
|
||||
* [drone](https://github.com/drone/drone): Drone is a Continuous Delivery platform built on Docker, written in Go
|
||||
* [gorush](https://github.com/appleboy/gorush): A push notification server written in Go.
|
||||
-92
@@ -1,92 +0,0 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
const AuthUserKey = "user"
|
||||
|
||||
type (
|
||||
Accounts map[string]string
|
||||
authPair struct {
|
||||
Value string
|
||||
User string
|
||||
}
|
||||
authPairs []authPair
|
||||
)
|
||||
|
||||
func (a authPairs) searchCredential(authValue string) (string, bool) {
|
||||
if len(authValue) == 0 {
|
||||
return "", false
|
||||
}
|
||||
for _, pair := range a {
|
||||
if pair.Value == authValue {
|
||||
return pair.User, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where
|
||||
// the key is the user name and the value is the password, as well as the name of the Realm.
|
||||
// If the realm is empty, "Authorization Required" will be used by default.
|
||||
// (see http://tools.ietf.org/html/rfc2617#section-1.2)
|
||||
func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
|
||||
if realm == "" {
|
||||
realm = "Authorization Required"
|
||||
}
|
||||
realm = "Basic realm=" + strconv.Quote(realm)
|
||||
pairs := processAccounts(accounts)
|
||||
return func(c *Context) {
|
||||
// Search user in the slice of allowed credentials
|
||||
user, found := pairs.searchCredential(c.Request.Header.Get("Authorization"))
|
||||
if !found {
|
||||
// Credentials doesn't match, we return 401 and abort handlers chain.
|
||||
c.Header("WWW-Authenticate", realm)
|
||||
c.AbortWithStatus(401)
|
||||
} else {
|
||||
// The user credentials was found, set user's id to key AuthUserKey in this context, the userId can be read later using
|
||||
// c.MustGet(gin.AuthUserKey)
|
||||
c.Set(AuthUserKey, user)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where
|
||||
// the key is the user name and the value is the password.
|
||||
func BasicAuth(accounts Accounts) HandlerFunc {
|
||||
return BasicAuthForRealm(accounts, "")
|
||||
}
|
||||
|
||||
func processAccounts(accounts Accounts) authPairs {
|
||||
assert1(len(accounts) > 0, "Empty list of authorized credentials")
|
||||
pairs := make(authPairs, 0, len(accounts))
|
||||
for user, password := range accounts {
|
||||
assert1(len(user) > 0, "User can not be empty")
|
||||
value := authorizationHeader(user, password)
|
||||
pairs = append(pairs, authPair{
|
||||
Value: value,
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
return pairs
|
||||
}
|
||||
|
||||
func authorizationHeader(user, password string) string {
|
||||
base := user + ":" + password
|
||||
return "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
|
||||
}
|
||||
|
||||
func secureCompare(given, actual string) bool {
|
||||
if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
|
||||
return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
|
||||
}
|
||||
/* Securely compare actual to itself to keep constant time, but always return false */
|
||||
return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
|
||||
}
|
||||
-146
@@ -1,146 +0,0 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestBasicAuth(t *testing.T) {
|
||||
pairs := processAccounts(Accounts{
|
||||
"admin": "password",
|
||||
"foo": "bar",
|
||||
"bar": "foo",
|
||||
})
|
||||
|
||||
assert.Len(t, pairs, 3)
|
||||
assert.Contains(t, pairs, authPair{
|
||||
User: "bar",
|
||||
Value: "Basic YmFyOmZvbw==",
|
||||
})
|
||||
assert.Contains(t, pairs, authPair{
|
||||
User: "foo",
|
||||
Value: "Basic Zm9vOmJhcg==",
|
||||
})
|
||||
assert.Contains(t, pairs, authPair{
|
||||
User: "admin",
|
||||
Value: "Basic YWRtaW46cGFzc3dvcmQ=",
|
||||
})
|
||||
}
|
||||
|
||||
func TestBasicAuthFails(t *testing.T) {
|
||||
assert.Panics(t, func() { processAccounts(nil) })
|
||||
assert.Panics(t, func() {
|
||||
processAccounts(Accounts{
|
||||
"": "password",
|
||||
"foo": "bar",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestBasicAuthSearchCredential(t *testing.T) {
|
||||
pairs := processAccounts(Accounts{
|
||||
"admin": "password",
|
||||
"foo": "bar",
|
||||
"bar": "foo",
|
||||
})
|
||||
|
||||
user, found := pairs.searchCredential(authorizationHeader("admin", "password"))
|
||||
assert.Equal(t, user, "admin")
|
||||
assert.True(t, found)
|
||||
|
||||
user, found = pairs.searchCredential(authorizationHeader("foo", "bar"))
|
||||
assert.Equal(t, user, "foo")
|
||||
assert.True(t, found)
|
||||
|
||||
user, found = pairs.searchCredential(authorizationHeader("bar", "foo"))
|
||||
assert.Equal(t, user, "bar")
|
||||
assert.True(t, found)
|
||||
|
||||
user, found = pairs.searchCredential(authorizationHeader("admins", "password"))
|
||||
assert.Empty(t, user)
|
||||
assert.False(t, found)
|
||||
|
||||
user, found = pairs.searchCredential(authorizationHeader("foo", "bar "))
|
||||
assert.Empty(t, user)
|
||||
assert.False(t, found)
|
||||
|
||||
user, found = pairs.searchCredential("")
|
||||
assert.Empty(t, user)
|
||||
assert.False(t, found)
|
||||
}
|
||||
|
||||
func TestBasicAuthAuthorizationHeader(t *testing.T) {
|
||||
assert.Equal(t, authorizationHeader("admin", "password"), "Basic YWRtaW46cGFzc3dvcmQ=")
|
||||
}
|
||||
|
||||
func TestBasicAuthSecureCompare(t *testing.T) {
|
||||
assert.True(t, secureCompare("1234567890", "1234567890"))
|
||||
assert.False(t, secureCompare("123456789", "1234567890"))
|
||||
assert.False(t, secureCompare("12345678900", "1234567890"))
|
||||
assert.False(t, secureCompare("1234567891", "1234567890"))
|
||||
}
|
||||
|
||||
func TestBasicAuthSucceed(t *testing.T) {
|
||||
accounts := Accounts{"admin": "password"}
|
||||
router := New()
|
||||
router.Use(BasicAuth(accounts))
|
||||
router.GET("/login", func(c *Context) {
|
||||
c.String(200, c.MustGet(AuthUserKey).(string))
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", "/login", nil)
|
||||
req.Header.Set("Authorization", authorizationHeader("admin", "password"))
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "admin")
|
||||
}
|
||||
|
||||
func TestBasicAuth401(t *testing.T) {
|
||||
called := false
|
||||
accounts := Accounts{"foo": "bar"}
|
||||
router := New()
|
||||
router.Use(BasicAuth(accounts))
|
||||
router.GET("/login", func(c *Context) {
|
||||
called = true
|
||||
c.String(200, c.MustGet(AuthUserKey).(string))
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", "/login", nil)
|
||||
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
assert.False(t, called)
|
||||
assert.Equal(t, w.Code, 401)
|
||||
assert.Equal(t, w.HeaderMap.Get("WWW-Authenticate"), "Basic realm=\"Authorization Required\"")
|
||||
}
|
||||
|
||||
func TestBasicAuth401WithCustomRealm(t *testing.T) {
|
||||
called := false
|
||||
accounts := Accounts{"foo": "bar"}
|
||||
router := New()
|
||||
router.Use(BasicAuthForRealm(accounts, "My Custom \"Realm\""))
|
||||
router.GET("/login", func(c *Context) {
|
||||
called = true
|
||||
c.String(200, c.MustGet(AuthUserKey).(string))
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", "/login", nil)
|
||||
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
assert.False(t, called)
|
||||
assert.Equal(t, w.Code, 401)
|
||||
assert.Equal(t, w.HeaderMap.Get("WWW-Authenticate"), "Basic realm=\"My Custom \\\"Realm\\\"\"")
|
||||
}
|
||||
-162
@@ -1,162 +0,0 @@
|
||||
// Copyright 2017 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func BenchmarkOneRoute(B *testing.B) {
|
||||
router := New()
|
||||
router.GET("/ping", func(c *Context) {})
|
||||
runRequest(B, router, "GET", "/ping")
|
||||
}
|
||||
|
||||
func BenchmarkRecoveryMiddleware(B *testing.B) {
|
||||
router := New()
|
||||
router.Use(Recovery())
|
||||
router.GET("/", func(c *Context) {})
|
||||
runRequest(B, router, "GET", "/")
|
||||
}
|
||||
|
||||
func BenchmarkLoggerMiddleware(B *testing.B) {
|
||||
router := New()
|
||||
router.Use(LoggerWithWriter(newMockWriter()))
|
||||
router.GET("/", func(c *Context) {})
|
||||
runRequest(B, router, "GET", "/")
|
||||
}
|
||||
|
||||
func BenchmarkManyHandlers(B *testing.B) {
|
||||
router := New()
|
||||
router.Use(Recovery(), LoggerWithWriter(newMockWriter()))
|
||||
router.Use(func(c *Context) {})
|
||||
router.Use(func(c *Context) {})
|
||||
router.GET("/ping", func(c *Context) {})
|
||||
runRequest(B, router, "GET", "/ping")
|
||||
}
|
||||
|
||||
func Benchmark5Params(B *testing.B) {
|
||||
DefaultWriter = os.Stdout
|
||||
router := New()
|
||||
router.Use(func(c *Context) {})
|
||||
router.GET("/param/:param1/:params2/:param3/:param4/:param5", func(c *Context) {})
|
||||
runRequest(B, router, "GET", "/param/path/to/parameter/john/12345")
|
||||
}
|
||||
|
||||
func BenchmarkOneRouteJSON(B *testing.B) {
|
||||
router := New()
|
||||
data := struct {
|
||||
Status string `json:"status"`
|
||||
}{"ok"}
|
||||
router.GET("/json", func(c *Context) {
|
||||
c.JSON(200, data)
|
||||
})
|
||||
runRequest(B, router, "GET", "/json")
|
||||
}
|
||||
|
||||
var htmlContentType = []string{"text/html; charset=utf-8"}
|
||||
|
||||
func BenchmarkOneRouteHTML(B *testing.B) {
|
||||
router := New()
|
||||
t := template.Must(template.New("index").Parse(`
|
||||
<html><body><h1>{{.}}</h1></body></html>`))
|
||||
router.SetHTMLTemplate(t)
|
||||
|
||||
router.GET("/html", func(c *Context) {
|
||||
c.HTML(200, "index", "hola")
|
||||
})
|
||||
runRequest(B, router, "GET", "/html")
|
||||
}
|
||||
|
||||
func BenchmarkOneRouteSet(B *testing.B) {
|
||||
router := New()
|
||||
router.GET("/ping", func(c *Context) {
|
||||
c.Set("key", "value")
|
||||
})
|
||||
runRequest(B, router, "GET", "/ping")
|
||||
}
|
||||
|
||||
func BenchmarkOneRouteString(B *testing.B) {
|
||||
router := New()
|
||||
router.GET("/text", func(c *Context) {
|
||||
c.String(200, "this is a plain text")
|
||||
})
|
||||
runRequest(B, router, "GET", "/text")
|
||||
}
|
||||
|
||||
func BenchmarkManyRoutesFist(B *testing.B) {
|
||||
router := New()
|
||||
router.Any("/ping", func(c *Context) {})
|
||||
runRequest(B, router, "GET", "/ping")
|
||||
}
|
||||
|
||||
func BenchmarkManyRoutesLast(B *testing.B) {
|
||||
router := New()
|
||||
router.Any("/ping", func(c *Context) {})
|
||||
runRequest(B, router, "OPTIONS", "/ping")
|
||||
}
|
||||
|
||||
func Benchmark404(B *testing.B) {
|
||||
router := New()
|
||||
router.Any("/something", func(c *Context) {})
|
||||
router.NoRoute(func(c *Context) {})
|
||||
runRequest(B, router, "GET", "/ping")
|
||||
}
|
||||
|
||||
func Benchmark404Many(B *testing.B) {
|
||||
router := New()
|
||||
router.GET("/", func(c *Context) {})
|
||||
router.GET("/path/to/something", func(c *Context) {})
|
||||
router.GET("/post/:id", func(c *Context) {})
|
||||
router.GET("/view/:id", func(c *Context) {})
|
||||
router.GET("/favicon.ico", func(c *Context) {})
|
||||
router.GET("/robots.txt", func(c *Context) {})
|
||||
router.GET("/delete/:id", func(c *Context) {})
|
||||
router.GET("/user/:id/:mode", func(c *Context) {})
|
||||
|
||||
router.NoRoute(func(c *Context) {})
|
||||
runRequest(B, router, "GET", "/viewfake")
|
||||
}
|
||||
|
||||
type mockWriter struct {
|
||||
headers http.Header
|
||||
}
|
||||
|
||||
func newMockWriter() *mockWriter {
|
||||
return &mockWriter{
|
||||
http.Header{},
|
||||
}
|
||||
}
|
||||
|
||||
func (m *mockWriter) Header() (h http.Header) {
|
||||
return m.headers
|
||||
}
|
||||
|
||||
func (m *mockWriter) Write(p []byte) (n int, err error) {
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (m *mockWriter) WriteString(s string) (n int, err error) {
|
||||
return len(s), nil
|
||||
}
|
||||
|
||||
func (m *mockWriter) WriteHeader(int) {}
|
||||
|
||||
func runRequest(B *testing.B, r *Engine, method, path string) {
|
||||
// create fake request
|
||||
req, err := http.NewRequest(method, path, nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
w := newMockWriter()
|
||||
B.ReportAllocs()
|
||||
B.ResetTimer()
|
||||
for i := 0; i < B.N; i++ {
|
||||
r.ServeHTTP(w, req)
|
||||
}
|
||||
}
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package binding
|
||||
|
||||
import "net/http"
|
||||
|
||||
const (
|
||||
MIMEJSON = "application/json"
|
||||
MIMEHTML = "text/html"
|
||||
MIMEXML = "application/xml"
|
||||
MIMEXML2 = "text/xml"
|
||||
MIMEPlain = "text/plain"
|
||||
MIMEPOSTForm = "application/x-www-form-urlencoded"
|
||||
MIMEMultipartPOSTForm = "multipart/form-data"
|
||||
MIMEPROTOBUF = "application/x-protobuf"
|
||||
MIMEMSGPACK = "application/x-msgpack"
|
||||
MIMEMSGPACK2 = "application/msgpack"
|
||||
)
|
||||
|
||||
type Binding interface {
|
||||
Name() string
|
||||
Bind(*http.Request, interface{}) error
|
||||
}
|
||||
|
||||
type StructValidator interface {
|
||||
// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
|
||||
// If the received type is not a struct, any validation should be skipped and nil must be returned.
|
||||
// If the received type is a struct or pointer to a struct, the validation should be performed.
|
||||
// If the struct is not valid or the validation itself fails, a descriptive error should be returned.
|
||||
// Otherwise nil must be returned.
|
||||
ValidateStruct(interface{}) error
|
||||
}
|
||||
|
||||
var Validator StructValidator = &defaultValidator{}
|
||||
|
||||
var (
|
||||
JSON = jsonBinding{}
|
||||
XML = xmlBinding{}
|
||||
Form = formBinding{}
|
||||
FormPost = formPostBinding{}
|
||||
FormMultipart = formMultipartBinding{}
|
||||
ProtoBuf = protobufBinding{}
|
||||
MsgPack = msgpackBinding{}
|
||||
)
|
||||
|
||||
func Default(method, contentType string) Binding {
|
||||
if method == "GET" {
|
||||
return Form
|
||||
}
|
||||
|
||||
switch contentType {
|
||||
case MIMEJSON:
|
||||
return JSON
|
||||
case MIMEXML, MIMEXML2:
|
||||
return XML
|
||||
case MIMEPROTOBUF:
|
||||
return ProtoBuf
|
||||
case MIMEMSGPACK, MIMEMSGPACK2:
|
||||
return MsgPack
|
||||
default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:
|
||||
return Form
|
||||
}
|
||||
}
|
||||
|
||||
func validate(obj interface{}) error {
|
||||
if Validator == nil {
|
||||
return nil
|
||||
}
|
||||
return Validator.ValidateStruct(obj)
|
||||
}
|
||||
-259
@@ -1,259 +0,0 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package binding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin/binding/example"
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/ugorji/go/codec"
|
||||
)
|
||||
|
||||
type FooStruct struct {
|
||||
Foo string `msgpack:"foo" json:"foo" form:"foo" xml:"foo" binding:"required"`
|
||||
}
|
||||
|
||||
type FooBarStruct struct {
|
||||
FooStruct
|
||||
Bar string `msgpack:"bar" json:"bar" form:"bar" xml:"bar" binding:"required"`
|
||||
}
|
||||
|
||||
func TestBindingDefault(t *testing.T) {
|
||||
assert.Equal(t, Default("GET", ""), Form)
|
||||
assert.Equal(t, Default("GET", MIMEJSON), Form)
|
||||
|
||||
assert.Equal(t, Default("POST", MIMEJSON), JSON)
|
||||
assert.Equal(t, Default("PUT", MIMEJSON), JSON)
|
||||
|
||||
assert.Equal(t, Default("POST", MIMEXML), XML)
|
||||
assert.Equal(t, Default("PUT", MIMEXML2), XML)
|
||||
|
||||
assert.Equal(t, Default("POST", MIMEPOSTForm), Form)
|
||||
assert.Equal(t, Default("PUT", MIMEPOSTForm), Form)
|
||||
|
||||
assert.Equal(t, Default("POST", MIMEMultipartPOSTForm), Form)
|
||||
assert.Equal(t, Default("PUT", MIMEMultipartPOSTForm), Form)
|
||||
|
||||
assert.Equal(t, Default("POST", MIMEPROTOBUF), ProtoBuf)
|
||||
assert.Equal(t, Default("PUT", MIMEPROTOBUF), ProtoBuf)
|
||||
|
||||
assert.Equal(t, Default("POST", MIMEMSGPACK), MsgPack)
|
||||
assert.Equal(t, Default("PUT", MIMEMSGPACK2), MsgPack)
|
||||
}
|
||||
|
||||
func TestBindingJSON(t *testing.T) {
|
||||
testBodyBinding(t,
|
||||
JSON, "json",
|
||||
"/", "/",
|
||||
`{"foo": "bar"}`, `{"bar": "foo"}`)
|
||||
}
|
||||
|
||||
func TestBindingForm(t *testing.T) {
|
||||
testFormBinding(t, "POST",
|
||||
"/", "/",
|
||||
"foo=bar&bar=foo", "bar2=foo")
|
||||
}
|
||||
|
||||
func TestBindingForm2(t *testing.T) {
|
||||
testFormBinding(t, "GET",
|
||||
"/?foo=bar&bar=foo", "/?bar2=foo",
|
||||
"", "")
|
||||
}
|
||||
|
||||
func TestBindingXML(t *testing.T) {
|
||||
testBodyBinding(t,
|
||||
XML, "xml",
|
||||
"/", "/",
|
||||
"<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")
|
||||
}
|
||||
|
||||
func createFormPostRequest() *http.Request {
|
||||
req, _ := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar&bar=foo"))
|
||||
req.Header.Set("Content-Type", MIMEPOSTForm)
|
||||
return req
|
||||
}
|
||||
|
||||
func createFormMultipartRequest() *http.Request {
|
||||
boundary := "--testboundary"
|
||||
body := new(bytes.Buffer)
|
||||
mw := multipart.NewWriter(body)
|
||||
defer mw.Close()
|
||||
|
||||
mw.SetBoundary(boundary)
|
||||
mw.WriteField("foo", "bar")
|
||||
mw.WriteField("bar", "foo")
|
||||
req, _ := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)
|
||||
req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
|
||||
return req
|
||||
}
|
||||
|
||||
func TestBindingFormPost(t *testing.T) {
|
||||
req := createFormPostRequest()
|
||||
var obj FooBarStruct
|
||||
FormPost.Bind(req, &obj)
|
||||
|
||||
assert.Equal(t, obj.Foo, "bar")
|
||||
assert.Equal(t, obj.Bar, "foo")
|
||||
}
|
||||
|
||||
func TestBindingFormMultipart(t *testing.T) {
|
||||
req := createFormMultipartRequest()
|
||||
var obj FooBarStruct
|
||||
FormMultipart.Bind(req, &obj)
|
||||
|
||||
assert.Equal(t, obj.Foo, "bar")
|
||||
assert.Equal(t, obj.Bar, "foo")
|
||||
}
|
||||
|
||||
func TestBindingProtoBuf(t *testing.T) {
|
||||
test := &example.Test{
|
||||
Label: proto.String("yes"),
|
||||
}
|
||||
data, _ := proto.Marshal(test)
|
||||
|
||||
testProtoBodyBinding(t,
|
||||
ProtoBuf, "protobuf",
|
||||
"/", "/",
|
||||
string(data), string(data[1:]))
|
||||
}
|
||||
|
||||
func TestBindingMsgPack(t *testing.T) {
|
||||
test := FooStruct{
|
||||
Foo: "bar",
|
||||
}
|
||||
|
||||
h := new(codec.MsgpackHandle)
|
||||
assert.NotNil(t, h)
|
||||
buf := bytes.NewBuffer([]byte{})
|
||||
assert.NotNil(t, buf)
|
||||
err := codec.NewEncoder(buf, h).Encode(test)
|
||||
assert.NoError(t, err)
|
||||
|
||||
data := buf.Bytes()
|
||||
|
||||
testMsgPackBodyBinding(t,
|
||||
MsgPack, "msgpack",
|
||||
"/", "/",
|
||||
string(data), string(data[1:]))
|
||||
}
|
||||
|
||||
func TestValidationFails(t *testing.T) {
|
||||
var obj FooStruct
|
||||
req := requestWithBody("POST", "/", `{"bar": "foo"}`)
|
||||
err := JSON.Bind(req, &obj)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestValidationDisabled(t *testing.T) {
|
||||
backup := Validator
|
||||
Validator = nil
|
||||
defer func() { Validator = backup }()
|
||||
|
||||
var obj FooStruct
|
||||
req := requestWithBody("POST", "/", `{"bar": "foo"}`)
|
||||
err := JSON.Bind(req, &obj)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestExistsSucceeds(t *testing.T) {
|
||||
type HogeStruct struct {
|
||||
Hoge *int `json:"hoge" binding:"exists"`
|
||||
}
|
||||
|
||||
var obj HogeStruct
|
||||
req := requestWithBody("POST", "/", `{"hoge": 0}`)
|
||||
err := JSON.Bind(req, &obj)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestExistsFails(t *testing.T) {
|
||||
type HogeStruct struct {
|
||||
Hoge *int `json:"foo" binding:"exists"`
|
||||
}
|
||||
|
||||
var obj HogeStruct
|
||||
req := requestWithBody("POST", "/", `{"boen": 0}`)
|
||||
err := JSON.Bind(req, &obj)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func testFormBinding(t *testing.T, method, path, badPath, body, badBody string) {
|
||||
b := Form
|
||||
assert.Equal(t, b.Name(), "form")
|
||||
|
||||
obj := FooBarStruct{}
|
||||
req := requestWithBody(method, path, body)
|
||||
if method == "POST" {
|
||||
req.Header.Add("Content-Type", MIMEPOSTForm)
|
||||
}
|
||||
err := b.Bind(req, &obj)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, obj.Foo, "bar")
|
||||
assert.Equal(t, obj.Bar, "foo")
|
||||
|
||||
obj = FooBarStruct{}
|
||||
req = requestWithBody(method, badPath, badBody)
|
||||
err = JSON.Bind(req, &obj)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
|
||||
assert.Equal(t, b.Name(), name)
|
||||
|
||||
obj := FooStruct{}
|
||||
req := requestWithBody("POST", path, body)
|
||||
err := b.Bind(req, &obj)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, obj.Foo, "bar")
|
||||
|
||||
obj = FooStruct{}
|
||||
req = requestWithBody("POST", badPath, badBody)
|
||||
err = JSON.Bind(req, &obj)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func testProtoBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
|
||||
assert.Equal(t, b.Name(), name)
|
||||
|
||||
obj := example.Test{}
|
||||
req := requestWithBody("POST", path, body)
|
||||
req.Header.Add("Content-Type", MIMEPROTOBUF)
|
||||
err := b.Bind(req, &obj)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, *obj.Label, "yes")
|
||||
|
||||
obj = example.Test{}
|
||||
req = requestWithBody("POST", badPath, badBody)
|
||||
req.Header.Add("Content-Type", MIMEPROTOBUF)
|
||||
err = ProtoBuf.Bind(req, &obj)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
|
||||
assert.Equal(t, b.Name(), name)
|
||||
|
||||
obj := FooStruct{}
|
||||
req := requestWithBody("POST", path, body)
|
||||
req.Header.Add("Content-Type", MIMEMSGPACK)
|
||||
err := b.Bind(req, &obj)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, obj.Foo, "bar")
|
||||
|
||||
obj = FooStruct{}
|
||||
req = requestWithBody("POST", badPath, badBody)
|
||||
req.Header.Add("Content-Type", MIMEMSGPACK)
|
||||
err = MsgPack.Bind(req, &obj)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func requestWithBody(method, path, body string) (req *http.Request) {
|
||||
req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
return
|
||||
}
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
// Copyright 2017 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package binding
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"gopkg.in/go-playground/validator.v8"
|
||||
)
|
||||
|
||||
type defaultValidator struct {
|
||||
once sync.Once
|
||||
validate *validator.Validate
|
||||
}
|
||||
|
||||
var _ StructValidator = &defaultValidator{}
|
||||
|
||||
func (v *defaultValidator) ValidateStruct(obj interface{}) error {
|
||||
if kindOfData(obj) == reflect.Struct {
|
||||
v.lazyinit()
|
||||
if err := v.validate.Struct(obj); err != nil {
|
||||
return error(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *defaultValidator) lazyinit() {
|
||||
v.once.Do(func() {
|
||||
config := &validator.Config{TagName: "binding"}
|
||||
v.validate = validator.New(config)
|
||||
})
|
||||
}
|
||||
|
||||
func kindOfData(data interface{}) reflect.Kind {
|
||||
value := reflect.ValueOf(data)
|
||||
valueType := value.Kind()
|
||||
if valueType == reflect.Ptr {
|
||||
valueType = value.Elem().Kind()
|
||||
}
|
||||
return valueType
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user