diff --git a/.gitignore b/.gitignore index 2e897d80..f5fe186d 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,6 @@ *.iml /hetzner-kube* /dist - +/vendor /cmd/test.go diff --git a/.travis.yml b/.travis.yml index b4193e6c..721db553 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,7 +6,8 @@ go: - tip before_install: - - go get -v ./... + - go get -v github.com/golang/dep/cmd/dep + - dep ensure - go get -v github.com/golang/lint/golint script: diff --git a/Gopkg.lock b/Gopkg.lock index 3cb1672b..936b442a 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -3,200 +3,260 @@ [[projects]] branch = "master" + digest = "1:0e5b66364c5559101d270c0ed5f0196ca6ce910cf89247b9315c6305f15f29d5" name = "github.com/Pallinder/go-randomdata" packages = ["."] - revision = "442d37d9dbc782dbd737af9ec575d8858b79261b" + pruneopts = "UT" + revision = "15df0648130a623e418886f81b2aaecd0a00547b" [[projects]] branch = "master" + digest = "1:86d119ee8a0fb122f2d0e0fbbbd5d2f65953029248743462ee3908a21ae04247" name = "github.com/andreyvit/diff" packages = ["."] + pruneopts = "UT" revision = "c7f18ee00883bfd3b00e0a2bf7607827e0148ad4" [[projects]] + digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" name = "github.com/fsnotify/fsnotify" packages = ["."] + pruneopts = "UT" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" version = "v1.4.7" [[projects]] + digest = "1:a6475803bcfec589e6bebc62b7326653102dda3926c37ee1e491f6574c9ea088" name = "github.com/go-kit/kit" packages = [ "log", - "log/term" + "log/term", ] - revision = "4dc7be5d2d12881735283bcab7352178e190fc71" - version = "v0.6.0" + pruneopts = "UT" + revision = "ca4112baa34cb55091301bdc13b1420a122b1b9e" + version = "v0.7.0" [[projects]] + digest = "1:31a18dae27a29aa074515e43a443abfd2ba6deb6d69309d8d7ce789c45f34659" name = "github.com/go-logfmt/logfmt" packages = ["."] + pruneopts = "UT" revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" version = "v0.3.0" [[projects]] + digest = "1:c4a2528ccbcabf90f9f3c464a5fc9e302d592861bbfd0b7135a7de8a943d0406" name = "github.com/go-stack/stack" packages = ["."] + pruneopts = "UT" revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc" version = "v1.7.0" [[projects]] branch = "master" + digest = "1:cde3502ff38bf880c3a783acc5b48754aa509c651c4902c68726d2769883e9de" name = "github.com/gosuri/uilive" packages = ["."] + pruneopts = "UT" revision = "ac356e6e42cd31fcef8e6aec13ae9ed6fe87713e" [[projects]] branch = "master" + digest = "1:f6ae4b3c3d4411bffa0b8045fff29974e1eb866e1828786972059f89a130aecf" name = "github.com/gosuri/uiprogress" packages = [ ".", - "util/strutil" + "util/strutil", ] + pruneopts = "UT" revision = "d0567a9d84a1c40dd7568115ea66f4887bf57b33" [[projects]] branch = "master" + digest = "1:a361611b8c8c75a1091f00027767f7779b29cb37c456a71b8f2604c88057ab40" name = "github.com/hashicorp/hcl" packages = [ ".", "hcl/ast", "hcl/parser", + "hcl/printer", "hcl/scanner", "hcl/strconv", "hcl/token", "json/parser", "json/scanner", - "json/token" + "json/token", ] - revision = "23c074d0eceb2b8a5bfdbb271ab780cde70f05a8" + pruneopts = "UT" + revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" [[projects]] + digest = "1:3d6d253f7ed0d409e3e86197a6a16b8705d52900dd4273f144900f2c1dfb4e99" name = "github.com/hetznercloud/hcloud-go" packages = [ "hcloud", - "hcloud/schema" + "hcloud/schema", ] - revision = "b37849e439d7a02b07d495f65e7b797bec30eeae" - version = "v1.4.0" + pruneopts = "UT" + revision = "400c6f026bf3c8d5fead3df7806e6981a16bb6b8" + version = "v1.8.0" [[projects]] + digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be" name = "github.com/inconshreveable/mousetrap" packages = ["."] + pruneopts = "UT" revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" version = "v1.0" [[projects]] branch = "master" + digest = "1:a64e323dc06b73892e5bb5d040ced475c4645d456038333883f58934abbf6f72" name = "github.com/kr/logfmt" packages = ["."] + pruneopts = "UT" revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" [[projects]] + digest = "1:53e8c5c79716437e601696140e8b1801aae4204f4ec54a504333702a49572c4f" name = "github.com/magiconair/properties" - packages = ["."] - revision = "c3beff4c2358b44d0493c7dda585e7db7ff28ae6" - version = "v1.7.6" + packages = [ + ".", + "assert", + ] + pruneopts = "UT" + revision = "c2353362d570a7bfa228149c62842019201cfb71" + version = "v1.8.0" [[projects]] + digest = "1:d4d17353dbd05cb52a2a52b7fe1771883b682806f68db442b436294926bbfafb" name = "github.com/mattn/go-isatty" packages = ["."] + pruneopts = "UT" revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" version = "v0.0.3" [[projects]] branch = "master" + digest = "1:c7354463195544b1ab3c1f1fadb41430947f5d28dfbf2cdbd38268c5717a5a03" name = "github.com/mitchellh/go-homedir" packages = ["."] - revision = "b8bc1bf767474819792c23f32d8286a45736f1c6" + pruneopts = "UT" + revision = "58046073cbffe2f25d425fe1331102f55cf719de" [[projects]] branch = "master" + digest = "1:5ab79470a1d0fb19b041a624415612f8236b3c06070161a910562f2b2d064355" name = "github.com/mitchellh/mapstructure" packages = ["."] - revision = "00c29f56e2386353d58c599509e8dc3801b0d716" + pruneopts = "UT" + revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" [[projects]] + digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e" name = "github.com/pelletier/go-toml" packages = ["."] - revision = "acdc4509485b587f5e675510c4f2c63e90ff68a8" - version = "v1.1.0" + pruneopts = "UT" + revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" + version = "v1.2.0" [[projects]] + digest = "1:d917313f309bda80d27274d53985bc65651f81a5b66b820749ac7f8ef061fd04" name = "github.com/sergi/go-diff" packages = ["diffmatchpatch"] + pruneopts = "UT" revision = "1744e2970ca51c86172c8190fadad617561ed6e7" version = "v1.0.0" [[projects]] + digest = "1:bd1ae00087d17c5a748660b8e89e1043e1e5479d0fea743352cda2f8dd8c4f84" name = "github.com/spf13/afero" packages = [ ".", - "mem" + "mem", ] - revision = "bb8f1927f2a9d3ab41c9340aa034f6b803f4359c" - version = "v1.0.2" + pruneopts = "UT" + revision = "787d034dfe70e44075ccc060d346146ef53270ad" + version = "v1.1.1" [[projects]] + digest = "1:516e71bed754268937f57d4ecb190e01958452336fa73dbac880894164e91c1f" name = "github.com/spf13/cast" packages = ["."] + pruneopts = "UT" revision = "8965335b8c7107321228e3e3702cab9832751bac" version = "v1.2.0" [[projects]] + digest = "1:645cabccbb4fa8aab25a956cbcbdf6a6845ca736b2c64e197ca7cbb9d210b939" name = "github.com/spf13/cobra" packages = ["."] - revision = "7b2c5ac9fc04fc5efafb60700713d4fa609b777b" - version = "v0.0.1" + pruneopts = "UT" + revision = "ef82de70bb3f60c65fb8eebacbb2d122ef517385" + version = "v0.0.3" [[projects]] branch = "master" + digest = "1:8a020f916b23ff574845789daee6818daf8d25a4852419aae3f0b12378ba432a" name = "github.com/spf13/jwalterweatherman" packages = ["."] - revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" + pruneopts = "UT" + revision = "14d3d4c518341bea657dd8a226f5121c0ff8c9f2" [[projects]] + digest = "1:dab83a1bbc7ad3d7a6ba1a1cc1760f25ac38cdf7d96a5cdd55cd915a4f5ceaf9" name = "github.com/spf13/pflag" packages = ["."] - revision = "e57e3eeb33f795204c1ca35f56c44f83227c6e66" - version = "v1.0.0" + pruneopts = "UT" + revision = "9a97c102cda95a86cec2345a6f09f55a939babf5" + version = "v1.0.2" [[projects]] + digest = "1:4fc8a61287ccfb4286e1ca5ad2ce3b0b301d746053bf44ac38cf34e40ae10372" name = "github.com/spf13/viper" packages = ["."] - revision = "25b30aa063fc18e48662b86996252eabdcf2f0c7" - version = "v1.0.0" + pruneopts = "UT" + revision = "907c19d40d9a6c9bb55f040ff4ae45271a4754b9" + version = "v1.1.0" [[projects]] branch = "master" + digest = "1:d2a36ba38f4f6871cd4346b5b3c327873c3b8da0a4c915ae82fba65c67a9a40c" name = "github.com/thcyron/uiprogress" packages = ["."] + pruneopts = "UT" revision = "25e98ffb0e98b5192b475d8f2fd78083bfe9a67e" [[projects]] branch = "master" + digest = "1:10e257965f5774c1ef03b258130a6caa8dddbfe03041f69d7c16a00463dece62" name = "golang.org/x/crypto" packages = [ "curve25519", "ed25519", "ed25519/internal/edwards25519", "internal/chacha20", + "internal/subtle", "poly1305", "ssh", - "ssh/terminal" + "ssh/terminal", ] - revision = "91a49db82a88618983a78a06c1cbd4e00ab749ab" + pruneopts = "UT" + revision = "de0752318171da717af4ce24d0a2e8626afaeb11" [[projects]] branch = "master" + digest = "1:2f71657f09ff05e4567909e9e0de7ad799828c96d402c540b41dc044a6590fb2" name = "golang.org/x/sys" packages = [ "unix", - "windows" + "windows", ] - revision = "dd2ff4accc098aceecb86b36eaa7829b2a17b1c9" + pruneopts = "UT" + revision = "1c9583448a9c3aa0f9a6a5241bf73c0bd8aafded" [[projects]] + digest = "1:8029e9743749d4be5bc9f7d42ea1659471767860f0cdc34d37c3111bd308a295" name = "golang.org/x/text" packages = [ "internal/gen", @@ -204,20 +264,37 @@ "internal/ucd", "transform", "unicode/cldr", - "unicode/norm" + "unicode/norm", ] + pruneopts = "UT" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" [[projects]] + digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202" name = "gopkg.in/yaml.v2" packages = ["."] - revision = "7f97868eec74b32b0982dd158a51a446d1da7eb5" - version = "v2.1.1" + pruneopts = "UT" + revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" + version = "v2.2.1" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "4fd661e189180b9c925c787cde36cb8c809b5e2a9a07fbfadeab65bf8245a715" + input-imports = [ + "github.com/Pallinder/go-randomdata", + "github.com/andreyvit/diff", + "github.com/go-kit/kit/log/term", + "github.com/gosuri/uiprogress", + "github.com/gosuri/uiprogress/util/strutil", + "github.com/hetznercloud/hcloud-go/hcloud", + "github.com/magiconair/properties/assert", + "github.com/mitchellh/go-homedir", + "github.com/spf13/cobra", + "github.com/spf13/viper", + "github.com/thcyron/uiprogress", + "golang.org/x/crypto/ssh", + "golang.org/x/crypto/ssh/terminal", + ] solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index e69de29b..d5f3676a 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -0,0 +1,47 @@ +[[constraint]] + branch = "master" + name = "github.com/Pallinder/go-randomdata" + +[[constraint]] + branch = "master" + name = "github.com/andreyvit/diff" + +[[constraint]] + name = "github.com/go-kit/kit" + version = "0.7.0" + +[[constraint]] + branch = "master" + name = "github.com/gosuri/uiprogress" + +[[constraint]] + name = "github.com/hetznercloud/hcloud-go" + version = "1.8.0" + +[[constraint]] + name = "github.com/magiconair/properties" + version = "1.8.0" + +[[constraint]] + branch = "master" + name = "github.com/mitchellh/go-homedir" + +[[constraint]] + name = "github.com/spf13/cobra" + version = "0.0.3" + +[[constraint]] + name = "github.com/spf13/viper" + version = "1.1.0" + +[[constraint]] + branch = "master" + name = "github.com/thcyron/uiprogress" + +[[constraint]] + branch = "master" + name = "golang.org/x/crypto" + +[prune] + go-tests = true + unused-packages = true diff --git a/build-all.sh b/build-all.sh index fe0ac2f7..f4a4f539 100755 --- a/build-all.sh +++ b/build-all.sh @@ -2,6 +2,7 @@ set -ev +dep ensure go build VERSION=$(./hetzner-kube version) diff --git a/vendor/github.com/Pallinder/go-randomdata/.gitignore b/vendor/github.com/Pallinder/go-randomdata/.gitignore deleted file mode 100644 index 583cb13d..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -# git ignore for idea (IntelliJ, Gogland,...) -.idea/ - -# 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 - -# Testing specific -*.out -*.prof -*.test \ No newline at end of file diff --git a/vendor/github.com/Pallinder/go-randomdata/.travis.yml b/vendor/github.com/Pallinder/go-randomdata/.travis.yml deleted file mode 100644 index eb93f278..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: go \ No newline at end of file diff --git a/vendor/github.com/Pallinder/go-randomdata/LICENSE b/vendor/github.com/Pallinder/go-randomdata/LICENSE deleted file mode 100644 index 258de4da..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 David Pallinder - -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. diff --git a/vendor/github.com/Pallinder/go-randomdata/README.md b/vendor/github.com/Pallinder/go-randomdata/README.md deleted file mode 100644 index 228dedb7..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/README.md +++ /dev/null @@ -1,175 +0,0 @@ -# go-randomdata - -[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/Pallinder/go-randomdata/issues) -[![GoDoc](https://godoc.org/github.com/Pallinder/go-randomdata?status.svg)](https://godoc.org/github.com/Pallinder/go-randomdata) -[![Build Status](https://travis-ci.org/Pallinder/go-randomdata.png)](https://travis-ci.org/Pallinder/go-randomdata) -[![Go Report Card](https://goreportcard.com/badge/github.com/Pallinder/go-randomdata)](https://goreportcard.com/report/github.com/Pallinder/go-randomdata) - -randomdata is a tiny help suite for generating random data such as - -* first names (male or female) -* last names -* full names (male or female) -* country names (full name or iso 3166.1 alpha-2 or alpha-3) -* random email address -* city names -* American state names (two chars or full) -* random numbers (in an interval) -* random paragraphs -* random bool values -* postal- or zip-codes formatted for a range of different countries. -* american sounding addresses / street names -* silly names - suitable for names of things -* random days -* random months -* random full date -* random full profile -* random date inside range - -## Installation - -```go get github.com/Pallinder/go-randomdata``` - -## Usage - -```go - -package main - -import ( - "fmt" - "github.com/Pallinder/go-randomdata" -) - -func main() { - // Print a random silly name - fmt.Println(randomdata.SillyName()) - - // Print a male title - fmt.Println(randomdata.Title(randomdata.Male)) - - // Print a female title - fmt.Println(randomdata.Title(randomdata.Female)) - - // Print a title with random gender - fmt.Println(randomdata.Title(randomdata.RandomGender)) - - // Print a male first name - fmt.Println(randomdata.FirstName(randomdata.Male)) - - // Print a female first name - fmt.Println(randomdata.FirstName(randomdata.Female)) - - // Print a last name - fmt.Println(randomdata.LastName()) - - // Print a male name - fmt.Println(randomdata.FullName(randomdata.Male)) - - // Print a female name - fmt.Println(randomdata.FullName(randomdata.Female)) - - // Print a name with random gender - fmt.Println(randomdata.FullName(randomdata.RandomGender)) - - // Print an email - fmt.Println(randomdata.Email()) - - // Print a country with full text representation - fmt.Println(randomdata.Country(randomdata.FullCountry)) - - // Print a country using ISO 3166-1 alpha-2 - fmt.Println(randomdata.Country(randomdata.TwoCharCountry)) - - // Print a country using ISO 3166-1 alpha-3 - fmt.Println(randomdata.Country(randomdata.ThreeCharCountry)) - - // Print a currency using ISO 4217 - fmt.Println(randomdata.Currency()) - - // Print the name of a random city - fmt.Println(randomdata.City()) - - // Print the name of a random american state - fmt.Println(randomdata.State(randomdata.Large)) - - // Print the name of a random american state using two chars - fmt.Println(randomdata.State(randomdata.Small)) - - // Print an american sounding street name - fmt.Println(randomdata.Street()) - - // Print an american sounding address - fmt.Println(randomdata.Address()) - - // Print a random number >= 10 and <= 20 - fmt.Println(randomdata.Number(10, 20)) - - // Print a number >= 0 and <= 20 - fmt.Println(randomdata.Number(20)) - - // Print a random float >= 0 and <= 20 with decimal point 3 - fmt.Println(randomdata.Decimal(0, 20, 3)) - - // Print a random float >= 10 and <= 20 - fmt.Println(randomdata.Decimal(10, 20)) - - // Print a random float >= 0 and <= 20 - fmt.Println(randomdata.Decimal(20)) - - // Print a bool - fmt.Println(randomdata.Boolean()) - - // Print a paragraph - fmt.Println(randomdata.Paragraph()) - - // Print a postal code - fmt.Println(randomdata.PostalCode("SE")) - - // Print a set of 2 random numbers as a string - fmt.Println(randomdata.StringNumber(2, "-")) - - // Print a set of 2 random 3-Digits numbers as a string - fmt.Println(randomdata.StringNumberExt(2, "-", 3)) - - // Print a random string sampled from a list of strings - fmt.Println(randomdata.StringSample("my string 1", "my string 2", "my string 3")) - - // Print a valid random IPv4 address - fmt.Println(randomdata.IpV4Address()) - - // Print a valid random IPv6 address - fmt.Println(randomdata.IpV6Address()) - - // Print a browser's user agent string - fmt.Println(randomdata.UserAgentString()) - - // Print a day - fmt.Println(randomdata.Day()) - - // Print a month - fmt.Println(randomdata.Month()) - - // Print full date like Monday 22 Aug 2016 - fmt.Println(randomdata.FullDate()) - - // Print full date <= Monday 22 Aug 2016 - fmt.Println(randomdata.FullDateInRange("2016-08-22")) - - // Print full date >= Monday 01 Aug 2016 and <= Monday 22 Aug 2016 - fmt.Println(randomdata.FullDateInRange("2016-08-01", "2016-08-22")) - - // Get a complete and randomised profile of data generally used for users - // There are many fields in the profile to use check the Profile struct definition in fullprofile.go - profile := randomdata.GenerateProfile(randomdata.Male | randomdata.Female | randomdata.RandomGender) - fmt.Printf("The new profile's username is: %s and password (md5): %s\n", profile.Login.Username, profile.Login.Md5) -} - -``` - -## Contributors - -* [jteeuwen](https://github.com/jteeuwen) -* [n1try](https://github.com/n1try) - -All the other contributors are listed [here](https://github.com/Pallinder/go-randomdata/graphs/contributors). \ No newline at end of file diff --git a/vendor/github.com/Pallinder/go-randomdata/fullprofile.go b/vendor/github.com/Pallinder/go-randomdata/fullprofile.go deleted file mode 100644 index 7e41a8f2..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/fullprofile.go +++ /dev/null @@ -1,150 +0,0 @@ -package randomdata - -import ( - "crypto/md5" - "crypto/sha1" - "crypto/sha256" - "encoding/base64" - "encoding/hex" - "fmt" - "math/rand" - "strconv" - "strings" - "time" -) - -var letterRunes = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") -var portraitDirs = []string{"men", "women"} - -type Profile struct { - Gender string `json:"gender"` - Name struct { - First string `json:"first"` - Last string `json:"last"` - Title string `json:"title"` - } `json:"name"` - Location struct { - Street string `json:"street"` - City string `json:"city"` - State string `json:"state"` - Postcode int `json:"postcode"` - } `json:"location"` - - Email string `json:"email"` - Login struct { - Username string `json:"username"` - Password string `json:"password"` - Salt string `json:"salt"` - Md5 string `json:"md5"` - Sha1 string `json:"sha1"` - Sha256 string `json:"sha256"` - } `json:"login"` - - Dob string `json:"dob"` - Registered string `json:"registered"` - Phone string `json:"phone"` - Cell string `json:"cell"` - - ID struct { - Name string `json:"name"` - Value interface{} `json:"value"` - } `json:"id"` - - Picture struct { - Large string `json:"large"` - Medium string `json:"medium"` - Thumbnail string `json:"thumbnail"` - } `json:"picture"` - Nat string `json:"nat"` -} - -func RandStringRunes(n int) string { - b := make([]rune, n) - for i := range b { - b[i] = letterRunes[rand.Intn(len(letterRunes))] - } - return string(b) -} - -func getMD5Hash(text string) string { - hasher := md5.New() - hasher.Write([]byte(text)) - return hex.EncodeToString(hasher.Sum(nil)) -} - -func getSha1(text string) string { - hasher := sha1.New() - hasher.Write([]byte(text)) - sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) - return sha -} - -func getSha256(text string) string { - hasher := sha256.New() - hasher.Write([]byte(text)) - sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) - return sha -} - -func GenerateProfile(gender int) *Profile { - rand.Seed(time.Now().UnixNano()) - profile := &Profile{} - if gender == Male { - profile.Gender = "male" - } else if gender == Female { - profile.Gender = "female" - } else { - gender = rand.Intn(2) - if gender == Male { - profile.Gender = "male" - } else { - profile.Gender = "female" - } - } - profile.Name.Title = Title(gender) - profile.Name.First = FirstName(gender) - profile.Name.Last = LastName() - profile.ID.Name = "SSN" - profile.ID.Value = fmt.Sprintf("%d-%d-%d", - Number(101, 999), - Number(01, 99), - Number(100, 9999), - ) - - profile.Email = strings.ToLower(profile.Name.First) + "." + strings.ToLower(profile.Name.Last) + "@example.com" - profile.Cell = fmt.Sprintf("%d-%d-%d", - Number(201, 999), - Number(201, 999), - Number(1000, 9999), - ) - profile.Phone = fmt.Sprintf("%d-%d-%d", - Number(201, 999), - Number(201, 999), - Number(1000, 9999), - ) - profile.Dob = FullDate() - profile.Registered = FullDate() - profile.Nat = "US" - - profile.Location.City = City() - i, _ := strconv.Atoi(PostalCode("US")) - profile.Location.Postcode = i - profile.Location.State = State(2) - profile.Location.Street = StringNumber(1, "") + " " + Street() - - profile.Login.Username = SillyName() - pass := SillyName() - salt := RandStringRunes(16) - profile.Login.Password = pass - profile.Login.Salt = salt - profile.Login.Md5 = getMD5Hash(pass + salt) - profile.Login.Sha1 = getSha1(pass + salt) - profile.Login.Sha256 = getSha256(pass + salt) - - pic := rand.Intn(35) - profile.Picture.Large = fmt.Sprintf("https://randomuser.me/api/portraits/%s/%d.jpg", portraitDirs[gender], pic) - profile.Picture.Medium = fmt.Sprintf("https://randomuser.me/api/portraits/med/%s/%d.jpg", portraitDirs[gender], pic) - profile.Picture.Thumbnail = fmt.Sprintf("https://randomuser.me/api/portraits/thumb/%s/%d.jpg", portraitDirs[gender], pic) - - return profile -} diff --git a/vendor/github.com/Pallinder/go-randomdata/fullprofile_test.go b/vendor/github.com/Pallinder/go-randomdata/fullprofile_test.go deleted file mode 100644 index c9afcbf1..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/fullprofile_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package randomdata - -import ( - "testing" -) - -func Test_FullProfileGenerator(t *testing.T) { - profile := GenerateProfile(1) - - if profile.Gender != "female" { - t.Fatalf("Expected gender to be female but got %s", profile.Gender) - } - - profile = GenerateProfile(0) - - if profile.Gender != "male" { - t.Fatalf("Expected gender to be male but got %s", profile.Gender) - } - - profile = GenerateProfile(2) - - if profile == nil { - t.Fatal("Profile failed to generate") - } - - if len(profile.Cell) != 12 { - t.Fatalf("Expected Cell# to be len %d but got %d\n", 12, len(profile.Cell)) - } - - if len(profile.Phone) != 12 { - t.Fatalf("Expected Phone# to be len %d but got %d\n", 12, len(profile.Cell)) - } - - if profile.Login.Username == "" { - t.Fatal("Profile Username failed to generate") - } - - if profile.Location.Street == "" { - t.Fatal("Profile Street failed to generate") - } - - if profile.ID.Name != "SSN" { - t.Fatalf("Profile ID Name to be SSN, but got %s\n", profile.ID.Name) - } - - if profile.Picture.Large == "" { - t.Fatalf("Profile Picture Large to be set, but got %s\n", profile.Picture.Large) - } -} diff --git a/vendor/github.com/Pallinder/go-randomdata/jsondata.go b/vendor/github.com/Pallinder/go-randomdata/jsondata.go deleted file mode 100644 index 58859bdb..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/jsondata.go +++ /dev/null @@ -1,2659 +0,0 @@ -package randomdata - -var data = []byte(`{ - "adjectives": [ - "black", - "white", - "gray", - "brown", - "red", - "pink", - "crimson", - "carnelian", - "orange", - "yellow", - "ivory", - "cream", - "green", - "viridian", - "aquamarine", - "cyan", - "blue", - "cerulean", - "azure", - "indigo", - "navy", - "violet", - "purple", - "lavender", - "magenta", - "rainbow", - "iridescent", - "spectrum", - "prism", - "bold", - "vivid", - "pale", - "clear", - "glass", - "translucent", - "misty", - "dark", - "light", - "gold", - "silver", - "copper", - "bronze", - "steel", - "iron", - "brass", - "mercury", - "zinc", - "chrome", - "platinum", - "titanium", - "nickel", - "lead", - "pewter", - "rust", - "metal", - "stone", - "quartz", - "granite", - "marble", - "alabaster", - "agate", - "jasper", - "pebble", - "pyrite", - "crystal", - "geode", - "obsidian", - "mica", - "flint", - "sand", - "gravel", - "boulder", - "basalt", - "ruby", - "beryl", - "scarlet", - "citrine", - "sulpher", - "topaz", - "amber", - "emerald", - "malachite", - "jade", - "abalone", - "lapis", - "sapphire", - "diamond", - "peridot", - "gem", - "jewel", - "bevel", - "coral", - "jet", - "ebony", - "wood", - "tree", - "cherry", - "maple", - "cedar", - "branch", - "bramble", - "rowan", - "ash", - "fir", - "pine", - "cactus", - "alder", - "grove", - "forest", - "jungle", - "palm", - "bush", - "mulberry", - "juniper", - "vine", - "ivy", - "rose", - "lily", - "tulip", - "daffodil", - "honeysuckle", - "fuschia", - "hazel", - "walnut", - "almond", - "lime", - "lemon", - "apple", - "blossom", - "bloom", - "crocus", - "rose", - "buttercup", - "dandelion", - "iris", - "carnation", - "fern", - "root", - "branch", - "leaf", - "seed", - "flower", - "petal", - "pollen", - "orchid", - "mangrove", - "cypress", - "sequoia", - "sage", - "heather", - "snapdragon", - "daisy", - "mountain", - "hill", - "alpine", - "chestnut", - "valley", - "glacier", - "forest", - "grove", - "glen", - "tree", - "thorn", - "stump", - "desert", - "canyon", - "dune", - "oasis", - "mirage", - "well", - "spring", - "meadow", - "field", - "prairie", - "grass", - "tundra", - "island", - "shore", - "sand", - "shell", - "surf", - "wave", - "foam", - "tide", - "lake", - "river", - "brook", - "stream", - "pool", - "pond", - "sun", - "sprinkle", - "shade", - "shadow", - "rain", - "cloud", - "storm", - "hail", - "snow", - "sleet", - "thunder", - "lightning", - "wind", - "hurricane", - "typhoon", - "dawn", - "sunrise", - "morning", - "noon", - "twilight", - "evening", - "sunset", - "midnight", - "night", - "sky", - "star", - "stellar", - "comet", - "nebula", - "quasar", - "solar", - "lunar", - "planet", - "meteor", - "sprout", - "pear", - "plum", - "kiwi", - "berry", - "apricot", - "peach", - "mango", - "pineapple", - "coconut", - "olive", - "ginger", - "root", - "plain", - "fancy", - "stripe", - "spot", - "speckle", - "spangle", - "ring", - "band", - "blaze", - "paint", - "pinto", - "shade", - "tabby", - "brindle", - "patch", - "calico", - "checker", - "dot", - "pattern", - "glitter", - "glimmer", - "shimmer", - "dull", - "dust", - "dirt", - "glaze", - "scratch", - "quick", - "swift", - "fast", - "slow", - "clever", - "fire", - "flicker", - "flash", - "spark", - "ember", - "coal", - "flame", - "chocolate", - "vanilla", - "sugar", - "spice", - "cake", - "pie", - "cookie", - "candy", - "caramel", - "spiral", - "round", - "jelly", - "square", - "narrow", - "long", - "short", - "small", - "tiny", - "big", - "giant", - "great", - "atom", - "peppermint", - "mint", - "butter", - "fringe", - "rag", - "quilt", - "truth", - "lie", - "holy", - "curse", - "noble", - "sly", - "brave", - "shy", - "lava", - "foul", - "leather", - "fantasy", - "keen", - "luminous", - "feather", - "sticky", - "gossamer", - "cotton", - "rattle", - "silk", - "satin", - "cord", - "denim", - "flannel", - "plaid", - "wool", - "linen", - "silent", - "flax", - "weak", - "valiant", - "fierce", - "gentle", - "rhinestone", - "splash", - "north", - "south", - "east", - "west", - "summer", - "winter", - "autumn", - "spring", - "season", - "equinox", - "solstice", - "paper", - "motley", - "torch", - "ballistic", - "rampant", - "shag", - "freckle", - "wild", - "free", - "chain", - "sheer", - "crazy", - "mad", - "candle", - "ribbon", - "lace", - "notch", - "wax", - "shine", - "shallow", - "deep", - "bubble", - "harvest", - "fluff", - "venom", - "boom", - "slash", - "rune", - "cold", - "quill", - "love", - "hate", - "garnet", - "zircon", - "power", - "bone", - "void", - "horn", - "glory", - "cyber", - "nova", - "hot", - "helix", - "cosmic", - "quark", - "quiver", - "holly", - "clover", - "polar", - "regal", - "ripple", - "ebony", - "wheat", - "phantom", - "dew", - "chisel", - "crack", - "chatter", - "laser", - "foil", - "tin", - "clever", - "treasure", - "maze", - "twisty", - "curly", - "fortune", - "fate", - "destiny", - "cute", - "slime", - "ink", - "disco", - "plume", - "time", - "psychadelic", - "relic", - "fossil", - "water", - "savage", - "ancient", - "rapid", - "road", - "trail", - "stitch", - "button", - "bow", - "nimble", - "zest", - "sour", - "bitter", - "phase", - "fan", - "frill", - "plump", - "pickle", - "mud", - "puddle", - "pond", - "river", - "spring", - "stream", - "battle", - "arrow", - "plume", - "roan", - "pitch", - "tar", - "cat", - "dog", - "horse", - "lizard", - "bird", - "fish", - "saber", - "scythe", - "sharp", - "soft", - "razor", - "neon", - "dandy", - "weed", - "swamp", - "marsh", - "bog", - "peat", - "moor", - "muck", - "mire", - "grave", - "fair", - "just", - "brick", - "puzzle", - "skitter", - "prong", - "fork", - "dent", - "dour", - "warp", - "luck", - "coffee", - "split", - "chip", - "hollow", - "heavy", - "legend", - "hickory", - "mesquite", - "nettle", - "rogue", - "charm", - "prickle", - "bead", - "sponge", - "whip", - "bald", - "frost", - "fog", - "oil", - "veil", - "cliff", - "volcano", - "rift", - "maze", - "proud", - "dew", - "mirror", - "shard", - "salt", - "pepper", - "honey", - "thread", - "bristle", - "ripple", - "glow", - "zenith" - ], - "nouns": [ - "head", - "crest", - "crown", - "tooth", - "fang", - "horn", - "frill", - "skull", - "bone", - "tongue", - "throat", - "voice", - "nose", - "snout", - "chin", - "eye", - "sight", - "seer", - "speaker", - "singer", - "song", - "chanter", - "howler", - "chatter", - "shrieker", - "shriek", - "jaw", - "bite", - "biter", - "neck", - "shoulder", - "fin", - "wing", - "arm", - "lifter", - "grasp", - "grabber", - "hand", - "paw", - "foot", - "finger", - "toe", - "thumb", - "talon", - "palm", - "touch", - "racer", - "runner", - "hoof", - "fly", - "flier", - "swoop", - "roar", - "hiss", - "hisser", - "snarl", - "dive", - "diver", - "rib", - "chest", - "back", - "ridge", - "leg", - "legs", - "tail", - "beak", - "walker", - "lasher", - "swisher", - "carver", - "kicker", - "roarer", - "crusher", - "spike", - "shaker", - "charger", - "hunter", - "weaver", - "crafter", - "binder", - "scribe", - "muse", - "snap", - "snapper", - "slayer", - "stalker", - "track", - "tracker", - "scar", - "scarer", - "fright", - "killer", - "death", - "doom", - "healer", - "saver", - "friend", - "foe", - "guardian", - "thunder", - "lightning", - "cloud", - "storm", - "forger", - "scale", - "hair", - "braid", - "nape", - "belly", - "thief", - "stealer", - "reaper", - "giver", - "taker", - "dancer", - "player", - "gambler", - "twister", - "turner", - "painter", - "dart", - "drifter", - "sting", - "stinger", - "venom", - "spur", - "ripper", - "swallow", - "devourer", - "knight", - "lady", - "lord", - "queen", - "king", - "master", - "mistress", - "prince", - "princess", - "duke", - "dutchess", - "samurai", - "ninja", - "knave", - "slave", - "servant", - "sage", - "wizard", - "witch", - "warlock", - "warrior", - "jester", - "paladin", - "bard", - "trader", - "sword", - "shield", - "knife", - "dagger", - "arrow", - "bow", - "fighter", - "bane", - "follower", - "leader", - "scourge", - "watcher", - "cat", - "panther", - "tiger", - "cougar", - "puma", - "jaguar", - "ocelot", - "lynx", - "lion", - "leopard", - "ferret", - "weasel", - "wolverine", - "bear", - "raccoon", - "dog", - "wolf", - "kitten", - "puppy", - "cub", - "fox", - "hound", - "terrier", - "coyote", - "hyena", - "jackal", - "pig", - "horse", - "donkey", - "stallion", - "mare", - "zebra", - "antelope", - "gazelle", - "deer", - "buffalo", - "bison", - "boar", - "elk", - "whale", - "dolphin", - "shark", - "fish", - "minnow", - "salmon", - "ray", - "fisher", - "otter", - "gull", - "duck", - "goose", - "crow", - "raven", - "bird", - "eagle", - "raptor", - "hawk", - "falcon", - "moose", - "heron", - "owl", - "stork", - "crane", - "sparrow", - "robin", - "parrot", - "cockatoo", - "carp", - "lizard", - "gecko", - "iguana", - "snake", - "python", - "viper", - "boa", - "condor", - "vulture", - "spider", - "fly", - "scorpion", - "heron", - "oriole", - "toucan", - "bee", - "wasp", - "hornet", - "rabbit", - "bunny", - "hare", - "brow", - "mustang", - "ox", - "piper", - "soarer", - "flasher", - "moth", - "mask", - "hide", - "hero", - "antler", - "chill", - "chiller", - "gem", - "ogre", - "myth", - "elf", - "fairy", - "pixie", - "dragon", - "griffin", - "unicorn", - "pegasus", - "sprite", - "fancier", - "chopper", - "slicer", - "skinner", - "butterfly", - "legend", - "wanderer", - "rover", - "raver", - "loon", - "lancer", - "glass", - "glazer", - "flame", - "crystal", - "lantern", - "lighter", - "cloak", - "bell", - "ringer", - "keeper", - "centaur", - "bolt", - "catcher", - "whimsey", - "quester", - "rat", - "mouse", - "serpent", - "wyrm", - "gargoyle", - "thorn", - "whip", - "rider", - "spirit", - "sentry", - "bat", - "beetle", - "burn", - "cowl", - "stone", - "gem", - "collar", - "mark", - "grin", - "scowl", - "spear", - "razor", - "edge", - "seeker", - "jay", - "ape", - "monkey", - "gorilla", - "koala", - "kangaroo", - "yak", - "sloth", - "ant", - "roach", - "weed", - "seed", - "eater", - "razor", - "shirt", - "face", - "goat", - "mind", - "shift", - "rider", - "face", - "mole", - "vole", - "pirate", - "llama", - "stag", - "bug", - "cap", - "boot", - "drop", - "hugger", - "sargent", - "snagglefoot", - "carpet", - "curtain" - ], - "firstNamesMale": [ - "Jacob", - "Mason", - "Ethan", - "Noah", - "William", - "Liam", - "Jayden", - "Michael", - "Alexander", - "Aiden", - "Daniel", - "Matthew", - "Elijah", - "James", - "Anthony", - "Benjamin", - "Joshua", - "Andrew", - "David", - "Joseph" - ], - "firstNamesFemale": [ - "Sophia", - "Emma", - "Isabella", - "Olivia", - "Ava", - "Emily", - "Abigail", - "Mia", - "Madison", - "Elizabeth", - "Chloe", - "Ella", - "Avery", - "Addison", - "Aubrey", - "Lily", - "Natalie", - "Sofia", - "Charlotte", - "Zoey" - ], - "lastNames": [ - "Smith", - "Johnson", - "Williams", - "Jones", - "Brown", - "Davis", - "Miller", - "Wilson", - "Moore", - "Taylor", - "Anderson", - "Thomas", - "Jackson", - "White", - "Harris", - "Martin", - "Thompson", - "Garcia", - "Martinez", - "Robinson" - ], - "domains": [ - "test.com", - "test.net", - "test.org", - "example.com", - "example.net", - "example.org" - ], - "people": [ - "Adams", - "Franklin", - "Jackson", - "Jefferson", - "Lincoln", - "Madison", - "Washington", - "Wilson" - ], - "streetTypes": [ - "St", - "Ave", - "Rd", - "Blvd", - "Trl", - "Ter", - "Rdg", - "Pl", - "Pkwy", - "Ct", - "Circle" - ], - "paragraphs": [ - "The Nellie, a cruising yawl, swung to her anchor without a flutter of the sails, and was at rest.", - "The sun set; the dusk fell on the stream, and lights began to appear along the shore. The Chapman light–house, a three–legged thing erect on a mud–flat, shone strongly.", - "He spoke of the happiness that was now certainly theirs, of the folly of not breaking sooner out of that magnificent prison of latter-day life, of the old romantic days that had passed from the world for ever.", - "One dog rolled before him, well-nigh slashed in half; but a second had him by the thigh, a third gripped his collar be- hind, and a fourth had the blade of the sword between its teeth, tasting its own blood.", - "She stared at him in astonishment, and as she read something of the significant hieroglyphic of his battered face, her lips whitened.", - "He completely abandoned the child of his marriage with Adelaida Ivanovna, not from malice, nor because of his matrimoni- al grievances, but simply because he forgot him.", - "It was at this time that the meeting, or, rather gathering of the mem- bers of this inharmonious family took place in the cell of the elder who had such an extraordinary influence on Alyosha.", - "The secular cooling that must someday overtake our planet has already gone far indeed with our neighbour.", - "Near it in the field, I remember, were three faint points of light, three telescopic stars infinitely remote, and all around it was the unfathomable darkness of empty space." - ], - "countries": [ - "Afghanistan", - "Albania", - "Algeria", - "American Samoa", - "Andorra", - "Angola", - "Antigua and Barbuda", - "Argentina", - "Armenia", - "Aruba", - "Australia", - "Austria", - "Azerbaijan", - "Bahamas, The", - "Bahrain", - "Bangladesh", - "Barbados", - "Belarus", - "Belgium", - "Belize", - "Benin", - "Bermuda", - "Bhutan", - "Bolivia", - "Bosnia and Herzegovina", - "Botswana", - "Brazil", - "Brunei Darussalam", - "Bulgaria", - "Burkina Faso", - "Burundi", - "Cambodia", - "Cameroon", - "Canada", - "Cape Verde", - "Cayman Islands", - "Central African Republic", - "Chad", - "Channel Islands", - "Chile", - "China", - "Colombia", - "Comoros", - "Congo, Dem. Rep.", - "Congo, Rep.", - "Costa Rica", - "Côte dIvoire", - "Croatia", - "Cuba", - "Cyprus", - "Czech Republic", - "Denmark", - "Djibouti", - "Dominica", - "Dominican Republic", - "Ecuador", - "Egypt, Arab Rep.", - "El Salvador", - "Equatorial Guinea", - "Eritrea", - "Estonia", - "Ethiopia", - "Faeroe Islands", - "Fiji", - "Finland", - "France", - "French Polynesia", - "Gabon", - "Gambia, The", - "Georgia", - "Germany", - "Ghana", - "Greece", - "Greenland", - "Grenada", - "Guam", - "Guatemala", - "Guinea", - "Guinea-Bissau", - "Guyana", - "Haiti", - "Honduras", - "Hong Kong, China", - "Hungary", - "Iceland", - "India", - "Indonesia", - "Iran, Islamic Rep.", - "Iraq", - "Ireland", - "Isle of Man", - "Israel", - "Italy", - "Jamaica", - "Japan", - "Jordan", - "Kazakhstan", - "Kenya", - "Kiribati", - "Korea, Dem. Rep.", - "Korea, Rep.", - "Kuwait", - "Kyrgyz Republic", - "Lao PDR", - "Latvia", - "Lebanon", - "Lesotho", - "Liberia", - "Libya", - "Liechtenstein", - "Lithuania", - "Luxembourg", - "Macao, China", - "Macedonia, FYR", - "Madagascar", - "Malawi", - "Malaysia", - "Maldives", - "Mali", - "Malta", - "Marshall Islands", - "Mauritania", - "Mauritius", - "Mayotte", - "Mexico", - "Micronesia, Fed. Sts.", - "Moldova", - "Monaco", - "Mongolia", - "Montenegro", - "Morocco", - "Mozambique", - "Myanmar", - "Namibia", - "Nepal", - "Netherlands", - "Netherlands Antilles", - "New Caledonia", - "New Zealand", - "Nicaragua", - "Niger", - "Nigeria", - "Northern Mariana Islands", - "Norway", - "Oman", - "Pakistan", - "Palau", - "Panama", - "Papua New Guinea", - "Paraguay", - "Peru", - "Philippines", - "Poland", - "Portugal", - "Puerto Rico", - "Qatar", - "Romania", - "Russian Federation", - "Rwanda", - "Samoa", - "San Marino", - "São Tomé and Principe", - "Saudi Arabia", - "Senegal", - "Serbia", - "Seychelles", - "Sierra Leone", - "Singapore", - "Slovak Republic", - "Slovenia", - "Solomon Islands", - "Somalia", - "South Africa", - "Spain", - "Sri Lanka", - "St. Kitts and Nevis", - "St. Lucia", - "St. Vincent and the Grenadines", - "Sudan", - "Suriname", - "Swaziland", - "Sweden", - "Switzerland", - "Syrian Arab Republic", - "Tajikistan", - "Tanzania", - "Thailand", - "Timor-Leste", - "Togo", - "Tonga", - "Trinidad and Tobago", - "Tunisia", - "Turkey", - "Turkmenistan", - "Uganda", - "Ukraine", - "United Arab Emirates", - "United Kingdom", - "United States", - "Uruguay", - "Uzbekistan", - "Vanuatu", - "Venezuela, RB", - "Vietnam", - "Virgin Islands (U.S.)", - "West Bank and Gaza", - "Yemen, Rep.", - "Zambia", - "Zimbabwe" - ], - "countriesThreeChars": [ - "AFG", - "ALB", - "DZA", - "ASM", - "ADO", - "AGO", - "ATG", - "ARG", - "ARM", - "ABW", - "AUS", - "AUT", - "AZE", - "BHS", - "BHR", - "BGD", - "BRB", - "BLR", - "BEL", - "BLZ", - "BEN", - "BMU", - "BTN", - "BOL", - "BIH", - "BWA", - "BRA", - "BRN", - "BGR", - "BFA", - "BDI", - "KHM", - "CMR", - "CAN", - "CPV", - "CYM", - "CAF", - "TCD", - "CHI", - "CHL", - "CHN", - "COL", - "COM", - "ZAR", - "COG", - "CRI", - "CIV", - "HRV", - "CUB", - "CUW", - "CYP", - "CZE", - "DNK", - "DJI", - "DMA", - "DOM", - "ECU", - "EGY", - "SLV", - "GNQ", - "ERI", - "EST", - "ETH", - "FRO", - "FJI", - "FIN", - "FRA", - "PYF", - "GAB", - "GMB", - "GEO", - "DEU", - "GHA", - "GRC", - "GRL", - "GRD", - "GUM", - "GTM", - "GIN", - "GNB", - "GUY", - "HTI", - "HND", - "HKG", - "HUN", - "ISL", - "IND", - "IDN", - "IRN", - "IRQ", - "IRL", - "IMY", - "ISR", - "ITA", - "JAM", - "JPN", - "JOR", - "KAZ", - "KEN", - "KIR", - "PRK", - "KOR", - "KSV", - "KWT", - "KGZ", - "LAO", - "LVA", - "LBN", - "LSO", - "LBR", - "LBY", - "LIE", - "LTU", - "LUX", - "MAC", - "MKD", - "MDG", - "MWI", - "MYS", - "MDV", - "MLI", - "MLT", - "MHL", - "MRT", - "MUS", - "MEX", - "FSM", - "MDA", - "MCO", - "MNG", - "MNE", - "MAR", - "MOZ", - "MMR", - "NAM", - "NPL", - "NLD", - "NCL", - "NZL", - "NIC", - "NER", - "NGA", - "MNP", - "NOR", - "OMN", - "PAK", - "PLW", - "PAN", - "PNG", - "PRY", - "PER", - "PHL", - "POL", - "PRT", - "PRI", - "QAT", - "ROM", - "RUS", - "RWA", - "WSM", - "SMR", - "STP", - "SAU", - "SEN", - "SRB", - "SYC", - "SLE", - "SGP", - "SXM", - "SVK", - "SVN", - "SLB", - "SOM", - "ZAF", - "SSD", - "ESP", - "LKA", - "KNA", - "LCA", - "MAF", - "VCT", - "SDN", - "SUR", - "SWZ", - "SWE", - "CHE", - "SYR", - "TJK", - "TZA", - "THA", - "TMP", - "TGO", - "TON", - "TTO", - "TUN", - "TUR", - "TKM", - "TCA", - "TUV", - "UGA", - "UKR", - "ARE", - "GBR", - "USA", - "URY", - "UZB", - "VUT", - "VEN", - "VNM", - "VIR", - "WBG", - "YEM", - "ZMB", - "ZWE" - ], - "countriesTwoChars": [ - "AF", - "AX", - "AL", - "DZ", - "AS", - "AD", - "AO", - "AI", - "AQ", - "AG", - "AR", - "AM", - "AW", - "AU", - "AT", - "AZ", - "BS", - "BH", - "BD", - "BB", - "BY", - "BE", - "BZ", - "BJ", - "BM", - "BT", - "BO", - "BQ", - "BA", - "BW", - "BV", - "BR", - "IO", - "BN", - "BG", - "BF", - "BI", - "KH", - "CM", - "CA", - "CV", - "KY", - "CF", - "TD", - "CL", - "CN", - "CX", - "CC", - "CO", - "KM", - "CG", - "CD", - "CK", - "CR", - "CI", - "HR", - "CU", - "CW", - "CY", - "CZ", - "DK", - "DJ", - "DM", - "DO", - "EC", - "EG", - "SV", - "GQ", - "ER", - "EE", - "ET", - "FK", - "FO", - "FJ", - "FI", - "FR", - "GF", - "PF", - "TF", - "GA", - "GM", - "GE", - "DE", - "GH", - "GI", - "GR", - "GL", - "GD", - "GP", - "GU", - "GT", - "GG", - "GN", - "GW", - "GY", - "HT", - "HM", - "VA", - "HN", - "HK", - "HU", - "IS", - "IN", - "ID", - "IR", - "IQ", - "IE", - "IM", - "IL", - "IT", - "JM", - "JP", - "JE", - "JO", - "KZ", - "KE", - "KI", - "KP", - "KR", - "KW", - "KG", - "LA", - "LV", - "LB", - "LS", - "LR", - "LY", - "LI", - "LT", - "LU", - "MO", - "MK", - "MG", - "MW", - "MY", - "MV", - "ML", - "MT", - "MH", - "MQ", - "MR", - "MU", - "YT", - "MX", - "FM", - "MD", - "MC", - "MN", - "ME", - "MS", - "MA", - "MZ", - "MM", - "NA", - "NR", - "NP", - "NL", - "NC", - "NZ", - "NI", - "NE", - "NG", - "NU", - "NF", - "MP", - "NO", - "OM", - "PK", - "PW", - "PS", - "PA", - "PG", - "PY", - "PE", - "PH", - "PN", - "PL", - "PT", - "PR", - "QA", - "RE", - "RO", - "RU", - "RW", - "BL", - "SH", - "KN", - "LC", - "MF", - "PM", - "VC", - "WS", - "SM", - "ST", - "SA", - "SN", - "RS", - "SC", - "SL", - "SG", - "SX", - "SK", - "SI", - "SB", - "SO", - "ZA", - "GS", - "SS", - "ES", - "LK", - "SD", - "SR", - "SJ", - "SZ", - "SE", - "CH", - "SY", - "TW", - "TJ", - "TZ", - "TH", - "TL", - "TG", - "TK", - "TO", - "TT", - "TN", - "TR", - "TM", - "TC", - "TV", - "UG", - "UA", - "AE", - "GB", - "US", - "UM", - "UY", - "UZ", - "VU", - "VE", - "VN", - "VG", - "VI", - "WF", - "EH", - "YE", - "ZM", - "ZW" - ], - "currencies": [ - "AED", - "AFN", - "ALL", - "AMD", - "ANG", - "AOA", - "ARS", - "AUD", - "AWG", - "AZN", - "BAM", - "BBD", - "BDT", - "BGN", - "BHD", - "BIF", - "BMD", - "BND", - "BOB", - "BOV", - "BRL", - "BSD", - "BTN", - "BWP", - "BYR", - "BZD", - "CAD", - "CDF", - "CHE", - "CHF", - "CHW", - "CLF", - "CLP", - "CNY", - "COP", - "COU", - "CRC", - "CUC", - "CUP", - "CVE", - "CZK", - "DJF", - "DKK", - "DOP", - "DZD", - "EGP", - "ERN", - "ETB", - "EUR", - "FJD", - "FKP", - "GBP", - "GEL", - "GHS", - "GIP", - "GMD", - "GNF", - "GTQ", - "GYD", - "HKD", - "HNL", - "HRK", - "HTG", - "HUF", - "IDR", - "ILS", - "INR", - "IQD", - "IRR", - "ISK", - "JMD", - "JOD", - "JPY", - "KES", - "KGS", - "KHR", - "KMF", - "KPW", - "KRW", - "KWD", - "KYD", - "KZT", - "LAK", - "LBP", - "LKR", - "LRD", - "LSL", - "LTL", - "LVL", - "LYD", - "MAD", - "MDL", - "MGA", - "MKD", - "MMK", - "MNT", - "MOP", - "MRO", - "MUR", - "MVR", - "MWK", - "MXN", - "MXV", - "MYR", - "MZN", - "NAD", - "NGN", - "NIO", - "NOK", - "NPR", - "NZD", - "OMR", - "PAB", - "PEN", - "PGK", - "PHP", - "PKR", - "PLN", - "PYG", - "QAR", - "RON", - "RSD", - "RUB", - "RWF", - "SAR", - "SBD", - "SCR", - "SDG", - "SEK", - "SGD", - "SHP", - "SLL", - "SOS", - "SRD", - "SSP", - "STD", - "SYP", - "SZL", - "THB", - "TJS", - "TMT", - "TND", - "TOP", - "TRY", - "TTD", - "TWD", - "TZS", - "UAH", - "UGX", - "USD", - "USN", - "USS", - "UYI", - "UYU", - "UZS", - "VEF", - "VND", - "VUV", - "WST", - "XAF", - "XCD", - "XDR", - "XFU", - "XOF", - "XPF", - "YER", - "ZAR", - "ZMW" - ], - "cities": [ - "Derby Center", - "New Deal", - "Cienega Springs", - "Ransom Canyon", - "Burrton", - "Hoonah", - "Lucien", - "San Martin", - "Buffalo City", - "Skidaway Island", - "Kingsbridge", - "Berkhamsted", - "Bury", - "Brandwell", - "Campden", - "Plympton", - "Baldock", - "Northleach", - "Newstead" - ], - "states": [ - "Alabama", - "Alaska", - "Arizona", - "Arkansas", - "California", - "Colorado", - "Connecticut", - "Delaware", - "Florida", - "Georgia", - "Hawaii", - "Idaho", - "Illinois", - "Indiana", - "Iowa", - "Kansas", - "Kentucky", - "Louisiana", - "Maine", - "Maryland", - "Massachusetts", - "Michigan", - "Minnesota", - "Mississippi", - "Missouri", - "Montana", - "Nebraska", - "Nevada", - "New Hampshire", - "New Jersey", - "New Mexico", - "New York", - "North Carolina", - "North Dakota", - "Ohio", - "Oklahoma", - "Oregon", - "Pennsylvania", - "Rhode Island", - "South Carolina", - "South Dakota", - "Tennessee", - "Texas", - "Utah", - "Vermont", - "Virginia", - "Washington", - "West Virginia", - "Wisconsin", - "Wyoming" - ], - "statesSmall": [ - "AL", - "AK", - "AS", - "AZ", - "AR", - "CA", - "CO", - "CT", - "DE", - "DC", - "FM", - "FL", - "GA", - "GU", - "HI", - "ID", - "IL", - "IN", - "IA", - "KS", - "KY", - "LA", - "ME", - "MH", - "MD", - "MA", - "MI", - "MN", - "MS", - "MO", - "MT", - "NE", - "NV", - "NH", - "NJ", - "NM", - "NY", - "NC", - "ND", - "MP", - "OH", - "OK", - "OR", - "PW", - "PA", - "PR", - "RI", - "SC", - "SD", - "TN", - "TX", - "UT", - "VT", - "VA", - "VI", - "WA", - "DC", - "WV", - "WI", - "WY" - ], - "days" : [ - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday" - ], - "months": [ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December" - ], - "femaleTitles": [ - "Ms", - "Miss", - "Mrs" - ], - "maleTitles": [ - "Mr" - ], - "timezones": [ - "Africa/Abidjan", - "Africa/Accra", - "Africa/Addis_Ababa", - "Africa/Algiers", - "Africa/Asmara", - "Africa/Asmera", - "Africa/Bamako", - "Africa/Bangui", - "Africa/Banjul", - "Africa/Bissau", - "Africa/Blantyre", - "Africa/Brazzaville", - "Africa/Bujumbura", - "Africa/Cairo", - "Africa/Casablanca", - "Africa/Ceuta", - "Africa/Conakry", - "Africa/Dakar", - "Africa/Dar_es_Salaam", - "Africa/Djibouti", - "Africa/Douala", - "Africa/El_Aaiun", - "Africa/Freetown", - "Africa/Gaborone", - "Africa/Harare", - "Africa/Johannesburg", - "Africa/Juba", - "Africa/Kampala", - "Africa/Khartoum", - "Africa/Kigali", - "Africa/Kinshasa", - "Africa/Lagos", - "Africa/Libreville", - "Africa/Lome", - "Africa/Luanda", - "Africa/Lubumbashi", - "Africa/Lusaka", - "Africa/Malabo", - "Africa/Maputo", - "Africa/Maseru", - "Africa/Mbabane", - "Africa/Mogadishu", - "Africa/Monrovia", - "Africa/Nairobi", - "Africa/Ndjamena", - "Africa/Niamey", - "Africa/Nouakchott", - "Africa/Ouagadougou", - "Africa/Porto-Novo", - "Africa/Sao_Tome", - "Africa/Timbuktu", - "Africa/Tripoli", - "Africa/Tunis", - "Africa/Windhoek", - "America/Argentina/Buenos_Aires", - "America/Argentina/Catamarca", - "America/Argentina/ComodRivadavia", - "America/Argentina/Cordoba", - "America/Argentina/Jujuy", - "America/Argentina/La_Rioja", - "America/Argentina/Mendoza", - "America/Argentina/Rio_Gallegos", - "America/Argentina/Salta", - "America/Argentina/San_Juan", - "America/Argentina/San_Luis", - "America/Argentina/Tucuman", - "America/Argentina/Ushuaia", - "America/Indiana/Indianapolis", - "America/Indiana/Knox", - "America/Indiana/Marengo", - "America/Indiana/Petersburg", - "America/Indiana/Tell_City", - "America/Indiana/Vevay", - "America/Indiana/Vincennes", - "America/Indiana/Winamac", - "America/Kentucky/Louisville", - "America/Kentucky/Monticello", - "America/North_Dakota/Beulah", - "America/North_Dakota/Center", - "America/North_Dakota/New_Salem", - "America/Adak", - "America/Anchorage", - "America/Anguilla", - "America/Antigua", - "America/Araguaina", - "America/Aruba", - "America/Asuncion", - "America/Atikokan", - "America/Atka", - "America/Bahia", - "America/Bahia_Banderas", - "America/Barbados", - "America/Belem", - "America/Belize", - "America/Blanc-Sablon", - "America/Boa_Vista", - "America/Bogota", - "America/Boise", - "America/Buenos_Aires", - "America/Cambridge_Bay", - "America/Campo_Grande", - "America/Cancun", - "America/Caracas", - "America/Catamarca", - "America/Cayenne", - "America/Cayman", - "America/Chicago", - "America/Chihuahua", - "America/Coral_Harbour", - "America/Cordoba", - "America/Costa_Rica", - "America/Creston", - "America/Cuiaba", - "America/Curacao", - "America/Danmarkshavn", - "America/Dawson", - "America/Dawson_Creek", - "America/Denver", - "America/Detroit", - "America/Dominica", - "America/Edmonton", - "America/Eirunepe", - "America/El_Salvador", - "America/Ensenada", - "America/Fortaleza", - "America/Fort_Nelson", - "America/Fort_Wayne", - "America/Glace_Bay", - "America/Godthab", - "America/Goose_Bay", - "America/Grand_Turk", - "America/Grenada", - "America/Guadeloupe", - "America/Guatemala", - "America/Guayaquil", - "America/Guyana", - "America/Halifax", - "America/Havana", - "America/Hermosillo", - "America/Indianapolis", - "America/Inuvik", - "America/Iqaluit", - "America/Jamaica", - "America/Jujuy", - "America/Juneau", - "America/Knox_IN", - "America/Kralendijk", - "America/La_Paz", - "America/Lima", - "America/Los_Angeles", - "America/Louisville", - "America/Lower_Princes", - "America/Maceio", - "America/Managua", - "America/Manaus", - "America/Marigot", - "America/Martinique", - "America/Matamoros", - "America/Mazatlan", - "America/Mendoza", - "America/Menominee", - "America/Merida", - "America/Metlakatla", - "America/Mexico_City", - "America/Miquelon", - "America/Moncton", - "America/Monterrey", - "America/Montevideo", - "America/Montreal", - "America/Montserrat", - "America/Nassau", - "America/New_York", - "America/Nipigon", - "America/Nome", - "America/Noronha", - "America/Ojinaga", - "America/Panama", - "America/Pangnirtung", - "America/Paramaribo", - "America/Phoenix", - "America/Port-au-Prince", - "America/Porto_Acre", - "America/Port_of_Spain", - "America/Porto_Velho", - "America/Puerto_Rico", - "America/Rainy_River", - "America/Rankin_Inlet", - "America/Recife", - "America/Regina", - "America/Resolute", - "America/Rio_Branco", - "America/Rosario", - "America/Santa_Isabel", - "America/Santarem", - "America/Santiago", - "America/Santo_Domingo", - "America/Sao_Paulo", - "America/Scoresbysund", - "America/Shiprock", - "America/Sitka", - "America/St_Barthelemy", - "America/St_Johns", - "America/St_Kitts", - "America/St_Lucia", - "America/St_Thomas", - "America/St_Vincent", - "America/Swift_Current", - "America/Tegucigalpa", - "America/Thule", - "America/Thunder_Bay", - "America/Tijuana", - "America/Toronto", - "America/Tortola", - "America/Vancouver", - "America/Virgin", - "America/Whitehorse", - "America/Winnipeg", - "America/Yakutat", - "America/Yellowknife", - "Antarctica/Casey", - "Antarctica/Davis", - "Antarctica/DumontDUrville", - "Antarctica/Macquarie", - "Antarctica/Mawson", - "Antarctica/McMurdo", - "Antarctica/Palmer", - "Antarctica/Rothera", - "Antarctica/South_Pole", - "Antarctica/Syowa", - "Antarctica/Troll", - "Antarctica/Vostok", - "Arctic/Longyearbyen", - "Asia/Aden", - "Asia/Almaty", - "Asia/Amman", - "Asia/Anadyr", - "Asia/Aqtau", - "Asia/Aqtobe", - "Asia/Ashgabat", - "Asia/Ashkhabad", - "Asia/Atyrau", - "Asia/Baghdad", - "Asia/Bahrain", - "Asia/Baku", - "Asia/Bangkok", - "Asia/Barnaul", - "Asia/Beirut", - "Asia/Bishkek", - "Asia/Brunei", - "Asia/Calcutta", - "Asia/Chita", - "Asia/Choibalsan", - "Asia/Chongqing", - "Asia/Chungking", - "Asia/Colombo", - "Asia/Dacca", - "Asia/Damascus", - "Asia/Dhaka", - "Asia/Dili", - "Asia/Dubai", - "Asia/Dushanbe", - "Asia/Famagusta", - "Asia/Gaza", - "Asia/Harbin", - "Asia/Hebron", - "Asia/Ho_Chi_Minh", - "Asia/Hong_Kong", - "Asia/Hovd", - "Asia/Irkutsk", - "Asia/Istanbul", - "Asia/Jakarta", - "Asia/Jayapura", - "Asia/Jerusalem", - "Asia/Kabul", - "Asia/Kamchatka", - "Asia/Karachi", - "Asia/Kashgar", - "Asia/Kathmandu", - "Asia/Katmandu", - "Asia/Khandyga", - "Asia/Kolkata", - "Asia/Krasnoyarsk", - "Asia/Kuala_Lumpur", - "Asia/Kuching", - "Asia/Kuwait", - "Asia/Macao", - "Asia/Macau", - "Asia/Magadan", - "Asia/Makassar", - "Asia/Manila", - "Asia/Muscat", - "Asia/Nicosia", - "Asia/Novokuznetsk", - "Asia/Novosibirsk", - "Asia/Omsk", - "Asia/Oral", - "Asia/Phnom_Penh", - "Asia/Pontianak", - "Asia/Pyongyang", - "Asia/Qatar", - "Asia/Qyzylorda", - "Asia/Rangoon", - "Asia/Riyadh", - "Asia/Saigon", - "Asia/Sakhalin", - "Asia/Samarkand", - "Asia/Seoul", - "Asia/Shanghai", - "Asia/Singapore", - "Asia/Srednekolymsk", - "Asia/Taipei", - "Asia/Tashkent", - "Asia/Tbilisi", - "Asia/Tehran", - "Asia/Tel_Aviv", - "Asia/Thimbu", - "Asia/Thimphu", - "Asia/Tokyo", - "Asia/Tomsk", - "Asia/Ujung_Pandang", - "Asia/Ulaanbaatar", - "Asia/Ulan_Bator", - "Asia/Urumqi", - "Asia/Ust-Nera", - "Asia/Vientiane", - "Asia/Vladivostok", - "Asia/Yakutsk", - "Asia/Yangon", - "Asia/Yekaterinburg", - "Asia/Yerevan", - "Atlantic/Azores", - "Atlantic/Bermuda", - "Atlantic/Canary", - "Atlantic/Cape_Verde", - "Atlantic/Faeroe", - "Atlantic/Faroe", - "Atlantic/Jan_Mayen", - "Atlantic/Madeira", - "Atlantic/Reykjavik", - "Atlantic/South_Georgia", - "Atlantic/Stanley", - "Atlantic/St_Helena", - "Australia/ACT", - "Australia/Adelaide", - "Australia/Brisbane", - "Australia/Broken_Hill", - "Australia/Canberra", - "Australia/Currie", - "Australia/Darwin", - "Australia/Eucla", - "Australia/Hobart", - "Australia/LHI", - "Australia/Lindeman", - "Australia/Lord_Howe", - "Australia/Melbourne", - "Australia/North", - "Australia/NSW", - "Australia/Perth", - "Australia/Queensland", - "Australia/South", - "Australia/Sydney", - "Australia/Tasmania", - "Australia/Victoria", - "Australia/West", - "Australia/Yancowinna", - "Brazil/Acre", - "Brazil/DeNoronha", - "Brazil/East", - "Brazil/West", - "Canada/Atlantic", - "Canada/Central", - "Canada/Eastern", - "Canada/East-Saskatchewan", - "Canada/Mountain", - "Canada/Newfoundland", - "Canada/Pacific", - "Canada/Saskatchewan", - "Canada/Yukon", - "Chile/Continental", - "Chile/EasterIsland", - "Etc/GMT", - "Etc/GMT0", - "Etc/GMT-0", - "Etc/GMT+0", - "Etc/GMT-1", - "Etc/GMT+1", - "Etc/GMT-10", - "Etc/GMT+10", - "Etc/GMT-11", - "Etc/GMT+11", - "Etc/GMT-12", - "Etc/GMT+12", - "Etc/GMT-13", - "Etc/GMT-14", - "Etc/GMT-2", - "Etc/GMT+2", - "Etc/GMT-3", - "Etc/GMT+3", - "Etc/GMT-4", - "Etc/GMT+4", - "Etc/GMT-5", - "Etc/GMT+5", - "Etc/GMT-6", - "Etc/GMT+6", - "Etc/GMT-7", - "Etc/GMT+7", - "Etc/GMT-8", - "Etc/GMT+8", - "Etc/GMT-9", - "Etc/GMT+9", - "Etc/Greenwich", - "Etc/UCT", - "Etc/Universal", - "Etc/UTC", - "Etc/Zulu", - "Europe/Amsterdam", - "Europe/Andorra", - "Europe/Astrakhan", - "Europe/Athens", - "Europe/Belfast", - "Europe/Belgrade", - "Europe/Berlin", - "Europe/Bratislava", - "Europe/Brussels", - "Europe/Bucharest", - "Europe/Budapest", - "Europe/Busingen", - "Europe/Chisinau", - "Europe/Copenhagen", - "Europe/Dublin", - "Europe/Gibraltar", - "Europe/Guernsey", - "Europe/Helsinki", - "Europe/Isle_of_Man", - "Europe/Istanbul", - "Europe/Jersey", - "Europe/Kaliningrad", - "Europe/Kiev", - "Europe/Kirov", - "Europe/Lisbon", - "Europe/Ljubljana", - "Europe/London", - "Europe/Luxembourg", - "Europe/Madrid", - "Europe/Malta", - "Europe/Mariehamn", - "Europe/Minsk", - "Europe/Monaco", - "Europe/Moscow", - "Europe/Nicosia", - "Europe/Oslo", - "Europe/Paris", - "Europe/Podgorica", - "Europe/Prague", - "Europe/Riga", - "Europe/Rome", - "Europe/Samara", - "Europe/San_Marino", - "Europe/Sarajevo", - "Europe/Saratov", - "Europe/Simferopol", - "Europe/Skopje", - "Europe/Sofia", - "Europe/Stockholm", - "Europe/Tallinn", - "Europe/Tirane", - "Europe/Tiraspol", - "Europe/Ulyanovsk", - "Europe/Uzhgorod", - "Europe/Vaduz", - "Europe/Vatican", - "Europe/Vienna", - "Europe/Vilnius", - "Europe/Volgograd", - "Europe/Warsaw", - "Europe/Zagreb", - "Europe/Zaporozhye", - "Europe/Zurich", - "Indian/Antananarivo", - "Indian/Chagos", - "Indian/Christmas", - "Indian/Cocos", - "Indian/Comoro", - "Indian/Kerguelen", - "Indian/Mahe", - "Indian/Maldives", - "Indian/Mauritius", - "Indian/Mayotte", - "Indian/Reunion", - "Mexico/BajaNorte", - "Mexico/BajaSur", - "Mexico/General", - "Pacific/Apia", - "Pacific/Auckland", - "Pacific/Bougainville", - "Pacific/Chatham", - "Pacific/Chuuk", - "Pacific/Easter", - "Pacific/Efate", - "Pacific/Enderbury", - "Pacific/Fakaofo", - "Pacific/Fiji", - "Pacific/Funafuti", - "Pacific/Galapagos", - "Pacific/Gambier", - "Pacific/Guadalcanal", - "Pacific/Guam", - "Pacific/Honolulu", - "Pacific/Johnston", - "Pacific/Kiritimati", - "Pacific/Kosrae", - "Pacific/Kwajalein", - "Pacific/Majuro", - "Pacific/Marquesas", - "Pacific/Midway", - "Pacific/Nauru", - "Pacific/Niue", - "Pacific/Norfolk", - "Pacific/Noumea", - "Pacific/Pago_Pago", - "Pacific/Palau", - "Pacific/Pitcairn", - "Pacific/Pohnpei", - "Pacific/Ponape", - "Pacific/Port_Moresby", - "Pacific/Rarotonga", - "Pacific/Saipan", - "Pacific/Samoa", - "Pacific/Tahiti", - "Pacific/Tarawa", - "Pacific/Tongatapu", - "Pacific/Truk", - "Pacific/Wake", - "Pacific/Wallis", - "Pacific/Yap", - "US/Alaska", - "US/Aleutian", - "US/Arizona", - "US/Central", - "US/Eastern", - "US/East-Indiana", - "US/Hawaii", - "US/Indiana-Starke", - "US/Michigan", - "US/Mountain", - "US/Pacific", - "US/Pacific-New", - "US/Samoa", - "CET", - "CST6CDT", - "Cuba", - "EET", - "Egypt", - "Eire", - "EST", - "EST5EDT", - "Factory", - "GB", - "GB-Eire", - "GMT", - "GMT0", - "GMT-0", - "GMT+0", - "Greenwich", - "Hongkong", - "HST", - "Iceland", - "Iran", - "Israel", - "Jamaica", - "Japan", - "Kwajalein", - "Libya", - "MET", - "MST", - "MST7MDT", - "Navajo", - "NZ", - "NZ-CHAT", - "Poland", - "Portugal", - "PRC", - "PST8PDT", - "ROC", - "ROK", - "Singapore", - "Turkey", - "UCT", - "Universal", - "UTC", - "WET", - "W-SU", - "Zulu" - ], - "userAgents": [ - "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML like Gecko) Chrome/28.0.1469.0 Safari/537.36", - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2869.0 Safari/537.36", - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3191.0 Safari/537.36", - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0", - "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0", - "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0", - "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.2; WOW64; Trident/5.0)", - "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko", - "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; MALNJS; rv:11.0) like Gecko", - "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36 OPR/47.0.2631.55", - "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.91 Safari/537.36 Vivaldi/1.92.917.39", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.49 Safari/537.36", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefox/25.0", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.56 (KHTML, like Gecko) Version/9.0 Safari/601.1.56", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Safari/602.1.50", - "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; en-us) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10", - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.4 (KHTML like Gecko) Chrome/22.0.1229.56 Safari/537.4", - "Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36", - "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/60.0.3112.78 Chrome/60.0.3112.78 Safari/537.36", - "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0", - "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.1", - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.166 Safari/537.36 OPR/20.0.1396.73172", - "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36 OPR/40.0.2308.62", - "Mozilla/5.0 (Linux; Android 8.0.0; Pixel XL Build/OPR6.170623.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.107 Mobile Safari/537.36", - "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch)", - "Opera/10.61 (J2ME/MIDP; Opera Mini/5.1.21219/19.999; en-US; rv:1.9.3a5) WebKit/534.5 Presto/2.6.30", - "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1", - "Mozilla/5.0 (Linux; Android 8.0.0; Pixel XL Build/OPR6.170623.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.107 Mobile Safari/537.36", - "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; DEVICE INFO) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Mobile Safari/537.36 Edge/12.0", - "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36", - "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36", - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14", - "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36", - "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36", - "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36", - "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0", - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" - ] -}`) diff --git a/vendor/github.com/Pallinder/go-randomdata/postalcodes.go b/vendor/github.com/Pallinder/go-randomdata/postalcodes.go deleted file mode 100644 index 88e4adf9..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/postalcodes.go +++ /dev/null @@ -1,244 +0,0 @@ -package randomdata - -import ( - "fmt" - "math" - "math/rand" - "strings" -) - -// Supported formats obtained from: -// * http://www.geopostcodes.com/GeoPC_Postal_codes_formats - -// PostalCode yields a random postal/zip code for the given 2-letter country code. -// -// These codes are not guaranteed to refer to actually locations. -// They merely follow the correct format as far as letters and digits goes. -// Where possible, the function enforces valid ranges of letters and digits. -func PostalCode(countrycode string) string { - switch strings.ToUpper(countrycode) { - case "LS", "MG", "IS", "OM", "PG": - return Digits(3) - - case "AM", "GE", "NZ", "NE", "NO", "PY", "ZA", "MZ", "SJ", "LI", "AL", - "BD", "CV", "GL": - return Digits(4) - - case "DZ", "BA", "KH", "DO", "EG", "EE", "GP", "GT", "ID", "IL", "JO", - "KW", "MQ", "MX", "LK", "SD", "TR", "UA", "US", "CR", "IQ", "KV", "MY", - "MN", "ME", "PK", "SM", "MA", "UY", "EH", "ZM": - return Digits(5) - - case "BY", "CN", "IN", "KZ", "KG", "NG", "RO", "RU", "SG", "TJ", "TM", "UZ", "VN": - return Digits(6) - - case "CL": - return Digits(7) - - case "IR": - return Digits(10) - - case "FO": - return "FO " + Digits(3) - - case "AF": - return BoundedDigits(2, 10, 43) + BoundedDigits(2, 1, 99) - - case "AU", "AT", "BE", "BG", "CY", "DK", "ET", "GW", "HU", "LR", "MK", "PH", - "CH", "TN", "VE": - return BoundedDigits(4, 1000, 9999) - - case "SV": - return "CP " + BoundedDigits(4, 1000, 9999) - - case "HT": - return "HT" + Digits(4) - - case "LB": - return Digits(4) + " " + Digits(4) - - case "LU": - return BoundedDigits(4, 6600, 6999) - - case "MD": - return "MD-" + BoundedDigits(4, 1000, 9999) - - case "HR": - return "HR-" + Digits(5) - - case "CU": - return "CP " + BoundedDigits(5, 10000, 99999) - - case "FI": - // Last digit is usually 0 but can, in some cases, be 1 or 5. - switch rand.Intn(2) { - case 0: - return Digits(4) + "0" - case 1: - return Digits(4) + "1" - } - - return Digits(4) + "5" - - case "FR", "GF", "PF", "YT", "MC", "RE", "BL", "MF", "PM", "RS", "TH": - return BoundedDigits(5, 10000, 99999) - - case "DE": - return BoundedDigits(5, 1000, 99999) - - case "GR": - return BoundedDigits(3, 100, 999) + " " + Digits(2) - - case "HN": - return "CM" + Digits(4) - - case "IT", "VA": - return BoundedDigits(5, 10, 99999) - - case "KE": - return BoundedDigits(5, 100, 99999) - - case "LA": - return BoundedDigits(5, 1000, 99999) - - case "MH": - return BoundedDigits(5, 96960, 96970) - - case "FM": - return "FM" + BoundedDigits(5, 96941, 96944) - - case "MM": - return BoundedDigits(2, 1, 14) + Digits(3) - - case "NP": - return BoundedDigits(5, 10700, 56311) - - case "NC": - return "98" + Digits(3) - - case "PW": - return "PW96940" - - case "PR": - return "PR " + Digits(5) - - case "SA": - return BoundedDigits(5, 10000, 99999) + "-" + BoundedDigits(4, 1000, 9999) - - case "ES": - return BoundedDigits(2, 1, 52) + BoundedDigits(3, 100, 999) - - case "WF": - return "986" + Digits(2) - - case "SZ": - return Letters(1) + Digits(3) - - case "BM": - return Letters(2) + Digits(2) - - case "AD": - return Letters(2) + Digits(3) - - case "BN", "AZ", "VG", "PE": - return Letters(2) + Digits(4) - - case "BB": - return Letters(2) + Digits(5) - - case "EC": - return Letters(2) + Digits(6) - - case "MT": - return Letters(3) + Digits(4) - - case "JM": - return "JM" + Letters(3) + Digits(2) - - case "AR": - return Letters(1) + Digits(4) + Letters(3) - - case "CA": - return Letters(1) + Digits(1) + Letters(1) + Digits(1) + Letters(1) + Digits(1) - - case "FK", "TC": - return Letters(4) + Digits(1) + Letters(2) - - case "GG", "IM", "JE", "GB": - return Letters(2) + Digits(2) + Letters(2) - - case "KY": - return Letters(2) + Digits(1) + "-" + Digits(4) - - case "JP": - return Digits(3) + "-" + Digits(4) - - case "LV", "SI": - return Letters(2) + "-" + Digits(4) - - case "LT": - return Letters(2) + "-" + Digits(5) - - case "SE", "TW": - return Digits(5) - - case "MV": - return Digits(2) + "-" + Digits(2) - - case "PL": - return Digits(2) + "-" + Digits(3) - - case "NI": - return Digits(3) + "-" + Digits(3) + "-" + Digits(1) - - case "KR": - return Digits(3) + "-" + Digits(3) - - case "PT": - return Digits(4) + "-" + Digits(3) - - case "NL": - return Digits(4) + Letters(2) - - case "BR": - return Digits(5) + "-" + Digits(3) - } - - return "" -} - -// Letters generates a string of N random leters (A-Z). -func Letters(letters int) string { - list := make([]byte, letters) - - for i := range list { - list[i] = byte(rand.Intn('Z'-'A') + 'A') - } - - return string(list) -} - -// Digits generates a string of N random digits, padded with zeros if necessary. -func Digits(digits int) string { - max := int(math.Pow10(digits)) - 1 - num := rand.Intn(max) - format := fmt.Sprintf("%%0%dd", digits) - return fmt.Sprintf(format, num) -} - -// BoundedDigits generates a string of N random digits, padded with zeros if necessary. -// The output is restricted to the given range. -func BoundedDigits(digits, low, high int) string { - if low > high { - low, high = high, low - } - - max := int(math.Pow10(digits)) - 1 - if high > max { - high = max - } - - num := rand.Intn(high-low+1) + low - format := fmt.Sprintf("%%0%dd", digits) - return fmt.Sprintf(format, num) -} diff --git a/vendor/github.com/Pallinder/go-randomdata/postalcodes_test.go b/vendor/github.com/Pallinder/go-randomdata/postalcodes_test.go deleted file mode 100644 index 96e621dd..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/postalcodes_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package randomdata - -import ( - "testing" -) - -var postalcodeTests = []struct { - Country string - Size int -}{ - {"PE", 6}, - {"FO", 6}, - {"AF", 4}, - {"DZ", 5}, - {"BY", 6}, - {"CL", 7}, - {"SZ", 4}, - {"BM", 4}, - {"AD", 5}, - {"BN", 6}, - {"BB", 7}, - {"MT", 7}, - {"JM", 7}, - {"AR", 8}, - {"CA", 6}, - {"FK", 7}, - {"GG", 6}, - {"NL", 6}, - {"BR", 9}, - {"KY", 8}, - {"JP", 8}, - {"LV", 7}, - {"LT", 8}, - {"MV", 5}, - {"NI", 9}, - {"PL", 6}, - {"PT", 8}, - {"KR", 7}, - {"TW", 5}, - {"MH", 5}, -} - -func TestPostalCode(t *testing.T) { - for _, pt := range postalcodeTests { - code := PostalCode(pt.Country) - - if len(code) == pt.Size { - continue - } - - t.Fatalf("Invalid length for country %q: Expected %d, have %d.", - pt.Country, pt.Size, len(code)) - } -} diff --git a/vendor/github.com/Pallinder/go-randomdata/random_data.go b/vendor/github.com/Pallinder/go-randomdata/random_data.go deleted file mode 100644 index 87ab0480..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/random_data.go +++ /dev/null @@ -1,376 +0,0 @@ -// Package randomdata implements a bunch of simple ways to generate (pseudo) random data -package randomdata - -import ( - "encoding/json" - "fmt" - "log" - "math/rand" - "net" - "strconv" - "strings" - "time" - "unicode" -) - -const ( - Male int = 0 - Female int = 1 - RandomGender int = 2 -) - -const ( - Small int = 0 - Large int = 1 -) - -const ( - FullCountry = 0 - TwoCharCountry = 1 - ThreeCharCountry = 2 -) - -const ( - DateInputLayout = "2006-01-02" - DateOutputLayout = "Monday 2 Jan 2006" -) - -type jsonContent struct { - Adjectives []string `json:"adjectives"` - Nouns []string `json:"nouns"` - FirstNamesFemale []string `json:"firstNamesFemale"` - FirstNamesMale []string `json:"firstNamesMale"` - LastNames []string `json:"lastNames"` - Domains []string `json:"domains"` - People []string `json:"people"` - StreetTypes []string `json:"streetTypes"` // Taken from https://github.com/tomharris/random_data/blob/master/lib/random_data/locations.rb - Paragraphs []string `json:"paragraphs"` // Taken from feedbooks.com - Countries []string `json:"countries"` // Fetched from the world bank at http://siteresources.worldbank.org/DATASTATISTICS/Resources/CLASS.XLS - CountriesThreeChars []string `json:"countriesThreeChars"` - CountriesTwoChars []string `json:"countriesTwoChars"` - Currencies []string `json:"currencies"` //https://github.com/OpenBookPrices/country-data - Cities []string `json:"cities"` - States []string `json:"states"` - StatesSmall []string `json:"statesSmall"` - Days []string `json:"days"` - Months []string `json:"months"` - FemaleTitles []string `json:"femaleTitles"` - MaleTitles []string `json:"maleTitles"` - Timezones []string `json:"timezones"` // https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - UserAgents []string `json:"userAgents"` // http://techpatterns.com/downloads/firefox/useragentswitcher.xml -} - -var jsonData = jsonContent{} - -func init() { - jsonData = jsonContent{} - - err := json.Unmarshal(data, &jsonData) - - if err != nil { - log.Fatal(err) - } -} - -func seedAndReturnRandom(n int) int { - rand.Seed(time.Now().UnixNano()) - return rand.Intn(n) -} - -func seedAndReturnRandomFloat() float64 { - rand.Seed(time.Now().UnixNano()) - return rand.Float64() -} - -// Returns a random part of a slice -func randomFrom(source []string) string { - return source[seedAndReturnRandom(len(source))] -} - -// Title returns a random title, gender decides the gender of the name -func Title(gender int) string { - var title = "" - switch gender { - case Male: - title = randomFrom(jsonData.MaleTitles) - break - case Female: - title = randomFrom(jsonData.FemaleTitles) - break - default: - rand.Seed(time.Now().UnixNano()) - title = FirstName(rand.Intn(2)) - break - } - return title -} - -// FirstName returns a random first name, gender decides the gender of the name -func FirstName(gender int) string { - var name = "" - switch gender { - case Male: - name = randomFrom(jsonData.FirstNamesMale) - break - case Female: - name = randomFrom(jsonData.FirstNamesFemale) - break - default: - rand.Seed(time.Now().UnixNano()) - name = FirstName(rand.Intn(2)) - break - } - return name -} - -// LastName returns a random last name -func LastName() string { - return randomFrom(jsonData.LastNames) -} - -// FullName returns a combination of FirstName LastName randomized, gender decides the gender of the name -func FullName(gender int) string { - return FirstName(gender) + " " + LastName() -} - -// Email returns a random email -func Email() string { - return strings.ToLower(FirstName(RandomGender)+LastName()) + StringNumberExt(1, "", 3) + "@" + randomFrom(jsonData.Domains) -} - -// Country returns a random country, countryStyle decides what kind of format the returned country will have -func Country(countryStyle int64) string { - country := "" - switch countryStyle { - - default: - - case FullCountry: - country = randomFrom(jsonData.Countries) - break - - case TwoCharCountry: - country = randomFrom(jsonData.CountriesTwoChars) - break - - case ThreeCharCountry: - country = randomFrom(jsonData.CountriesThreeChars) - break - } - return country -} - -// Currency returns a random currency under ISO 4217 format -func Currency() string { - return randomFrom(jsonData.Currencies) -} - -// City returns a random city -func City() string { - return randomFrom(jsonData.Cities) -} - -// State returns a random american state -func State(typeOfState int) string { - if typeOfState == Small { - return randomFrom(jsonData.StatesSmall) - } - return randomFrom(jsonData.States) -} - -// Street returns a random fake street name -func Street() string { - return fmt.Sprintf("%s %s", randomFrom(jsonData.People), randomFrom(jsonData.StreetTypes)) -} - -// Address returns an american style address -func Address() string { - return fmt.Sprintf("%d %s,\n%s, %s, %s", Number(100), Street(), City(), State(Small), PostalCode("US")) -} - -// Paragraph returns a random paragraph -func Paragraph() string { - return randomFrom(jsonData.Paragraphs) -} - -// Number returns a random number, if only one integer is supplied it is treated as the max value to return -// if a second argument is supplied it returns a number between (and including) the two numbers -func Number(numberRange ...int) int { - nr := 0 - rand.Seed(time.Now().UnixNano()) - if len(numberRange) > 1 { - nr = 1 - nr = seedAndReturnRandom(numberRange[1]-numberRange[0]) + numberRange[0] - } else { - nr = seedAndReturnRandom(numberRange[0]) - } - return nr -} - -func Decimal(numberRange ...int) float64 { - nr := 0.0 - rand.Seed(time.Now().UnixNano()) - if len(numberRange) > 1 { - nr = 1.0 - nr = seedAndReturnRandomFloat()*(float64(numberRange[1])-float64(numberRange[0])) + float64(numberRange[0]) - } else { - nr = seedAndReturnRandomFloat() * float64(numberRange[0]) - } - - if len(numberRange) > 2 { - sf := strconv.FormatFloat(nr, 'f', numberRange[2], 64) - nr, _ = strconv.ParseFloat(sf, 64) - } - return nr -} - -func StringNumberExt(numberPairs int, separator string, numberOfDigits int) string { - numberString := "" - - for i := 0; i < numberPairs; i++ { - for d := 0; d < numberOfDigits; d++ { - numberString += fmt.Sprintf("%d", Number(0, 9)) - } - - if i+1 != numberPairs { - numberString += separator - } - } - - return numberString -} - -// StringNumber returns a random number as a string -func StringNumber(numberPairs int, separator string) string { - return StringNumberExt(numberPairs, separator, 2) -} - -// StringSample returns a random string from a list of strings -func StringSample(stringList ...string) string { - str := "" - if len(stringList) > 0 { - str = stringList[Number(0, len(stringList))] - } - return str -} - -func Boolean() bool { - nr := seedAndReturnRandom(2) - return nr != 0 -} - -// Noun returns a random noun -func Noun() string { - return randomFrom(jsonData.Nouns) -} - -// Adjective returns a random adjective -func Adjective() string { - return randomFrom(jsonData.Adjectives) -} - -func uppercaseFirstLetter(word string) string { - a := []rune(word) - a[0] = unicode.ToUpper(a[0]) - return string(a) -} - -func lowercaseFirstLetter(word string) string { - a := []rune(word) - a[0] = unicode.ToLower(a[0]) - return string(a) -} - -// SillyName returns a silly name, useful for randomizing naming of things -func SillyName() string { - return uppercaseFirstLetter(Noun()) + Adjective() -} - -// IpV4Address returns a valid IPv4 address as string -func IpV4Address() string { - blocks := []string{} - for i := 0; i < 4; i++ { - number := seedAndReturnRandom(255) - blocks = append(blocks, strconv.Itoa(number)) - } - - return strings.Join(blocks, ".") -} - -// IpV6Address returns a valid IPv6 address as net.IP -func IpV6Address() string { - var ip net.IP - for i := 0; i < net.IPv6len; i++ { - number := uint8(seedAndReturnRandom(255)) - ip = append(ip, number) - } - return ip.String() -} - -// MacAddress returns an mac address string -func MacAddress() string { - blocks := []string{} - for i := 0; i < 6; i++ { - number := fmt.Sprintf("%02x", seedAndReturnRandom(255)) - blocks = append(blocks, number) - } - - return strings.Join(blocks, ":") -} - -// Day returns random day -func Day() string { - return randomFrom(jsonData.Days) -} - -// Month returns random month -func Month() string { - return randomFrom(jsonData.Months) -} - -// FullDate returns full date -func FullDate() string { - timestamp := time.Now() - day := Day() - month := Month() - year := timestamp.Year() - fullDate := day + " " + strconv.Itoa(Number(1, 30)) + " " + month[0:3] + " " + strconv.Itoa(year) - return fullDate -} - -// FullDateInRange returns a date string within a given range, given in the format "2006-01-02". -// If no argument is supplied it will return the result of randomdata.FullDate(). -// If only one argument is supplied it is treated as the max date to return. -// If a second argument is supplied it returns a date between (and including) the two dates. -// Returned date is in format "Monday 2 Jan 2006". -func FullDateInRange(dateRange ...string) string { - var ( - min time.Time - max time.Time - duration int - dateString string - ) - if len(dateRange) == 1 { - max, _ = time.Parse(DateInputLayout, dateRange[0]) - } else if len(dateRange) == 2 { - min, _ = time.Parse(DateInputLayout, dateRange[0]) - max, _ = time.Parse(DateInputLayout, dateRange[1]) - } - if !max.IsZero() && max.After(min) { - duration = Number(int(max.Sub(min))) * -1 - dateString = max.Add(time.Duration(duration)).Format(DateOutputLayout) - } else if !max.IsZero() && !max.After(min) { - dateString = max.Format(DateOutputLayout) - } else { - dateString = FullDate() - } - return dateString -} - -func Timezone() string { - return randomFrom(jsonData.Timezones) -} - -func UserAgentString() string { - return randomFrom(jsonData.UserAgents) -} diff --git a/vendor/github.com/Pallinder/go-randomdata/random_data_example_test.go b/vendor/github.com/Pallinder/go-randomdata/random_data_example_test.go deleted file mode 100644 index bdcf9f00..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/random_data_example_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package randomdata - -import "fmt" - -func ExampleRandomdata() { - - // Print a male first name - fmt.Println(FirstName(Male)) - - // Print a female first name - fmt.Println(FirstName(Female)) - - // Print a last name - fmt.Println(LastName()) - - // Print a male name - fmt.Println(FullName(Male)) - - // Print a female name - fmt.Println(FullName(Female)) - - // Print a name with random gender - fmt.Println(FullName(RandomGender)) - - // Print a random email - fmt.Println(Email()) - - // Print a country with full text representation - fmt.Println(Country(FullCountry)) - - // Print a country using ISO 3166-1 alpha-3 - fmt.Println(Country(ThreeCharCountry)) - - // Print a country using ISO 3166-1 alpha-2 - fmt.Println(Country(TwoCharCountry)) - - // Print a currency using ISO 4217 - fmt.Println(Currency()) - - // Print the name of a random city - fmt.Println(City()) - - // Print the name of a random american state - fmt.Println(State(Large)) - - // Print the name of a random american state using two letters - fmt.Println(State(Small)) - - // Print a random number >= 10 and <= 20 - fmt.Println(Number(10, 20)) - - // Print a number >= 0 and <= 20 - fmt.Println(Number(20)) - - // Print a random float >= 0 and <= 20 with decimal point 3 - fmt.Println(Decimal(0, 20, 3)) - - // Print a random float >= 10 and <= 20 - fmt.Println(Decimal(10, 20)) - - // Print a random float >= 0 and <= 20 - fmt.Println(Decimal(20)) - - // Print a paragraph - fmt.Println(Paragraph()) - - // Print a random bool - fmt.Println(Boolean()) - - // Print a random postalcode from Sweden - fmt.Println(PostalCode("SE")) - - // Print a random american sounding street name - fmt.Println(Street()) - - // Print a random american address - fmt.Println(Address()) - - // Print a random string of numbers - fmt.Println(StringNumber(2, "-")) - - // Print a set of 2 random 3-Digits numbers as a string - fmt.Println(StringNumberExt(2, "-", 3)) - - // Print a random IPv4 address - fmt.Println(IpV4Address()) - - // Print a random IPv6 address - fmt.Println(IpV6Address()) - - // Print a random day - fmt.Println(Day()) - - // Print a month - fmt.Println(Month()) - - // Print full date - fmt.Println(FullDate()) - -} diff --git a/vendor/github.com/Pallinder/go-randomdata/random_data_test.go b/vendor/github.com/Pallinder/go-randomdata/random_data_test.go deleted file mode 100644 index e2962a40..00000000 --- a/vendor/github.com/Pallinder/go-randomdata/random_data_test.go +++ /dev/null @@ -1,424 +0,0 @@ -package randomdata - -import ( - "bytes" - "net" - "reflect" - "regexp" - "strconv" - "strings" - "testing" - "time" -) - -func TestRandomStringDigits(t *testing.T) { - t.Log("TestRandomStringDigits") - - if len(StringNumber(2, "-")) != 5 { - t.Fatal("Wrong length returned") - } - - if len(StringNumber(2, "")) != 4 { - t.Fatal("Wrong length returned") - } - - if len(StringNumberExt(3, "/", 3)) != 11 { - t.Fatal("Wrong length returned") - } - - if len(StringNumberExt(3, "", 3)) != 9 { - t.Fatal("Wrong length returned") - } -} - -func TestFirstName(t *testing.T) { - t.Log("TestFirstName") - firstNameMale := FirstName(Male) - firstNameFemale := FirstName(Female) - randomName := FirstName(RandomGender) - - if !findInSlice(jsonData.FirstNamesMale, firstNameMale) { - t.Error("firstNameMale empty or not in male names") - } - - if !findInSlice(jsonData.FirstNamesFemale, firstNameFemale) { - t.Error("firstNameFemale empty or not in female names") - } - - if randomName == "" { - t.Error("randomName empty") - } - -} - -func TestLastName(t *testing.T) { - t.Log("TestLastName") - lastName := LastName() - - if !findInSlice(jsonData.LastNames, lastName) { - t.Error("lastName empty or not in slice") - } -} - -func TestFullName(t *testing.T) { - t.Log("TestFullName") - - fullNameMale := FullName(Male) - fullNameFemale := FullName(Female) - fullNameRandom := FullName(RandomGender) - - maleSplit := strings.Fields(fullNameMale) - femaleSplit := strings.Fields(fullNameFemale) - randomSplit := strings.Fields(fullNameRandom) - - if len(maleSplit) == 0 { - t.Error("Failed on full name male") - } - - if !findInSlice(jsonData.FirstNamesMale, maleSplit[0]) { - t.Error("Couldnt find maleSplit first name in firstNamesMale") - } - - if !findInSlice(jsonData.LastNames, maleSplit[1]) { - t.Error("Couldnt find maleSplit last name in lastNames") - } - - if len(femaleSplit) == 0 { - t.Error("Failed on full name female") - } - - if !findInSlice(jsonData.FirstNamesFemale, femaleSplit[0]) { - t.Error("Couldnt find femaleSplit first name in firstNamesFemale") - } - - if !findInSlice(jsonData.LastNames, femaleSplit[1]) { - t.Error("Couldnt find femaleSplit last name in lastNames") - } - - if len(randomSplit) == 0 { - t.Error("Failed on full name random") - } - - if !findInSlice(jsonData.FirstNamesMale, randomSplit[0]) && !findInSlice(jsonData.FirstNamesFemale, randomSplit[0]) { - t.Error("Couldnt find randomSplit first name in either firstNamesMale or firstNamesFemale") - } - -} - -func TestEmail(t *testing.T) { - t.Log("TestEmail") - email := Email() - - if email == "" { - t.Error("Failed to generate email with content") - } - -} - -func TestCountry(t *testing.T) { - t.Log("TestCountry") - countryFull := Country(FullCountry) - countryTwo := Country(TwoCharCountry) - countryThree := Country(ThreeCharCountry) - - if len(countryThree) < 3 { - t.Error("countryThree < 3 chars") - } - - if !findInSlice(jsonData.Countries, countryFull) { - t.Error("Couldnt find country in countries") - } - - if !findInSlice(jsonData.CountriesTwoChars, countryTwo) { - t.Error("Couldnt find country with two chars in countriesTwoChars") - } - - if !findInSlice(jsonData.CountriesThreeChars, countryThree) { - t.Error("Couldnt find country with three chars in countriesThreeChars") - } -} - -func TestCurrency(t *testing.T) { - t.Log("TestCurrency") - if !findInSlice(jsonData.Currencies, Currency()) { - t.Error("Could not find currency in currencies") - } -} - -func TestCity(t *testing.T) { - t.Log("TestCity") - city := City() - - if !findInSlice(jsonData.Cities, city) { - t.Error("Couldnt find city in cities") - } -} - -func TestParagraph(t *testing.T) { - t.Log("TestParagraph") - paragraph := Paragraph() - - if !findInSlice(jsonData.Paragraphs, paragraph) { - t.Error("Couldnt find paragraph in paragraphs") - } -} - -func TestBool(t *testing.T) { - t.Log("TestBool") - booleanVal := Boolean() - if booleanVal != true && booleanVal != false { - t.Error("Bool was wrong format") - } -} - -func TestState(t *testing.T) { - t.Log("TestState") - stateValSmall := State(Small) - stateValLarge := State(Large) - - if !findInSlice(jsonData.StatesSmall, stateValSmall) { - t.Error("Couldnt find small state name in states") - } - - if !findInSlice(jsonData.States, stateValLarge) { - t.Error("Couldnt find state name in states") - } - -} - -func TestNoun(t *testing.T) { - if len(jsonData.Nouns) == 0 { - t.Error("Nouns is empty") - } - - noun := Noun() - - if !findInSlice(jsonData.Nouns, noun) { - t.Error("Couldnt find noun in json data") - } -} - -func TestAdjective(t *testing.T) { - if len(jsonData.Adjectives) == 0 { - t.Error("Adjectives array is empty") - } - - adjective := Adjective() - - if !findInSlice(jsonData.Adjectives, adjective) { - t.Error("Couldnt find noun in json data") - } -} - -func TestSillyName(t *testing.T) { - sillyName := SillyName() - - if len(sillyName) == 0 { - t.Error("Couldnt generate a silly name") - } -} - -func TestIpV4Address(t *testing.T) { - ipAddress := IpV4Address() - - ipBlocks := strings.Split(ipAddress, ".") - - if len(ipBlocks) < 0 || len(ipBlocks) > 4 { - t.Error("Invalid generated IP address") - } - - for _, blockString := range ipBlocks { - blockNumber, err := strconv.Atoi(blockString) - - if err != nil { - t.Error("Error while testing IpV4Address(): " + err.Error()) - } - - if blockNumber < 0 || blockNumber > 255 { - t.Error("Invalid generated IP address") - } - } -} - -func TestIpV6Address(t *testing.T) { - ipAddress := net.ParseIP(IpV6Address()) - - if len(ipAddress) != net.IPv6len { - t.Errorf("Invalid generated IPv6 address %v", ipAddress) - } - roundTripIP := net.ParseIP(ipAddress.String()) - if roundTripIP == nil || !bytes.Equal(ipAddress, roundTripIP) { - t.Errorf("Invalid generated IPv6 address %v", ipAddress) - } -} - -func TestMacAddress(t *testing.T) { - t.Log("MacAddress") - - mac := MacAddress() - if len(mac) != 17 { - t.Errorf("Invalid generated Mac address %v", mac) - } - - if !regexp.MustCompile(`([0-9a-fa-f]{2}[:-]){5}([0-9a-fa-f]{2})`).MatchString(mac) { - t.Errorf("Invalid generated Mac address %v", mac) - } -} - -func TestDecimal(t *testing.T) { - d := Decimal(2, 4, 3) - if !(d >= 2 && d <= 4) { - t.Error("Invalid generate range") - } - - ds := strings.Split(strconv.FormatFloat(d, 'f', 3, 64), ".") - if len(ds[1]) != 3 { - t.Error("Invalid floating point") - } -} - -func TestDay(t *testing.T) { - t.Log("TestDay") - day := Day() - - if !findInSlice(jsonData.Days, day) { - t.Error("Couldnt find day in days") - } -} - -func TestMonth(t *testing.T) { - t.Log("TestMonth") - month := Month() - - if !findInSlice(jsonData.Months, month) { - t.Error("Couldnt find month in months") - } -} - -func TestStringSample(t *testing.T) { - t.Log("TestStringSample") - list := []string{"str1", "str2", "str3"} - str := StringSample(list...) - if reflect.TypeOf(str).String() != "string" { - t.Error("Didn't get a string object") - } - if !findInSlice(list, str) { - t.Error("Didn't get string from sample list") - } -} - -func TestStringSampleEmptyList(t *testing.T) { - t.Log("TestStringSample") - str := StringSample() - if reflect.TypeOf(str).String() != "string" { - t.Error("Didn't get a string object") - } - if str != "" { - t.Error("Didn't get empty string for empty sample list") - } -} - -func TestFullDate(t *testing.T) { - t.Log("TestFullDate") - fulldateOne := FullDate() - fulldateTwo := FullDate() - - if fulldateOne == fulldateTwo { - t.Error("Invalid random full date") - } -} - -func TestFullDateInRangeNoArgs(t *testing.T) { - t.Log("TestFullDateInRangeNoArgs") - fullDate := FullDateInRange() - _, err := time.Parse(DateOutputLayout, fullDate) - - if err != nil { - t.Error("Didn't get valid date format.") - } -} - -func TestFullDateInRangeOneArg(t *testing.T) { - t.Log("TestFullDateInRangeOneArg") - maxDate, _ := time.Parse(DateInputLayout, "2016-12-31") - for i := 0; i < 100000; i++ { - fullDate := FullDateInRange("2016-12-31") - d, err := time.Parse(DateOutputLayout, fullDate) - - if err != nil { - t.Error("Didn't get valid date format.") - } - - if d.After(maxDate) { - t.Error("Random date didn't match specified max date.") - } - } -} - -func TestFullDateInRangeTwoArgs(t *testing.T) { - t.Log("TestFullDateInRangeTwoArgs") - minDate, _ := time.Parse(DateInputLayout, "2016-01-01") - maxDate, _ := time.Parse(DateInputLayout, "2016-12-31") - for i := 0; i < 100000; i++ { - fullDate := FullDateInRange("2016-01-01", "2016-12-31") - d, err := time.Parse(DateOutputLayout, fullDate) - - if err != nil { - t.Error("Didn't get valid date format.") - } - - if d.After(maxDate) { - t.Error("Random date didn't match specified max date.") - } - - if d.Before(minDate) { - t.Error("Random date didn't match specified min date.") - } - } -} - -func TestFullDateInRangeSwappedArgs(t *testing.T) { - t.Log("TestFullDateInRangeSwappedArgs") - wrongMaxDate, _ := time.Parse(DateInputLayout, "2016-01-01") - fullDate := FullDateInRange("2016-12-31", "2016-01-01") - d, err := time.Parse(DateOutputLayout, fullDate) - - if err != nil { - t.Error("Didn't get valid date format.") - } - - if d != wrongMaxDate { - t.Error("Didn't return min date.") - } -} - -func TestTimezone(t *testing.T) { - t.Log("TestTimezone") - timezone := Timezone() - - if !findInSlice(jsonData.Timezones, timezone) { - t.Errorf("Couldnt find timezone in timezones: %v", timezone) - } -} - -func TestUserAgentString(t *testing.T) { - t.Log("UserAgentString") - - ua := UserAgentString() - if len(ua) == 0 { - t.Error("Empty User Agent String") - } - - if !regexp.MustCompile(`^[a-zA-Z]+\/[0-9]+.[0-9]+\ \(.*\).*$`).MatchString(ua) { - t.Errorf("Invalid generated User Agent String: %v", ua) - } -} - -func findInSlice(source []string, toFind string) bool { - for _, text := range source { - if text == toFind { - return true - } - } - return false -} diff --git a/vendor/github.com/andreyvit/diff/.gitignore b/vendor/github.com/andreyvit/diff/.gitignore deleted file mode 100644 index daf913b1..00000000 --- a/vendor/github.com/andreyvit/diff/.gitignore +++ /dev/null @@ -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 diff --git a/vendor/github.com/andreyvit/diff/LICENSE b/vendor/github.com/andreyvit/diff/LICENSE deleted file mode 100644 index 05b98e1f..00000000 --- a/vendor/github.com/andreyvit/diff/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 Andrey Tarantsov - -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. diff --git a/vendor/github.com/andreyvit/diff/README.md b/vendor/github.com/andreyvit/diff/README.md deleted file mode 100644 index 5b52fea8..00000000 --- a/vendor/github.com/andreyvit/diff/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# diff - -Quick'n'easy string diffing functions for Golang based on [github.com/sergi/go-diff](https://github.com/sergi/go-diff). Mainly for diffing strings in tests. - -See [the docs on GoDoc](https://godoc.org/github.com/andreyvit/diff). - -Get it: - - go get -u github.com/andreyvit/diff - -Example: - - import ( - "strings" - "testing" - "github.com/andreyvit/diff" - ) - - const expected = ` - ... - ` - - func TestFoo(t *testing.T) { - actual := Foo(...) - if a, e := strings.TrimSpace(actual), strings.TrimSpace(expected); a != e { - t.Errorf("Result not as expected:\n%v", diff.LineDiff(e, a)) - } - } diff --git a/vendor/github.com/andreyvit/diff/diff.go b/vendor/github.com/andreyvit/diff/diff.go deleted file mode 100644 index 12953c83..00000000 --- a/vendor/github.com/andreyvit/diff/diff.go +++ /dev/null @@ -1,128 +0,0 @@ -package diff - -import ( - "bytes" - "strings" - - "github.com/sergi/go-diff/diffmatchpatch" -) - -func diff(a, b string) []diffmatchpatch.Diff { - dmp := diffmatchpatch.New() - diffs := dmp.DiffMain(a, b, true) - if len(diffs) > 2 { - diffs = dmp.DiffCleanupSemantic(diffs) - diffs = dmp.DiffCleanupEfficiency(diffs) - } - return diffs -} - -// CharacterDiff returns an inline diff between the two strings, using (++added++) and (~~deleted~~) markup. -func CharacterDiff(a, b string) string { - return diffsToString(diff(a, b)) -} - -func diffsToString(diffs []diffmatchpatch.Diff) string { - var buff bytes.Buffer - for _, diff := range diffs { - text := diff.Text - switch diff.Type { - case diffmatchpatch.DiffInsert: - buff.WriteString("(++") - buff.WriteString(text) - buff.WriteString("++)") - case diffmatchpatch.DiffDelete: - buff.WriteString("(~~") - buff.WriteString(text) - buff.WriteString("~~)") - case diffmatchpatch.DiffEqual: - buff.WriteString(text) - } - } - return buff.String() -} - -// LineDiff returns a normal linewise diff between the two given strings. -func LineDiff(a, b string) string { - return strings.Join(LineDiffAsLines(a, b), "\n") -} - -// LineDiffAsLines returns the lines of a linewise diff between the two given strings. -func LineDiffAsLines(a, b string) []string { - return diffsToPatchLines(diff(a, b)) -} - -type patchBuilder struct { - output []string - oldLines []string - newLines []string - newLineBuffer bytes.Buffer - oldLineBuffer bytes.Buffer -} - -func (b *patchBuilder) AddCharacters(text string, op diffmatchpatch.Operation) { - if op == diffmatchpatch.DiffInsert || op == diffmatchpatch.DiffEqual { - b.newLineBuffer.WriteString(text) - } - if op == diffmatchpatch.DiffDelete || op == diffmatchpatch.DiffEqual { - b.oldLineBuffer.WriteString(text) - } -} -func (b *patchBuilder) AddNewline(op diffmatchpatch.Operation) { - oldLine := b.oldLineBuffer.String() - newLine := b.newLineBuffer.String() - - if op == diffmatchpatch.DiffEqual && (oldLine == newLine) { - b.FlushChunk() - b.output = append(b.output, " "+newLine) - b.oldLineBuffer.Reset() - b.newLineBuffer.Reset() - } else { - if op == diffmatchpatch.DiffDelete || op == diffmatchpatch.DiffEqual { - b.oldLines = append(b.oldLines, "-"+oldLine) - b.oldLineBuffer.Reset() - } - if op == diffmatchpatch.DiffInsert || op == diffmatchpatch.DiffEqual { - b.newLines = append(b.newLines, "+"+newLine) - b.newLineBuffer.Reset() - } - } -} -func (b *patchBuilder) FlushChunk() { - if b.oldLines != nil { - b.output = append(b.output, b.oldLines...) - b.oldLines = nil - } - if b.newLines != nil { - b.output = append(b.output, b.newLines...) - b.newLines = nil - } -} -func (b *patchBuilder) Flush() { - if b.oldLineBuffer.Len() > 0 && b.newLineBuffer.Len() > 0 { - b.AddNewline(diffmatchpatch.DiffEqual) - } else if b.oldLineBuffer.Len() > 0 { - b.AddNewline(diffmatchpatch.DiffDelete) - } else if b.newLineBuffer.Len() > 0 { - b.AddNewline(diffmatchpatch.DiffInsert) - } - b.FlushChunk() -} - -func diffsToPatchLines(diffs []diffmatchpatch.Diff) []string { - b := new(patchBuilder) - b.output = make([]string, 0, len(diffs)) - - for _, diff := range diffs { - lines := strings.Split(diff.Text, "\n") - for idx, line := range lines { - if idx > 0 { - b.AddNewline(diff.Type) - } - b.AddCharacters(line, diff.Type) - } - } - - b.Flush() - return b.output -} diff --git a/vendor/github.com/andreyvit/diff/diff_test.go b/vendor/github.com/andreyvit/diff/diff_test.go deleted file mode 100644 index edd1699e..00000000 --- a/vendor/github.com/andreyvit/diff/diff_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package diff - -import ( - "testing" -) - -func Test_CharacterDiff_NoChanges(t *testing.T) { - actual := CharacterDiff("abc", "abc") - expected := "abc" - if actual != expected { - t.Errorf("Got %#v instead of %#v", actual, expected) - } -} - -func Test_CharacterDiff_SomeChanges(t *testing.T) { - actual := CharacterDiff("abc", "abdef") - expected := "ab(~~c~~)(++def++)" - if actual != expected { - t.Errorf("Got %#v instead of expected %#v", actual, expected) - } -} - -func Test_LineDiff_NoChanges(t *testing.T) { - o(t, "abc", "abc", " abc") -} - -func Test_LineDiff_EverythingChanged(t *testing.T) { - o(t, "abc", "def", "-abc\n+def") -} - -func Test_LineDiff_AddedLine(t *testing.T) { - o(t, "abc\nxyz", "abc\ndef\nxyz", " abc\n+def\n xyz") -} - -func Test_LineDiff_AddedMultipleLines(t *testing.T) { - o(t, "abc\nxyz", "abc\ndef\nghi\njkl\nxyz", " abc\n+def\n+ghi\n+jkl\n xyz") -} - -func Test_LineDiff_DeletedLine(t *testing.T) { - o(t, "abc\ndef\nxyz", "abc\nxyz", " abc\n-def\n xyz") -} - -func Test_LineDiff_DeletedMultipleLines(t *testing.T) { - o(t, "abc\ndef\nghi\njkl\nxyz", "abc\nxyz", " abc\n-def\n-ghi\n-jkl\n xyz") -} - -func Test_LineDiff_ReplacedLine(t *testing.T) { - o(t, "abc\ndef\nxyz", "abc\nghi\nxyz", " abc\n-def\n+ghi\n xyz") -} - -func Test_LineDiff_ReplacedMultipleLines(t *testing.T) { - o(t, "abc\ndef\nghi\nxyz", "abc\njkl\nnop\nxyz", " abc\n-def\n-ghi\n+jkl\n+nop\n xyz") -} - -func Test_LineDiff_ReplacedPartOfLine(t *testing.T) { - o(t, "abc\ndef\nxyz", "abc\ndxf\nxyz", " abc\n-def\n+dxf\n xyz") -} - -func Test_LineDiff_ReplacedPartsOfMultipleConsecutiveLines(t *testing.T) { - o(t, "abc\ndef\nghi\njkl\nxyz", "abc\ndxf\nghix\nxjkl\nxyz", " abc\n-def\n-ghi\n-jkl\n+dxf\n+ghix\n+xjkl\n xyz") -} - -func Test_LineDiff_ReplacedTrailingPartOfLastLine(t *testing.T) { - o(t, "abc\ndef\nxyz", "abc\ndef\nxyzuv", " abc\n def\n-xyz\n+xyzuv") -} - -func o(t *testing.T, a, b, expected string) { - actual := LineDiff(a, b) - if actual != expected { - t.Logf("Actual:\n%v\n\nExpected:\n%v", actual, expected) - t.Errorf("Got %#v instead of expected %#v", actual, expected) - } -} diff --git a/vendor/github.com/andreyvit/diff/doc.go b/vendor/github.com/andreyvit/diff/doc.go deleted file mode 100644 index 98e24708..00000000 --- a/vendor/github.com/andreyvit/diff/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// diff provides quick and easy string diffing functions based on github.com/sergi/go-diff, mainly for diffing strings in tests -package diff diff --git a/vendor/github.com/andreyvit/diff/trim.go b/vendor/github.com/andreyvit/diff/trim.go deleted file mode 100644 index 87871f99..00000000 --- a/vendor/github.com/andreyvit/diff/trim.go +++ /dev/null @@ -1,19 +0,0 @@ -package diff - -import ( - "strings" -) - -// TrimLines applies TrimSpace to each string in the given array. -func TrimLines(input []string) []string { - result := make([]string, 0, len(input)) - for _, el := range input { - result = append(result, strings.TrimSpace(el)) - } - return result -} - -// TrimLinesInString applies TrimSpace to each line in the given string, and returns the new trimmed string. Empty lines are not removed. -func TrimLinesInString(input string) string { - return strings.Join(TrimLines(strings.Split(strings.TrimSpace(input), "\n")), "\n") -} diff --git a/vendor/github.com/fsnotify/fsnotify/.editorconfig b/vendor/github.com/fsnotify/fsnotify/.editorconfig deleted file mode 100644 index ba49e3c2..00000000 --- a/vendor/github.com/fsnotify/fsnotify/.editorconfig +++ /dev/null @@ -1,5 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 diff --git a/vendor/github.com/fsnotify/fsnotify/.github/ISSUE_TEMPLATE.md b/vendor/github.com/fsnotify/fsnotify/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 4ad1aed8..00000000 --- a/vendor/github.com/fsnotify/fsnotify/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,11 +0,0 @@ -Before reporting an issue, please ensure you are using the latest release of fsnotify. - -### Which operating system (GOOS) and version are you using? - -Linux: lsb_release -a -macOS: sw_vers -Windows: systeminfo | findstr /B /C:OS - -### Please describe the issue that occurred. - -### Are you able to reproduce the issue? Please provide steps to reproduce and a code sample if possible. diff --git a/vendor/github.com/fsnotify/fsnotify/.github/PULL_REQUEST_TEMPLATE.md b/vendor/github.com/fsnotify/fsnotify/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 64ddf7ce..00000000 --- a/vendor/github.com/fsnotify/fsnotify/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,8 +0,0 @@ -#### What does this pull request do? - - -#### Where should the reviewer start? - - -#### How should this be manually tested? - diff --git a/vendor/github.com/fsnotify/fsnotify/.gitignore b/vendor/github.com/fsnotify/fsnotify/.gitignore deleted file mode 100644 index 4cd0cbaf..00000000 --- a/vendor/github.com/fsnotify/fsnotify/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -# Setup a Global .gitignore for OS and editor generated files: -# https://help.github.com/articles/ignoring-files -# git config --global core.excludesfile ~/.gitignore_global - -.vagrant -*.sublime-project diff --git a/vendor/github.com/fsnotify/fsnotify/.travis.yml b/vendor/github.com/fsnotify/fsnotify/.travis.yml deleted file mode 100644 index 981d1bb8..00000000 --- a/vendor/github.com/fsnotify/fsnotify/.travis.yml +++ /dev/null @@ -1,30 +0,0 @@ -sudo: false -language: go - -go: - - 1.8.x - - 1.9.x - - tip - -matrix: - allow_failures: - - go: tip - fast_finish: true - -before_script: - - go get -u github.com/golang/lint/golint - -script: - - go test -v --race ./... - -after_script: - - test -z "$(gofmt -s -l -w . | tee /dev/stderr)" - - test -z "$(golint ./... | tee /dev/stderr)" - - go vet ./... - -os: - - linux - - osx - -notifications: - email: false diff --git a/vendor/github.com/fsnotify/fsnotify/AUTHORS b/vendor/github.com/fsnotify/fsnotify/AUTHORS deleted file mode 100644 index 5ab5d41c..00000000 --- a/vendor/github.com/fsnotify/fsnotify/AUTHORS +++ /dev/null @@ -1,52 +0,0 @@ -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# You can update this list using the following command: -# -# $ git shortlog -se | awk '{print $2 " " $3 " " $4}' - -# Please keep the list sorted. - -Aaron L -Adrien Bustany -Amit Krishnan -Anmol Sethi -Bjørn Erik Pedersen -Bruno Bigras -Caleb Spare -Case Nelson -Chris Howey -Christoffer Buchholz -Daniel Wagner-Hall -Dave Cheney -Evan Phoenix -Francisco Souza -Hari haran -John C Barstow -Kelvin Fo -Ken-ichirou MATSUZAWA -Matt Layher -Nathan Youngman -Nickolai Zeldovich -Patrick -Paul Hammond -Pawel Knap -Pieter Droogendijk -Pursuit92 -Riku Voipio -Rob Figueiredo -Rodrigo Chiossi -Slawek Ligus -Soge Zhang -Tiffany Jernigan -Tilak Sharma -Tom Payne -Travis Cline -Tudor Golubenco -Vahe Khachikyan -Yukang -bronze1man -debrando -henrikedwards -铁哥 diff --git a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md deleted file mode 100644 index be4d7ea2..00000000 --- a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md +++ /dev/null @@ -1,317 +0,0 @@ -# Changelog - -## v1.4.7 / 2018-01-09 - -* BSD/macOS: Fix possible deadlock on closing the watcher on kqueue (thanks @nhooyr and @glycerine) -* Tests: Fix missing verb on format string (thanks @rchiossi) -* Linux: Fix deadlock in Remove (thanks @aarondl) -* Linux: Watch.Add improvements (avoid race, fix consistency, reduce garbage) (thanks @twpayne) -* Docs: Moved FAQ into the README (thanks @vahe) -* Linux: Properly handle inotify's IN_Q_OVERFLOW event (thanks @zeldovich) -* Docs: replace references to OS X with macOS - -## v1.4.2 / 2016-10-10 - -* Linux: use InotifyInit1 with IN_CLOEXEC to stop leaking a file descriptor to a child process when using fork/exec [#178](https://github.com/fsnotify/fsnotify/pull/178) (thanks @pattyshack) - -## v1.4.1 / 2016-10-04 - -* Fix flaky inotify stress test on Linux [#177](https://github.com/fsnotify/fsnotify/pull/177) (thanks @pattyshack) - -## v1.4.0 / 2016-10-01 - -* add a String() method to Event.Op [#165](https://github.com/fsnotify/fsnotify/pull/165) (thanks @oozie) - -## v1.3.1 / 2016-06-28 - -* Windows: fix for double backslash when watching the root of a drive [#151](https://github.com/fsnotify/fsnotify/issues/151) (thanks @brunoqc) - -## v1.3.0 / 2016-04-19 - -* Support linux/arm64 by [patching](https://go-review.googlesource.com/#/c/21971/) x/sys/unix and switching to to it from syscall (thanks @suihkulokki) [#135](https://github.com/fsnotify/fsnotify/pull/135) - -## v1.2.10 / 2016-03-02 - -* Fix golint errors in windows.go [#121](https://github.com/fsnotify/fsnotify/pull/121) (thanks @tiffanyfj) - -## v1.2.9 / 2016-01-13 - -kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsnotify/pull/111) (thanks @bep) - -## v1.2.8 / 2015-12-17 - -* kqueue: fix race condition in Close [#105](https://github.com/fsnotify/fsnotify/pull/105) (thanks @djui for reporting the issue and @ppknap for writing a failing test) -* inotify: fix race in test -* enable race detection for continuous integration (Linux, Mac, Windows) - -## v1.2.5 / 2015-10-17 - -* inotify: use epoll_create1 for arm64 support (requires Linux 2.6.27 or later) [#100](https://github.com/fsnotify/fsnotify/pull/100) (thanks @suihkulokki) -* inotify: fix path leaks [#73](https://github.com/fsnotify/fsnotify/pull/73) (thanks @chamaken) -* kqueue: watch for rename events on subdirectories [#83](https://github.com/fsnotify/fsnotify/pull/83) (thanks @guotie) -* kqueue: avoid infinite loops from symlinks cycles [#101](https://github.com/fsnotify/fsnotify/pull/101) (thanks @illicitonion) - -## v1.2.1 / 2015-10-14 - -* kqueue: don't watch named pipes [#98](https://github.com/fsnotify/fsnotify/pull/98) (thanks @evanphx) - -## v1.2.0 / 2015-02-08 - -* inotify: use epoll to wake up readEvents [#66](https://github.com/fsnotify/fsnotify/pull/66) (thanks @PieterD) -* inotify: closing watcher should now always shut down goroutine [#63](https://github.com/fsnotify/fsnotify/pull/63) (thanks @PieterD) -* kqueue: close kqueue after removing watches, fixes [#59](https://github.com/fsnotify/fsnotify/issues/59) - -## v1.1.1 / 2015-02-05 - -* inotify: Retry read on EINTR [#61](https://github.com/fsnotify/fsnotify/issues/61) (thanks @PieterD) - -## v1.1.0 / 2014-12-12 - -* kqueue: rework internals [#43](https://github.com/fsnotify/fsnotify/pull/43) - * add low-level functions - * only need to store flags on directories - * less mutexes [#13](https://github.com/fsnotify/fsnotify/issues/13) - * done can be an unbuffered channel - * remove calls to os.NewSyscallError -* More efficient string concatenation for Event.String() [#52](https://github.com/fsnotify/fsnotify/pull/52) (thanks @mdlayher) -* kqueue: fix regression in rework causing subdirectories to be watched [#48](https://github.com/fsnotify/fsnotify/issues/48) -* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) - -## v1.0.4 / 2014-09-07 - -* kqueue: add dragonfly to the build tags. -* Rename source code files, rearrange code so exported APIs are at the top. -* Add done channel to example code. [#37](https://github.com/fsnotify/fsnotify/pull/37) (thanks @chenyukang) - -## v1.0.3 / 2014-08-19 - -* [Fix] Windows MOVED_TO now translates to Create like on BSD and Linux. [#36](https://github.com/fsnotify/fsnotify/issues/36) - -## v1.0.2 / 2014-08-17 - -* [Fix] Missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) -* [Fix] Make ./path and path equivalent. (thanks @zhsso) - -## v1.0.0 / 2014-08-15 - -* [API] Remove AddWatch on Windows, use Add. -* Improve documentation for exported identifiers. [#30](https://github.com/fsnotify/fsnotify/issues/30) -* Minor updates based on feedback from golint. - -## dev / 2014-07-09 - -* Moved to [github.com/fsnotify/fsnotify](https://github.com/fsnotify/fsnotify). -* Use os.NewSyscallError instead of returning errno (thanks @hariharan-uno) - -## dev / 2014-07-04 - -* kqueue: fix incorrect mutex used in Close() -* Update example to demonstrate usage of Op. - -## dev / 2014-06-28 - -* [API] Don't set the Write Op for attribute notifications [#4](https://github.com/fsnotify/fsnotify/issues/4) -* Fix for String() method on Event (thanks Alex Brainman) -* Don't build on Plan 9 or Solaris (thanks @4ad) - -## dev / 2014-06-21 - -* Events channel of type Event rather than *Event. -* [internal] use syscall constants directly for inotify and kqueue. -* [internal] kqueue: rename events to kevents and fileEvent to event. - -## dev / 2014-06-19 - -* Go 1.3+ required on Windows (uses syscall.ERROR_MORE_DATA internally). -* [internal] remove cookie from Event struct (unused). -* [internal] Event struct has the same definition across every OS. -* [internal] remove internal watch and removeWatch methods. - -## dev / 2014-06-12 - -* [API] Renamed Watch() to Add() and RemoveWatch() to Remove(). -* [API] Pluralized channel names: Events and Errors. -* [API] Renamed FileEvent struct to Event. -* [API] Op constants replace methods like IsCreate(). - -## dev / 2014-06-12 - -* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) - -## dev / 2014-05-23 - -* [API] Remove current implementation of WatchFlags. - * current implementation doesn't take advantage of OS for efficiency - * provides little benefit over filtering events as they are received, but has extra bookkeeping and mutexes - * no tests for the current implementation - * not fully implemented on Windows [#93](https://github.com/howeyc/fsnotify/issues/93#issuecomment-39285195) - -## v0.9.3 / 2014-12-31 - -* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) - -## v0.9.2 / 2014-08-17 - -* [Backport] Fix missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) - -## v0.9.1 / 2014-06-12 - -* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) - -## v0.9.0 / 2014-01-17 - -* IsAttrib() for events that only concern a file's metadata [#79][] (thanks @abustany) -* [Fix] kqueue: fix deadlock [#77][] (thanks @cespare) -* [NOTICE] Development has moved to `code.google.com/p/go.exp/fsnotify` in preparation for inclusion in the Go standard library. - -## v0.8.12 / 2013-11-13 - -* [API] Remove FD_SET and friends from Linux adapter - -## v0.8.11 / 2013-11-02 - -* [Doc] Add Changelog [#72][] (thanks @nathany) -* [Doc] Spotlight and double modify events on macOS [#62][] (reported by @paulhammond) - -## v0.8.10 / 2013-10-19 - -* [Fix] kqueue: remove file watches when parent directory is removed [#71][] (reported by @mdwhatcott) -* [Fix] kqueue: race between Close and readEvents [#70][] (reported by @bernerdschaefer) -* [Doc] specify OS-specific limits in README (thanks @debrando) - -## v0.8.9 / 2013-09-08 - -* [Doc] Contributing (thanks @nathany) -* [Doc] update package path in example code [#63][] (thanks @paulhammond) -* [Doc] GoCI badge in README (Linux only) [#60][] -* [Doc] Cross-platform testing with Vagrant [#59][] (thanks @nathany) - -## v0.8.8 / 2013-06-17 - -* [Fix] Windows: handle `ERROR_MORE_DATA` on Windows [#49][] (thanks @jbowtie) - -## v0.8.7 / 2013-06-03 - -* [API] Make syscall flags internal -* [Fix] inotify: ignore event changes -* [Fix] race in symlink test [#45][] (reported by @srid) -* [Fix] tests on Windows -* lower case error messages - -## v0.8.6 / 2013-05-23 - -* kqueue: Use EVT_ONLY flag on Darwin -* [Doc] Update README with full example - -## v0.8.5 / 2013-05-09 - -* [Fix] inotify: allow monitoring of "broken" symlinks (thanks @tsg) - -## v0.8.4 / 2013-04-07 - -* [Fix] kqueue: watch all file events [#40][] (thanks @ChrisBuchholz) - -## v0.8.3 / 2013-03-13 - -* [Fix] inoitfy/kqueue memory leak [#36][] (reported by @nbkolchin) -* [Fix] kqueue: use fsnFlags for watching a directory [#33][] (reported by @nbkolchin) - -## v0.8.2 / 2013-02-07 - -* [Doc] add Authors -* [Fix] fix data races for map access [#29][] (thanks @fsouza) - -## v0.8.1 / 2013-01-09 - -* [Fix] Windows path separators -* [Doc] BSD License - -## v0.8.0 / 2012-11-09 - -* kqueue: directory watching improvements (thanks @vmirage) -* inotify: add `IN_MOVED_TO` [#25][] (requested by @cpisto) -* [Fix] kqueue: deleting watched directory [#24][] (reported by @jakerr) - -## v0.7.4 / 2012-10-09 - -* [Fix] inotify: fixes from https://codereview.appspot.com/5418045/ (ugorji) -* [Fix] kqueue: preserve watch flags when watching for delete [#21][] (reported by @robfig) -* [Fix] kqueue: watch the directory even if it isn't a new watch (thanks @robfig) -* [Fix] kqueue: modify after recreation of file - -## v0.7.3 / 2012-09-27 - -* [Fix] kqueue: watch with an existing folder inside the watched folder (thanks @vmirage) -* [Fix] kqueue: no longer get duplicate CREATE events - -## v0.7.2 / 2012-09-01 - -* kqueue: events for created directories - -## v0.7.1 / 2012-07-14 - -* [Fix] for renaming files - -## v0.7.0 / 2012-07-02 - -* [Feature] FSNotify flags -* [Fix] inotify: Added file name back to event path - -## v0.6.0 / 2012-06-06 - -* kqueue: watch files after directory created (thanks @tmc) - -## v0.5.1 / 2012-05-22 - -* [Fix] inotify: remove all watches before Close() - -## v0.5.0 / 2012-05-03 - -* [API] kqueue: return errors during watch instead of sending over channel -* kqueue: match symlink behavior on Linux -* inotify: add `DELETE_SELF` (requested by @taralx) -* [Fix] kqueue: handle EINTR (reported by @robfig) -* [Doc] Godoc example [#1][] (thanks @davecheney) - -## v0.4.0 / 2012-03-30 - -* Go 1 released: build with go tool -* [Feature] Windows support using winfsnotify -* Windows does not have attribute change notifications -* Roll attribute notifications into IsModify - -## v0.3.0 / 2012-02-19 - -* kqueue: add files when watch directory - -## v0.2.0 / 2011-12-30 - -* update to latest Go weekly code - -## v0.1.0 / 2011-10-19 - -* kqueue: add watch on file creation to match inotify -* kqueue: create file event -* inotify: ignore `IN_IGNORED` events -* event String() -* linux: common FileEvent functions -* initial commit - -[#79]: https://github.com/howeyc/fsnotify/pull/79 -[#77]: https://github.com/howeyc/fsnotify/pull/77 -[#72]: https://github.com/howeyc/fsnotify/issues/72 -[#71]: https://github.com/howeyc/fsnotify/issues/71 -[#70]: https://github.com/howeyc/fsnotify/issues/70 -[#63]: https://github.com/howeyc/fsnotify/issues/63 -[#62]: https://github.com/howeyc/fsnotify/issues/62 -[#60]: https://github.com/howeyc/fsnotify/issues/60 -[#59]: https://github.com/howeyc/fsnotify/issues/59 -[#49]: https://github.com/howeyc/fsnotify/issues/49 -[#45]: https://github.com/howeyc/fsnotify/issues/45 -[#40]: https://github.com/howeyc/fsnotify/issues/40 -[#36]: https://github.com/howeyc/fsnotify/issues/36 -[#33]: https://github.com/howeyc/fsnotify/issues/33 -[#29]: https://github.com/howeyc/fsnotify/issues/29 -[#25]: https://github.com/howeyc/fsnotify/issues/25 -[#24]: https://github.com/howeyc/fsnotify/issues/24 -[#21]: https://github.com/howeyc/fsnotify/issues/21 diff --git a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md deleted file mode 100644 index 828a60b2..00000000 --- a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md +++ /dev/null @@ -1,77 +0,0 @@ -# Contributing - -## Issues - -* Request features and report bugs using the [GitHub Issue Tracker](https://github.com/fsnotify/fsnotify/issues). -* Please indicate the platform you are using fsnotify on. -* A code example to reproduce the problem is appreciated. - -## Pull Requests - -### Contributor License Agreement - -fsnotify is derived from code in the [golang.org/x/exp](https://godoc.org/golang.org/x/exp) package and it may be included [in the standard library](https://github.com/fsnotify/fsnotify/issues/1) in the future. Therefore fsnotify carries the same [LICENSE](https://github.com/fsnotify/fsnotify/blob/master/LICENSE) as Go. Contributors retain their copyright, so you need to fill out a short form before we can accept your contribution: [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual). - -Please indicate that you have signed the CLA in your pull request. - -### How fsnotify is Developed - -* Development is done on feature branches. -* Tests are run on BSD, Linux, macOS and Windows. -* Pull requests are reviewed and [applied to master][am] using [hub][]. - * Maintainers may modify or squash commits rather than asking contributors to. -* To issue a new release, the maintainers will: - * Update the CHANGELOG - * Tag a version, which will become available through gopkg.in. - -### How to Fork - -For smooth sailing, always use the original import path. Installing with `go get` makes this easy. - -1. Install from GitHub (`go get -u github.com/fsnotify/fsnotify`) -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Ensure everything works and the tests pass (see below) -4. Commit your changes (`git commit -am 'Add some feature'`) - -Contribute upstream: - -1. Fork fsnotify on GitHub -2. Add your remote (`git remote add fork git@github.com:mycompany/repo.git`) -3. Push to the branch (`git push fork my-new-feature`) -4. Create a new Pull Request on GitHub - -This workflow is [thoroughly explained by Katrina Owen](https://splice.com/blog/contributing-open-source-git-repositories-go/). - -### Testing - -fsnotify uses build tags to compile different code on Linux, BSD, macOS, and Windows. - -Before doing a pull request, please do your best to test your changes on multiple platforms, and list which platforms you were able/unable to test on. - -To aid in cross-platform testing there is a Vagrantfile for Linux and BSD. - -* Install [Vagrant](http://www.vagrantup.com/) and [VirtualBox](https://www.virtualbox.org/) -* Setup [Vagrant Gopher](https://github.com/nathany/vagrant-gopher) in your `src` folder. -* Run `vagrant up` from the project folder. You can also setup just one box with `vagrant up linux` or `vagrant up bsd` (note: the BSD box doesn't support Windows hosts at this time, and NFS may prompt for your host OS password) -* Once setup, you can run the test suite on a given OS with a single command `vagrant ssh linux -c 'cd fsnotify/fsnotify; go test'`. -* When you're done, you will want to halt or destroy the Vagrant boxes. - -Notice: fsnotify file system events won't trigger in shared folders. The tests get around this limitation by using the /tmp directory. - -Right now there is no equivalent solution for Windows and macOS, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads). - -### Maintainers - -Help maintaining fsnotify is welcome. To be a maintainer: - -* Submit a pull request and sign the CLA as above. -* You must be able to run the test suite on Mac, Windows, Linux and BSD. - -To keep master clean, the fsnotify project uses the "apply mail" workflow outlined in Nathaniel Talbott's post ["Merge pull request" Considered Harmful][am]. This requires installing [hub][]. - -All code changes should be internal pull requests. - -Releases are tagged using [Semantic Versioning](http://semver.org/). - -[hub]: https://github.com/github/hub -[am]: http://blog.spreedly.com/2014/06/24/merge-pull-request-considered-harmful/#.VGa5yZPF_Zs diff --git a/vendor/github.com/fsnotify/fsnotify/LICENSE b/vendor/github.com/fsnotify/fsnotify/LICENSE deleted file mode 100644 index f21e5408..00000000 --- a/vendor/github.com/fsnotify/fsnotify/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. -Copyright (c) 2012 fsnotify Authors. 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 Google Inc. 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. diff --git a/vendor/github.com/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md deleted file mode 100644 index 39932074..00000000 --- a/vendor/github.com/fsnotify/fsnotify/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# File system notifications for Go - -[![GoDoc](https://godoc.org/github.com/fsnotify/fsnotify?status.svg)](https://godoc.org/github.com/fsnotify/fsnotify) [![Go Report Card](https://goreportcard.com/badge/github.com/fsnotify/fsnotify)](https://goreportcard.com/report/github.com/fsnotify/fsnotify) - -fsnotify utilizes [golang.org/x/sys](https://godoc.org/golang.org/x/sys) rather than `syscall` from the standard library. Ensure you have the latest version installed by running: - -```console -go get -u golang.org/x/sys/... -``` - -Cross platform: Windows, Linux, BSD and macOS. - -|Adapter |OS |Status | -|----------|----------|----------| -|inotify |Linux 2.6.27 or later, Android\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)| -|kqueue |BSD, macOS, iOS\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)| -|ReadDirectoryChangesW|Windows|Supported [![Build status](https://ci.appveyor.com/api/projects/status/ivwjubaih4r0udeh/branch/master?svg=true)](https://ci.appveyor.com/project/NathanYoungman/fsnotify/branch/master)| -|FSEvents |macOS |[Planned](https://github.com/fsnotify/fsnotify/issues/11)| -|FEN |Solaris 11 |[In Progress](https://github.com/fsnotify/fsnotify/issues/12)| -|fanotify |Linux 2.6.37+ | | -|USN Journals |Windows |[Maybe](https://github.com/fsnotify/fsnotify/issues/53)| -|Polling |*All* |[Maybe](https://github.com/fsnotify/fsnotify/issues/9)| - -\* Android and iOS are untested. - -Please see [the documentation](https://godoc.org/github.com/fsnotify/fsnotify) and consult the [FAQ](#faq) for usage information. - -## API stability - -fsnotify is a fork of [howeyc/fsnotify](https://godoc.org/github.com/howeyc/fsnotify) with a new API as of v1.0. The API is based on [this design document](http://goo.gl/MrYxyA). - -All [releases](https://github.com/fsnotify/fsnotify/releases) are tagged based on [Semantic Versioning](http://semver.org/). Further API changes are [planned](https://github.com/fsnotify/fsnotify/milestones), and will be tagged with a new major revision number. - -Go 1.6 supports dependencies located in the `vendor/` folder. Unless you are creating a library, it is recommended that you copy fsnotify into `vendor/github.com/fsnotify/fsnotify` within your project, and likewise for `golang.org/x/sys`. - -## Contributing - -Please refer to [CONTRIBUTING][] before opening an issue or pull request. - -## Example - -See [example_test.go](https://github.com/fsnotify/fsnotify/blob/master/example_test.go). - -## FAQ - -**When a file is moved to another directory is it still being watched?** - -No (it shouldn't be, unless you are watching where it was moved to). - -**When I watch a directory, are all subdirectories watched as well?** - -No, you must add watches for any directory you want to watch (a recursive watcher is on the roadmap [#18][]). - -**Do I have to watch the Error and Event channels in a separate goroutine?** - -As of now, yes. Looking into making this single-thread friendly (see [howeyc #7][#7]) - -**Why am I receiving multiple events for the same file on OS X?** - -Spotlight indexing on OS X can result in multiple events (see [howeyc #62][#62]). A temporary workaround is to add your folder(s) to the *Spotlight Privacy settings* until we have a native FSEvents implementation (see [#11][]). - -**How many files can be watched at once?** - -There are OS-specific limits as to how many watches can be created: -* Linux: /proc/sys/fs/inotify/max_user_watches contains the limit, reaching this limit results in a "no space left on device" error. -* BSD / OSX: sysctl variables "kern.maxfiles" and "kern.maxfilesperproc", reaching these limits results in a "too many open files" error. - -[#62]: https://github.com/howeyc/fsnotify/issues/62 -[#18]: https://github.com/fsnotify/fsnotify/issues/18 -[#11]: https://github.com/fsnotify/fsnotify/issues/11 -[#7]: https://github.com/howeyc/fsnotify/issues/7 - -[contributing]: https://github.com/fsnotify/fsnotify/blob/master/CONTRIBUTING.md - -## Related Projects - -* [notify](https://github.com/rjeczalik/notify) -* [fsevents](https://github.com/fsnotify/fsevents) - diff --git a/vendor/github.com/fsnotify/fsnotify/example_test.go b/vendor/github.com/fsnotify/fsnotify/example_test.go deleted file mode 100644 index 700502cb..00000000 --- a/vendor/github.com/fsnotify/fsnotify/example_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2012 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. - -// +build !plan9 - -package fsnotify_test - -import ( - "log" - - "github.com/fsnotify/fsnotify" -) - -func ExampleNewWatcher() { - watcher, err := fsnotify.NewWatcher() - if err != nil { - log.Fatal(err) - } - defer watcher.Close() - - done := make(chan bool) - go func() { - for { - select { - case event := <-watcher.Events: - log.Println("event:", event) - if event.Op&fsnotify.Write == fsnotify.Write { - log.Println("modified file:", event.Name) - } - case err := <-watcher.Errors: - log.Println("error:", err) - } - } - }() - - err = watcher.Add("/tmp/foo") - if err != nil { - log.Fatal(err) - } - <-done -} diff --git a/vendor/github.com/fsnotify/fsnotify/fen.go b/vendor/github.com/fsnotify/fsnotify/fen.go deleted file mode 100644 index ced39cb8..00000000 --- a/vendor/github.com/fsnotify/fsnotify/fen.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2010 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. - -// +build solaris - -package fsnotify - -import ( - "errors" -) - -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct { - Events chan Event - Errors chan error -} - -// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events. -func NewWatcher() (*Watcher, error) { - return nil, errors.New("FEN based watcher not yet supported for fsnotify\n") -} - -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - return nil -} - -// Add starts watching the named file or directory (non-recursively). -func (w *Watcher) Add(name string) error { - return nil -} - -// Remove stops watching the the named file or directory (non-recursively). -func (w *Watcher) Remove(name string) error { - return nil -} diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go deleted file mode 100644 index 190bf0de..00000000 --- a/vendor/github.com/fsnotify/fsnotify/fsnotify.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2012 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. - -// +build !plan9 - -// Package fsnotify provides a platform-independent interface for file system notifications. -package fsnotify - -import ( - "bytes" - "errors" - "fmt" -) - -// Event represents a single file system notification. -type Event struct { - Name string // Relative path to the file or directory. - Op Op // File operation that triggered the event. -} - -// Op describes a set of file operations. -type Op uint32 - -// These are the generalized file operations that can trigger a notification. -const ( - Create Op = 1 << iota - Write - Remove - Rename - Chmod -) - -func (op Op) String() string { - // Use a buffer for efficient string concatenation - var buffer bytes.Buffer - - if op&Create == Create { - buffer.WriteString("|CREATE") - } - if op&Remove == Remove { - buffer.WriteString("|REMOVE") - } - if op&Write == Write { - buffer.WriteString("|WRITE") - } - if op&Rename == Rename { - buffer.WriteString("|RENAME") - } - if op&Chmod == Chmod { - buffer.WriteString("|CHMOD") - } - if buffer.Len() == 0 { - return "" - } - return buffer.String()[1:] // Strip leading pipe -} - -// String returns a string representation of the event in the form -// "file: REMOVE|WRITE|..." -func (e Event) String() string { - return fmt.Sprintf("%q: %s", e.Name, e.Op.String()) -} - -// Common errors that can be reported by a watcher -var ErrEventOverflow = errors.New("fsnotify queue overflow") diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go b/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go deleted file mode 100644 index f9771d9d..00000000 --- a/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2016 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. - -// +build !plan9 - -package fsnotify - -import ( - "os" - "testing" - "time" -) - -func TestEventStringWithValue(t *testing.T) { - for opMask, expectedString := range map[Op]string{ - Chmod | Create: `"/usr/someFile": CREATE|CHMOD`, - Rename: `"/usr/someFile": RENAME`, - Remove: `"/usr/someFile": REMOVE`, - Write | Chmod: `"/usr/someFile": WRITE|CHMOD`, - } { - event := Event{Name: "/usr/someFile", Op: opMask} - if event.String() != expectedString { - t.Fatalf("Expected %s, got: %v", expectedString, event.String()) - } - - } -} - -func TestEventOpStringWithValue(t *testing.T) { - expectedOpString := "WRITE|CHMOD" - event := Event{Name: "someFile", Op: Write | Chmod} - if event.Op.String() != expectedOpString { - t.Fatalf("Expected %s, got: %v", expectedOpString, event.Op.String()) - } -} - -func TestEventOpStringWithNoValue(t *testing.T) { - expectedOpString := "" - event := Event{Name: "testFile", Op: 0} - if event.Op.String() != expectedOpString { - t.Fatalf("Expected %s, got: %v", expectedOpString, event.Op.String()) - } -} - -// TestWatcherClose tests that the goroutine started by creating the watcher can be -// signalled to return at any time, even if there is no goroutine listening on the events -// or errors channels. -func TestWatcherClose(t *testing.T) { - t.Parallel() - - name := tempMkFile(t, "") - w := newWatcher(t) - err := w.Add(name) - if err != nil { - t.Fatal(err) - } - - err = os.Remove(name) - if err != nil { - t.Fatal(err) - } - // Allow the watcher to receive the event. - time.Sleep(time.Millisecond * 100) - - err = w.Close() - if err != nil { - t.Fatal(err) - } -} diff --git a/vendor/github.com/fsnotify/fsnotify/inotify.go b/vendor/github.com/fsnotify/fsnotify/inotify.go deleted file mode 100644 index d9fd1b88..00000000 --- a/vendor/github.com/fsnotify/fsnotify/inotify.go +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright 2010 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. - -// +build linux - -package fsnotify - -import ( - "errors" - "fmt" - "io" - "os" - "path/filepath" - "strings" - "sync" - "unsafe" - - "golang.org/x/sys/unix" -) - -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct { - Events chan Event - Errors chan error - mu sync.Mutex // Map access - fd int - poller *fdPoller - watches map[string]*watch // Map of inotify watches (key: path) - paths map[int]string // Map of watched paths (key: watch descriptor) - done chan struct{} // Channel for sending a "quit message" to the reader goroutine - doneResp chan struct{} // Channel to respond to Close -} - -// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events. -func NewWatcher() (*Watcher, error) { - // Create inotify fd - fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC) - if fd == -1 { - return nil, errno - } - // Create epoll - poller, err := newFdPoller(fd) - if err != nil { - unix.Close(fd) - return nil, err - } - w := &Watcher{ - fd: fd, - poller: poller, - watches: make(map[string]*watch), - paths: make(map[int]string), - Events: make(chan Event), - Errors: make(chan error), - done: make(chan struct{}), - doneResp: make(chan struct{}), - } - - go w.readEvents() - return w, nil -} - -func (w *Watcher) isClosed() bool { - select { - case <-w.done: - return true - default: - return false - } -} - -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - if w.isClosed() { - return nil - } - - // Send 'close' signal to goroutine, and set the Watcher to closed. - close(w.done) - - // Wake up goroutine - w.poller.wake() - - // Wait for goroutine to close - <-w.doneResp - - return nil -} - -// Add starts watching the named file or directory (non-recursively). -func (w *Watcher) Add(name string) error { - name = filepath.Clean(name) - if w.isClosed() { - return errors.New("inotify instance already closed") - } - - const agnosticEvents = unix.IN_MOVED_TO | unix.IN_MOVED_FROM | - unix.IN_CREATE | unix.IN_ATTRIB | unix.IN_MODIFY | - unix.IN_MOVE_SELF | unix.IN_DELETE | unix.IN_DELETE_SELF - - var flags uint32 = agnosticEvents - - w.mu.Lock() - defer w.mu.Unlock() - watchEntry := w.watches[name] - if watchEntry != nil { - flags |= watchEntry.flags | unix.IN_MASK_ADD - } - wd, errno := unix.InotifyAddWatch(w.fd, name, flags) - if wd == -1 { - return errno - } - - if watchEntry == nil { - w.watches[name] = &watch{wd: uint32(wd), flags: flags} - w.paths[wd] = name - } else { - watchEntry.wd = uint32(wd) - watchEntry.flags = flags - } - - return nil -} - -// Remove stops watching the named file or directory (non-recursively). -func (w *Watcher) Remove(name string) error { - name = filepath.Clean(name) - - // Fetch the watch. - w.mu.Lock() - defer w.mu.Unlock() - watch, ok := w.watches[name] - - // Remove it from inotify. - if !ok { - return fmt.Errorf("can't remove non-existent inotify watch for: %s", name) - } - - // We successfully removed the watch if InotifyRmWatch doesn't return an - // error, we need to clean up our internal state to ensure it matches - // inotify's kernel state. - delete(w.paths, int(watch.wd)) - delete(w.watches, name) - - // inotify_rm_watch will return EINVAL if the file has been deleted; - // the inotify will already have been removed. - // watches and pathes are deleted in ignoreLinux() implicitly and asynchronously - // by calling inotify_rm_watch() below. e.g. readEvents() goroutine receives IN_IGNORE - // so that EINVAL means that the wd is being rm_watch()ed or its file removed - // by another thread and we have not received IN_IGNORE event. - success, errno := unix.InotifyRmWatch(w.fd, watch.wd) - if success == -1 { - // TODO: Perhaps it's not helpful to return an error here in every case. - // the only two possible errors are: - // EBADF, which happens when w.fd is not a valid file descriptor of any kind. - // EINVAL, which is when fd is not an inotify descriptor or wd is not a valid watch descriptor. - // Watch descriptors are invalidated when they are removed explicitly or implicitly; - // explicitly by inotify_rm_watch, implicitly when the file they are watching is deleted. - return errno - } - - return nil -} - -type watch struct { - wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall) - flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags) -} - -// readEvents reads from the inotify file descriptor, converts the -// received events into Event objects and sends them via the Events channel -func (w *Watcher) readEvents() { - var ( - buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events - n int // Number of bytes read with read() - errno error // Syscall errno - ok bool // For poller.wait - ) - - defer close(w.doneResp) - defer close(w.Errors) - defer close(w.Events) - defer unix.Close(w.fd) - defer w.poller.close() - - for { - // See if we have been closed. - if w.isClosed() { - return - } - - ok, errno = w.poller.wait() - if errno != nil { - select { - case w.Errors <- errno: - case <-w.done: - return - } - continue - } - - if !ok { - continue - } - - n, errno = unix.Read(w.fd, buf[:]) - // If a signal interrupted execution, see if we've been asked to close, and try again. - // http://man7.org/linux/man-pages/man7/signal.7.html : - // "Before Linux 3.8, reads from an inotify(7) file descriptor were not restartable" - if errno == unix.EINTR { - continue - } - - // unix.Read might have been woken up by Close. If so, we're done. - if w.isClosed() { - return - } - - if n < unix.SizeofInotifyEvent { - var err error - if n == 0 { - // If EOF is received. This should really never happen. - err = io.EOF - } else if n < 0 { - // If an error occurred while reading. - err = errno - } else { - // Read was too short. - err = errors.New("notify: short read in readEvents()") - } - select { - case w.Errors <- err: - case <-w.done: - return - } - continue - } - - var offset uint32 - // We don't know how many events we just read into the buffer - // While the offset points to at least one whole event... - for offset <= uint32(n-unix.SizeofInotifyEvent) { - // Point "raw" to the event in the buffer - raw := (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset])) - - mask := uint32(raw.Mask) - nameLen := uint32(raw.Len) - - if mask&unix.IN_Q_OVERFLOW != 0 { - select { - case w.Errors <- ErrEventOverflow: - case <-w.done: - return - } - } - - // If the event happened to the watched directory or the watched file, the kernel - // doesn't append the filename to the event, but we would like to always fill the - // the "Name" field with a valid filename. We retrieve the path of the watch from - // the "paths" map. - w.mu.Lock() - name, ok := w.paths[int(raw.Wd)] - // IN_DELETE_SELF occurs when the file/directory being watched is removed. - // This is a sign to clean up the maps, otherwise we are no longer in sync - // with the inotify kernel state which has already deleted the watch - // automatically. - if ok && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { - delete(w.paths, int(raw.Wd)) - delete(w.watches, name) - } - w.mu.Unlock() - - if nameLen > 0 { - // Point "bytes" at the first byte of the filename - bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent])) - // The filename is padded with NULL bytes. TrimRight() gets rid of those. - name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") - } - - event := newEvent(name, mask) - - // Send the events that are not ignored on the events channel - if !event.ignoreLinux(mask) { - select { - case w.Events <- event: - case <-w.done: - return - } - } - - // Move to the next event in the buffer - offset += unix.SizeofInotifyEvent + nameLen - } - } -} - -// Certain types of events can be "ignored" and not sent over the Events -// channel. Such as events marked ignore by the kernel, or MODIFY events -// against files that do not exist. -func (e *Event) ignoreLinux(mask uint32) bool { - // Ignore anything the inotify API says to ignore - if mask&unix.IN_IGNORED == unix.IN_IGNORED { - return true - } - - // If the event is not a DELETE or RENAME, the file must exist. - // Otherwise the event is ignored. - // *Note*: this was put in place because it was seen that a MODIFY - // event was sent after the DELETE. This ignores that MODIFY and - // assumes a DELETE will come or has come if the file doesn't exist. - if !(e.Op&Remove == Remove || e.Op&Rename == Rename) { - _, statErr := os.Lstat(e.Name) - return os.IsNotExist(statErr) - } - return false -} - -// newEvent returns an platform-independent Event based on an inotify mask. -func newEvent(name string, mask uint32) Event { - e := Event{Name: name} - if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { - e.Op |= Create - } - if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE { - e.Op |= Remove - } - if mask&unix.IN_MODIFY == unix.IN_MODIFY { - e.Op |= Write - } - if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { - e.Op |= Rename - } - if mask&unix.IN_ATTRIB == unix.IN_ATTRIB { - e.Op |= Chmod - } - return e -} diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_poller.go b/vendor/github.com/fsnotify/fsnotify/inotify_poller.go deleted file mode 100644 index cc7db4b2..00000000 --- a/vendor/github.com/fsnotify/fsnotify/inotify_poller.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright 2015 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. - -// +build linux - -package fsnotify - -import ( - "errors" - - "golang.org/x/sys/unix" -) - -type fdPoller struct { - fd int // File descriptor (as returned by the inotify_init() syscall) - epfd int // Epoll file descriptor - pipe [2]int // Pipe for waking up -} - -func emptyPoller(fd int) *fdPoller { - poller := new(fdPoller) - poller.fd = fd - poller.epfd = -1 - poller.pipe[0] = -1 - poller.pipe[1] = -1 - return poller -} - -// Create a new inotify poller. -// This creates an inotify handler, and an epoll handler. -func newFdPoller(fd int) (*fdPoller, error) { - var errno error - poller := emptyPoller(fd) - defer func() { - if errno != nil { - poller.close() - } - }() - poller.fd = fd - - // Create epoll fd - poller.epfd, errno = unix.EpollCreate1(0) - if poller.epfd == -1 { - return nil, errno - } - // Create pipe; pipe[0] is the read end, pipe[1] the write end. - errno = unix.Pipe2(poller.pipe[:], unix.O_NONBLOCK) - if errno != nil { - return nil, errno - } - - // Register inotify fd with epoll - event := unix.EpollEvent{ - Fd: int32(poller.fd), - Events: unix.EPOLLIN, - } - errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.fd, &event) - if errno != nil { - return nil, errno - } - - // Register pipe fd with epoll - event = unix.EpollEvent{ - Fd: int32(poller.pipe[0]), - Events: unix.EPOLLIN, - } - errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.pipe[0], &event) - if errno != nil { - return nil, errno - } - - return poller, nil -} - -// Wait using epoll. -// Returns true if something is ready to be read, -// false if there is not. -func (poller *fdPoller) wait() (bool, error) { - // 3 possible events per fd, and 2 fds, makes a maximum of 6 events. - // I don't know whether epoll_wait returns the number of events returned, - // or the total number of events ready. - // I decided to catch both by making the buffer one larger than the maximum. - events := make([]unix.EpollEvent, 7) - for { - n, errno := unix.EpollWait(poller.epfd, events, -1) - if n == -1 { - if errno == unix.EINTR { - continue - } - return false, errno - } - if n == 0 { - // If there are no events, try again. - continue - } - if n > 6 { - // This should never happen. More events were returned than should be possible. - return false, errors.New("epoll_wait returned more events than I know what to do with") - } - ready := events[:n] - epollhup := false - epollerr := false - epollin := false - for _, event := range ready { - if event.Fd == int32(poller.fd) { - if event.Events&unix.EPOLLHUP != 0 { - // This should not happen, but if it does, treat it as a wakeup. - epollhup = true - } - if event.Events&unix.EPOLLERR != 0 { - // If an error is waiting on the file descriptor, we should pretend - // something is ready to read, and let unix.Read pick up the error. - epollerr = true - } - if event.Events&unix.EPOLLIN != 0 { - // There is data to read. - epollin = true - } - } - if event.Fd == int32(poller.pipe[0]) { - if event.Events&unix.EPOLLHUP != 0 { - // Write pipe descriptor was closed, by us. This means we're closing down the - // watcher, and we should wake up. - } - if event.Events&unix.EPOLLERR != 0 { - // If an error is waiting on the pipe file descriptor. - // This is an absolute mystery, and should never ever happen. - return false, errors.New("Error on the pipe descriptor.") - } - if event.Events&unix.EPOLLIN != 0 { - // This is a regular wakeup, so we have to clear the buffer. - err := poller.clearWake() - if err != nil { - return false, err - } - } - } - } - - if epollhup || epollerr || epollin { - return true, nil - } - return false, nil - } -} - -// Close the write end of the poller. -func (poller *fdPoller) wake() error { - buf := make([]byte, 1) - n, errno := unix.Write(poller.pipe[1], buf) - if n == -1 { - if errno == unix.EAGAIN { - // Buffer is full, poller will wake. - return nil - } - return errno - } - return nil -} - -func (poller *fdPoller) clearWake() error { - // You have to be woken up a LOT in order to get to 100! - buf := make([]byte, 100) - n, errno := unix.Read(poller.pipe[0], buf) - if n == -1 { - if errno == unix.EAGAIN { - // Buffer is empty, someone else cleared our wake. - return nil - } - return errno - } - return nil -} - -// Close all poller file descriptors, but not the one passed to it. -func (poller *fdPoller) close() { - if poller.pipe[1] != -1 { - unix.Close(poller.pipe[1]) - } - if poller.pipe[0] != -1 { - unix.Close(poller.pipe[0]) - } - if poller.epfd != -1 { - unix.Close(poller.epfd) - } -} diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go b/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go deleted file mode 100644 index 26623efe..00000000 --- a/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2015 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. - -// +build linux - -package fsnotify - -import ( - "testing" - "time" - - "golang.org/x/sys/unix" -) - -type testFd [2]int - -func makeTestFd(t *testing.T) testFd { - var tfd testFd - errno := unix.Pipe(tfd[:]) - if errno != nil { - t.Fatalf("Failed to create pipe: %v", errno) - } - return tfd -} - -func (tfd testFd) fd() int { - return tfd[0] -} - -func (tfd testFd) closeWrite(t *testing.T) { - errno := unix.Close(tfd[1]) - if errno != nil { - t.Fatalf("Failed to close write end of pipe: %v", errno) - } -} - -func (tfd testFd) put(t *testing.T) { - buf := make([]byte, 10) - _, errno := unix.Write(tfd[1], buf) - if errno != nil { - t.Fatalf("Failed to write to pipe: %v", errno) - } -} - -func (tfd testFd) get(t *testing.T) { - buf := make([]byte, 10) - _, errno := unix.Read(tfd[0], buf) - if errno != nil { - t.Fatalf("Failed to read from pipe: %v", errno) - } -} - -func (tfd testFd) close() { - unix.Close(tfd[1]) - unix.Close(tfd[0]) -} - -func makePoller(t *testing.T) (testFd, *fdPoller) { - tfd := makeTestFd(t) - poller, err := newFdPoller(tfd.fd()) - if err != nil { - t.Fatalf("Failed to create poller: %v", err) - } - return tfd, poller -} - -func TestPollerWithBadFd(t *testing.T) { - _, err := newFdPoller(-1) - if err != unix.EBADF { - t.Fatalf("Expected EBADF, got: %v", err) - } -} - -func TestPollerWithData(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - tfd.put(t) - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } - tfd.get(t) -} - -func TestPollerWithWakeup(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - err := poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if ok { - t.Fatalf("expected poller to return false") - } -} - -func TestPollerWithClose(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - tfd.closeWrite(t) - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } -} - -func TestPollerWithWakeupAndData(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - tfd.put(t) - err := poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - - // both data and wakeup - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } - - // data is still in the buffer, wakeup is cleared - ok, err = poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } - - tfd.get(t) - // data is gone, only wakeup now - err = poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - ok, err = poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if ok { - t.Fatalf("expected poller to return false") - } -} - -func TestPollerConcurrent(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - oks := make(chan bool) - live := make(chan bool) - defer close(live) - go func() { - defer close(oks) - for { - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - oks <- ok - if !<-live { - return - } - } - }() - - // Try a write - select { - case <-time.After(50 * time.Millisecond): - case <-oks: - t.Fatalf("poller did not wait") - } - tfd.put(t) - if !<-oks { - t.Fatalf("expected true") - } - tfd.get(t) - live <- true - - // Try a wakeup - select { - case <-time.After(50 * time.Millisecond): - case <-oks: - t.Fatalf("poller did not wait") - } - err := poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - if <-oks { - t.Fatalf("expected false") - } - live <- true - - // Try a close - select { - case <-time.After(50 * time.Millisecond): - case <-oks: - t.Fatalf("poller did not wait") - } - tfd.closeWrite(t) - if !<-oks { - t.Fatalf("expected true") - } - tfd.get(t) -} diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_test.go b/vendor/github.com/fsnotify/fsnotify/inotify_test.go deleted file mode 100644 index 54f3f00e..00000000 --- a/vendor/github.com/fsnotify/fsnotify/inotify_test.go +++ /dev/null @@ -1,449 +0,0 @@ -// Copyright 2015 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. - -// +build linux - -package fsnotify - -import ( - "fmt" - "os" - "path/filepath" - "strings" - "testing" - "time" -) - -func TestInotifyCloseRightAway(t *testing.T) { - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - - // Close immediately; it won't even reach the first unix.Read. - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func TestInotifyCloseSlightlyLater(t *testing.T) { - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - - // Wait until readEvents has reached unix.Read, and Close. - <-time.After(50 * time.Millisecond) - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func TestInotifyCloseSlightlyLaterWithWatch(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - w.Add(testDir) - - // Wait until readEvents has reached unix.Read, and Close. - <-time.After(50 * time.Millisecond) - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func TestInotifyCloseAfterRead(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - - err = w.Add(testDir) - if err != nil { - t.Fatalf("Failed to add .") - } - - // Generate an event. - os.Create(filepath.Join(testDir, "somethingSOMETHINGsomethingSOMETHING")) - - // Wait for readEvents to read the event, then close the watcher. - <-time.After(50 * time.Millisecond) - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func isWatcherReallyClosed(t *testing.T, w *Watcher) { - select { - case err, ok := <-w.Errors: - if ok { - t.Fatalf("w.Errors is not closed; readEvents is still alive after closing (error: %v)", err) - } - default: - t.Fatalf("w.Errors would have blocked; readEvents is still alive!") - } - - select { - case _, ok := <-w.Events: - if ok { - t.Fatalf("w.Events is not closed; readEvents is still alive after closing") - } - default: - t.Fatalf("w.Events would have blocked; readEvents is still alive!") - } -} - -func TestInotifyCloseCreate(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testDir) - if err != nil { - t.Fatalf("Failed to add testDir: %v", err) - } - h, err := os.Create(filepath.Join(testDir, "testfile")) - if err != nil { - t.Fatalf("Failed to create file in testdir: %v", err) - } - h.Close() - select { - case _ = <-w.Events: - case err := <-w.Errors: - t.Fatalf("Error from watcher: %v", err) - case <-time.After(50 * time.Millisecond): - t.Fatalf("Took too long to wait for event") - } - - // At this point, we've received one event, so the goroutine is ready. - // It's also blocking on unix.Read. - // Now we try to swap the file descriptor under its nose. - w.Close() - w, err = NewWatcher() - defer w.Close() - if err != nil { - t.Fatalf("Failed to create second watcher: %v", err) - } - - <-time.After(50 * time.Millisecond) - err = w.Add(testDir) - if err != nil { - t.Fatalf("Error adding testDir again: %v", err) - } -} - -// This test verifies the watcher can keep up with file creations/deletions -// when under load. -func TestInotifyStress(t *testing.T) { - maxNumToCreate := 1000 - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - testFilePrefix := filepath.Join(testDir, "testfile") - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testDir) - if err != nil { - t.Fatalf("Failed to add testDir: %v", err) - } - - doneChan := make(chan struct{}) - // The buffer ensures that the file generation goroutine is never blocked. - errChan := make(chan error, 2*maxNumToCreate) - - go func() { - for i := 0; i < maxNumToCreate; i++ { - testFile := fmt.Sprintf("%s%d", testFilePrefix, i) - - handle, err := os.Create(testFile) - if err != nil { - errChan <- fmt.Errorf("Create failed: %v", err) - continue - } - - err = handle.Close() - if err != nil { - errChan <- fmt.Errorf("Close failed: %v", err) - continue - } - } - - // If we delete a newly created file too quickly, inotify will skip the - // create event and only send the delete event. - time.Sleep(100 * time.Millisecond) - - for i := 0; i < maxNumToCreate; i++ { - testFile := fmt.Sprintf("%s%d", testFilePrefix, i) - err = os.Remove(testFile) - if err != nil { - errChan <- fmt.Errorf("Remove failed: %v", err) - } - } - - close(doneChan) - }() - - creates := 0 - removes := 0 - - finished := false - after := time.After(10 * time.Second) - for !finished { - select { - case <-after: - t.Fatalf("Not done") - case <-doneChan: - finished = true - case err := <-errChan: - t.Fatalf("Got an error from file creator goroutine: %v", err) - case err := <-w.Errors: - t.Fatalf("Got an error from watcher: %v", err) - case evt := <-w.Events: - if !strings.HasPrefix(evt.Name, testFilePrefix) { - t.Fatalf("Got an event for an unknown file: %s", evt.Name) - } - if evt.Op == Create { - creates++ - } - if evt.Op == Remove { - removes++ - } - } - } - - // Drain remaining events from channels - count := 0 - for count < 10 { - select { - case err := <-errChan: - t.Fatalf("Got an error from file creator goroutine: %v", err) - case err := <-w.Errors: - t.Fatalf("Got an error from watcher: %v", err) - case evt := <-w.Events: - if !strings.HasPrefix(evt.Name, testFilePrefix) { - t.Fatalf("Got an event for an unknown file: %s", evt.Name) - } - if evt.Op == Create { - creates++ - } - if evt.Op == Remove { - removes++ - } - count = 0 - default: - count++ - // Give the watcher chances to fill the channels. - time.Sleep(time.Millisecond) - } - } - - if creates-removes > 1 || creates-removes < -1 { - t.Fatalf("Creates and removes should not be off by more than one: %d creates, %d removes", creates, removes) - } - if creates < 50 { - t.Fatalf("Expected at least 50 creates, got %d", creates) - } -} - -func TestInotifyRemoveTwice(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - testFile := filepath.Join(testDir, "testfile") - - handle, err := os.Create(testFile) - if err != nil { - t.Fatalf("Create failed: %v", err) - } - handle.Close() - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testFile) - if err != nil { - t.Fatalf("Failed to add testFile: %v", err) - } - - err = w.Remove(testFile) - if err != nil { - t.Fatalf("wanted successful remove but got: %v", err) - } - - err = w.Remove(testFile) - if err == nil { - t.Fatalf("no error on removing invalid file") - } - - w.mu.Lock() - defer w.mu.Unlock() - if len(w.watches) != 0 { - t.Fatalf("Expected watches len is 0, but got: %d, %v", len(w.watches), w.watches) - } - if len(w.paths) != 0 { - t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths) - } -} - -func TestInotifyInnerMapLength(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - testFile := filepath.Join(testDir, "testfile") - - handle, err := os.Create(testFile) - if err != nil { - t.Fatalf("Create failed: %v", err) - } - handle.Close() - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testFile) - if err != nil { - t.Fatalf("Failed to add testFile: %v", err) - } - go func() { - for err := range w.Errors { - t.Fatalf("error received: %s", err) - } - }() - - err = os.Remove(testFile) - if err != nil { - t.Fatalf("Failed to remove testFile: %v", err) - } - _ = <-w.Events // consume Remove event - <-time.After(50 * time.Millisecond) // wait IN_IGNORE propagated - - w.mu.Lock() - defer w.mu.Unlock() - if len(w.watches) != 0 { - t.Fatalf("Expected watches len is 0, but got: %d, %v", len(w.watches), w.watches) - } - if len(w.paths) != 0 { - t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths) - } -} - -func TestInotifyOverflow(t *testing.T) { - // We need to generate many more events than the - // fs.inotify.max_queued_events sysctl setting. - // We use multiple goroutines (one per directory) - // to speed up file creation. - numDirs := 128 - numFiles := 1024 - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - for dn := 0; dn < numDirs; dn++ { - testSubdir := fmt.Sprintf("%s/%d", testDir, dn) - - err := os.Mkdir(testSubdir, 0777) - if err != nil { - t.Fatalf("Cannot create subdir: %v", err) - } - - err = w.Add(testSubdir) - if err != nil { - t.Fatalf("Failed to add subdir: %v", err) - } - } - - errChan := make(chan error, numDirs*numFiles) - - for dn := 0; dn < numDirs; dn++ { - testSubdir := fmt.Sprintf("%s/%d", testDir, dn) - - go func() { - for fn := 0; fn < numFiles; fn++ { - testFile := fmt.Sprintf("%s/%d", testSubdir, fn) - - handle, err := os.Create(testFile) - if err != nil { - errChan <- fmt.Errorf("Create failed: %v", err) - continue - } - - err = handle.Close() - if err != nil { - errChan <- fmt.Errorf("Close failed: %v", err) - continue - } - } - }() - } - - creates := 0 - overflows := 0 - - after := time.After(10 * time.Second) - for overflows == 0 && creates < numDirs*numFiles { - select { - case <-after: - t.Fatalf("Not done") - case err := <-errChan: - t.Fatalf("Got an error from file creator goroutine: %v", err) - case err := <-w.Errors: - if err == ErrEventOverflow { - overflows++ - } else { - t.Fatalf("Got an error from watcher: %v", err) - } - case evt := <-w.Events: - if !strings.HasPrefix(evt.Name, testDir) { - t.Fatalf("Got an event for an unknown file: %s", evt.Name) - } - if evt.Op == Create { - creates++ - } - } - } - - if creates == numDirs*numFiles { - t.Fatalf("Could not trigger overflow") - } - - if overflows == 0 { - t.Fatalf("No overflow and not enough creates (expected %d, got %d)", - numDirs*numFiles, creates) - } -} diff --git a/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go b/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go deleted file mode 100644 index cd6adc27..00000000 --- a/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2016 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. - -package fsnotify - -import ( - "os" - "path/filepath" - "testing" - "time" - - "golang.org/x/sys/unix" -) - -// testExchangedataForWatcher tests the watcher with the exchangedata operation on macOS. -// -// This is widely used for atomic saves on macOS, e.g. TextMate and in Apple's NSDocument. -// -// See https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/exchangedata.2.html -// Also see: https://github.com/textmate/textmate/blob/cd016be29489eba5f3c09b7b70b06da134dda550/Frameworks/io/src/swap_file_data.cc#L20 -func testExchangedataForWatcher(t *testing.T, watchDir bool) { - // Create directory to watch - testDir1 := tempMkdir(t) - - // For the intermediate file - testDir2 := tempMkdir(t) - - defer os.RemoveAll(testDir1) - defer os.RemoveAll(testDir2) - - resolvedFilename := "TestFsnotifyEvents.file" - - // TextMate does: - // - // 1. exchangedata (intermediate, resolved) - // 2. unlink intermediate - // - // Let's try to simulate that: - resolved := filepath.Join(testDir1, resolvedFilename) - intermediate := filepath.Join(testDir2, resolvedFilename+"~") - - // Make sure we create the file before we start watching - createAndSyncFile(t, resolved) - - watcher := newWatcher(t) - - // Test both variants in isolation - if watchDir { - addWatch(t, watcher, testDir1) - } else { - addWatch(t, watcher, resolved) - } - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var removeReceived counter - var createReceived counter - - done := make(chan bool) - - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(resolved) { - if event.Op&Remove == Remove { - removeReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - } - t.Logf("event received: %s", event) - } - done <- true - }() - - // Repeat to make sure the watched file/directory "survives" the REMOVE/CREATE loop. - for i := 1; i <= 3; i++ { - // The intermediate file is created in a folder outside the watcher - createAndSyncFile(t, intermediate) - - // 1. Swap - if err := unix.Exchangedata(intermediate, resolved, 0); err != nil { - t.Fatalf("[%d] exchangedata failed: %s", i, err) - } - - time.Sleep(50 * time.Millisecond) - - // 2. Delete the intermediate file - err := os.Remove(intermediate) - - if err != nil { - t.Fatalf("[%d] remove %s failed: %s", i, intermediate, err) - } - - time.Sleep(50 * time.Millisecond) - - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - - // The events will be (CHMOD + REMOVE + CREATE) X 2. Let's focus on the last two: - if removeReceived.value() < 3 { - t.Fatal("fsnotify remove events have not been received after 500 ms") - } - - if createReceived.value() < 3 { - t.Fatal("fsnotify create events have not been received after 500 ms") - } - - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -// TestExchangedataInWatchedDir test exchangedata operation on file in watched dir. -func TestExchangedataInWatchedDir(t *testing.T) { - testExchangedataForWatcher(t, true) -} - -// TestExchangedataInWatchedDir test exchangedata operation on watched file. -func TestExchangedataInWatchedFile(t *testing.T) { - testExchangedataForWatcher(t, false) -} - -func createAndSyncFile(t *testing.T, filepath string) { - f1, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating %s failed: %s", filepath, err) - } - f1.Sync() - f1.Close() -} diff --git a/vendor/github.com/fsnotify/fsnotify/integration_test.go b/vendor/github.com/fsnotify/fsnotify/integration_test.go deleted file mode 100644 index 8b7e9d3e..00000000 --- a/vendor/github.com/fsnotify/fsnotify/integration_test.go +++ /dev/null @@ -1,1237 +0,0 @@ -// Copyright 2010 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. - -// +build !plan9,!solaris - -package fsnotify - -import ( - "io/ioutil" - "os" - "os/exec" - "path" - "path/filepath" - "runtime" - "sync/atomic" - "testing" - "time" -) - -// An atomic counter -type counter struct { - val int32 -} - -func (c *counter) increment() { - atomic.AddInt32(&c.val, 1) -} - -func (c *counter) value() int32 { - return atomic.LoadInt32(&c.val) -} - -func (c *counter) reset() { - atomic.StoreInt32(&c.val, 0) -} - -// tempMkdir makes a temporary directory -func tempMkdir(t *testing.T) string { - dir, err := ioutil.TempDir("", "fsnotify") - if err != nil { - t.Fatalf("failed to create test directory: %s", err) - } - return dir -} - -// tempMkFile makes a temporary file. -func tempMkFile(t *testing.T, dir string) string { - f, err := ioutil.TempFile(dir, "fsnotify") - if err != nil { - t.Fatalf("failed to create test file: %v", err) - } - defer f.Close() - return f.Name() -} - -// newWatcher initializes an fsnotify Watcher instance. -func newWatcher(t *testing.T) *Watcher { - watcher, err := NewWatcher() - if err != nil { - t.Fatalf("NewWatcher() failed: %s", err) - } - return watcher -} - -// addWatch adds a watch for a directory -func addWatch(t *testing.T, watcher *Watcher, dir string) { - if err := watcher.Add(dir); err != nil { - t.Fatalf("watcher.Add(%q) failed: %s", dir, err) - } -} - -func TestFsnotifyMultipleOperations(t *testing.T) { - watcher := newWatcher(t) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create directory that's not watched - testDirToMoveFiles := tempMkdir(t) - defer os.RemoveAll(testDirToMoveFiles) - - testFile := filepath.Join(testDir, "TestFsnotifySeq.testfile") - testFileRenamed := filepath.Join(testDirToMoveFiles, "TestFsnotifySeqRename.testfile") - - addWatch(t, watcher, testDir) - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, modifyReceived, deleteReceived, renameReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - if event.Op&Write == Write { - modifyReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - if event.Op&Rename == Rename { - renameReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // Modify the file outside of the watched dir - f, err = os.Open(testFileRenamed) - if err != nil { - t.Fatalf("open test renamed file failed: %s", err) - } - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Recreate the file that was moved - f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Close() - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 2 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2) - } - mReceived := modifyReceived.value() - if mReceived != 1 { - t.Fatalf("incorrect number of modify events received after 500 ms (%d vs %d)", mReceived, 1) - } - dReceived := deleteReceived.value() - rReceived := renameReceived.value() - if dReceived+rReceived != 1 { - t.Fatalf("incorrect number of rename+delete events received after 500 ms (%d vs %d)", rReceived+dReceived, 1) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyMultipleCreates(t *testing.T) { - watcher := newWatcher(t) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - testFile := filepath.Join(testDir, "TestFsnotifySeq.testfile") - - addWatch(t, watcher, testDir) - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, modifyReceived, deleteReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - if event.Op&Write == Write { - modifyReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - os.Remove(testFile) - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Recreate the file - f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Close() - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Modify - f, err = os.OpenFile(testFile, os.O_WRONLY, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Modify - f, err = os.OpenFile(testFile, os.O_WRONLY, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 2 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2) - } - mReceived := modifyReceived.value() - if mReceived < 3 { - t.Fatalf("incorrect number of modify events received after 500 ms (%d vs atleast %d)", mReceived, 3) - } - dReceived := deleteReceived.value() - if dReceived != 1 { - t.Fatalf("incorrect number of rename+delete events received after 500 ms (%d vs %d)", dReceived, 1) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyDirOnly(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - // This should NOT add any events to the fsnotify event queue - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDir, "TestFsnotifyDirOnly.testfile") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, modifyReceived, deleteReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileAlreadyExists) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - if event.Op&Write == Write { - modifyReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - os.Remove(testFile) - os.Remove(testFileAlreadyExists) - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 1 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 1) - } - mReceived := modifyReceived.value() - if mReceived != 1 { - t.Fatalf("incorrect number of modify events received after 500 ms (%d vs %d)", mReceived, 1) - } - dReceived := deleteReceived.value() - if dReceived != 2 { - t.Fatalf("incorrect number of delete events received after 500 ms (%d vs %d)", dReceived, 2) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyDeleteWatchedDir(t *testing.T) { - watcher := newWatcher(t) - defer watcher.Close() - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - addWatch(t, watcher, testDir) - - // Add a watch for testFile - addWatch(t, watcher, testFileAlreadyExists) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var deleteReceived counter - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFileAlreadyExists) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - }() - - os.RemoveAll(testDir) - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - dReceived := deleteReceived.value() - if dReceived < 2 { - t.Fatalf("did not receive at least %d delete events, received %d after 500 ms", 2, dReceived) - } -} - -func TestFsnotifySubDir(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - testFile1 := filepath.Join(testDir, "TestFsnotifyFile1.testfile") - testSubDir := filepath.Join(testDir, "sub") - testSubDirFile := filepath.Join(testDir, "sub/TestFsnotifyFile1.testfile") - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, deleteReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testSubDir) || event.Name == filepath.Clean(testFile1) { - t.Logf("event received: %s", event) - if event.Op&Create == Create { - createReceived.increment() - } - if event.Op&Remove == Remove { - deleteReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - addWatch(t, watcher, testDir) - - // Create sub-directory - if err := os.Mkdir(testSubDir, 0777); err != nil { - t.Fatalf("failed to create test sub-directory: %s", err) - } - - // Create a file - var f *os.File - f, err := os.OpenFile(testFile1, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - - // Create a file (Should not see this! we are not watching subdir) - var fs *os.File - fs, err = os.OpenFile(testSubDirFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - fs.Sync() - fs.Close() - - time.Sleep(200 * time.Millisecond) - - // Make sure receive deletes for both file and sub-directory - os.RemoveAll(testSubDir) - os.Remove(testFile1) - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 2 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2) - } - dReceived := deleteReceived.value() - if dReceived != 2 { - t.Fatalf("incorrect number of delete events received after 500 ms (%d vs %d)", dReceived, 2) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyRename(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDir, "TestFsnotifyEvents.testfile") - testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var renameReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileRenamed) { - if event.Op&Rename == Rename { - renameReceived.increment() - } - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - f.WriteString("data") - f.Sync() - f.Close() - - // Add a watch for testFile - addWatch(t, watcher, testFile) - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - if renameReceived.value() == 0 { - t.Fatal("fsnotify rename events have not been received after 500 ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } - - os.Remove(testFileRenamed) -} - -func TestFsnotifyRenameToCreate(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create directory to get file - testDirFrom := tempMkdir(t) - defer os.RemoveAll(testDirFrom) - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDirFrom, "TestFsnotifyEvents.testfile") - testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileRenamed) { - if event.Op&Create == Create { - createReceived.increment() - } - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - if createReceived.value() == 0 { - t.Fatal("fsnotify create events have not been received after 500 ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } - - os.Remove(testFileRenamed) -} - -func TestFsnotifyRenameToOverwrite(t *testing.T) { - switch runtime.GOOS { - case "plan9", "windows": - t.Skipf("skipping test on %q (os.Rename over existing file does not create event).", runtime.GOOS) - } - - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create directory to get file - testDirFrom := tempMkdir(t) - defer os.RemoveAll(testDirFrom) - - testFile := filepath.Join(testDirFrom, "TestFsnotifyEvents.testfile") - testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed") - - // Create a file - var fr *os.File - fr, err := os.OpenFile(testFileRenamed, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - fr.Sync() - fr.Close() - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var eventReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testFileRenamed) { - eventReceived.increment() - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - if eventReceived.value() == 0 { - t.Fatal("fsnotify events have not been received after 500 ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } - - os.Remove(testFileRenamed) -} - -func TestRemovalOfWatch(t *testing.T) { - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - watcher := newWatcher(t) - defer watcher.Close() - - addWatch(t, watcher, testDir) - if err := watcher.Remove(testDir); err != nil { - t.Fatalf("Could not remove the watch: %v\n", err) - } - - go func() { - select { - case ev := <-watcher.Events: - t.Fatalf("We received event: %v\n", ev) - case <-time.After(500 * time.Millisecond): - t.Log("No event received, as expected.") - } - }() - - time.Sleep(200 * time.Millisecond) - // Modify the file outside of the watched dir - f, err := os.Open(testFileAlreadyExists) - if err != nil { - t.Fatalf("Open test file failed: %s", err) - } - f.WriteString("data") - f.Sync() - f.Close() - if err := os.Chmod(testFileAlreadyExists, 0700); err != nil { - t.Fatalf("chmod failed: %s", err) - } - time.Sleep(400 * time.Millisecond) -} - -func TestFsnotifyAttrib(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("attributes don't work on Windows.") - } - - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDir, "TestFsnotifyAttrib.testfile") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - // The modifyReceived counter counts IsModify events that are not IsAttrib, - // and the attribReceived counts IsAttrib events (which are also IsModify as - // a consequence). - var modifyReceived counter - var attribReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) { - if event.Op&Write == Write { - modifyReceived.increment() - } - if event.Op&Chmod == Chmod { - attribReceived.increment() - } - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - f.WriteString("data") - f.Sync() - f.Close() - - // Add a watch for testFile - addWatch(t, watcher, testFile) - - if err := os.Chmod(testFile, 0700); err != nil { - t.Fatalf("chmod failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - // Creating/writing a file changes also the mtime, so IsAttrib should be set to true here - time.Sleep(500 * time.Millisecond) - if modifyReceived.value() != 0 { - t.Fatal("received an unexpected modify event when creating a test file") - } - if attribReceived.value() == 0 { - t.Fatal("fsnotify attribute events have not received after 500 ms") - } - - // Modifying the contents of the file does not set the attrib flag (although eg. the mtime - // might have been modified). - modifyReceived.reset() - attribReceived.reset() - - f, err = os.OpenFile(testFile, os.O_WRONLY, 0) - if err != nil { - t.Fatalf("reopening test file failed: %s", err) - } - - f.WriteString("more data") - f.Sync() - f.Close() - - time.Sleep(500 * time.Millisecond) - - if modifyReceived.value() != 1 { - t.Fatal("didn't receive a modify event after changing test file contents") - } - - if attribReceived.value() != 0 { - t.Fatal("did receive an unexpected attrib event after changing test file contents") - } - - modifyReceived.reset() - attribReceived.reset() - - // Doing a chmod on the file should trigger an event with the "attrib" flag set (the contents - // of the file are not changed though) - if err := os.Chmod(testFile, 0600); err != nil { - t.Fatalf("chmod failed: %s", err) - } - - time.Sleep(500 * time.Millisecond) - - if attribReceived.value() != 1 { - t.Fatal("didn't receive an attribute change after 500ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(1e9): - t.Fatal("event stream was not closed after 1 second") - } - - os.Remove(testFile) -} - -func TestFsnotifyClose(t *testing.T) { - watcher := newWatcher(t) - watcher.Close() - - var done int32 - go func() { - watcher.Close() - atomic.StoreInt32(&done, 1) - }() - - time.Sleep(50e6) // 50 ms - if atomic.LoadInt32(&done) == 0 { - t.Fatal("double Close() test failed: second Close() call didn't return") - } - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - if err := watcher.Add(testDir); err == nil { - t.Fatal("expected error on Watch() after Close(), got nil") - } -} - -func TestFsnotifyFakeSymlink(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("symlinks don't work on Windows.") - } - - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - var errorsReceived counter - // Receive errors on the error channel on a separate goroutine - go func() { - for errors := range watcher.Errors { - t.Logf("Received error: %s", errors) - errorsReceived.increment() - } - }() - - // Count the CREATE events received - var createEventsReceived, otherEventsReceived counter - go func() { - for ev := range watcher.Events { - t.Logf("event received: %s", ev) - if ev.Op&Create == Create { - createEventsReceived.increment() - } else { - otherEventsReceived.increment() - } - } - }() - - addWatch(t, watcher, testDir) - - if err := os.Symlink(filepath.Join(testDir, "zzz"), filepath.Join(testDir, "zzznew")); err != nil { - t.Fatalf("Failed to create bogus symlink: %s", err) - } - t.Logf("Created bogus symlink") - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - - // Should not be error, just no events for broken links (watching nothing) - if errorsReceived.value() > 0 { - t.Fatal("fsnotify errors have been received.") - } - if otherEventsReceived.value() > 0 { - t.Fatal("fsnotify other events received on the broken link") - } - - // Except for 1 create event (for the link itself) - if createEventsReceived.value() == 0 { - t.Fatal("fsnotify create events were not received after 500 ms") - } - if createEventsReceived.value() > 1 { - t.Fatal("fsnotify more create events received than expected") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() -} - -func TestCyclicSymlink(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("symlinks don't work on Windows.") - } - - watcher := newWatcher(t) - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - link := path.Join(testDir, "link") - if err := os.Symlink(".", link); err != nil { - t.Fatalf("could not make symlink: %v", err) - } - addWatch(t, watcher, testDir) - - var createEventsReceived counter - go func() { - for ev := range watcher.Events { - if ev.Op&Create == Create { - createEventsReceived.increment() - } - } - }() - - if err := os.Remove(link); err != nil { - t.Fatalf("Error removing link: %v", err) - } - - // It would be nice to be able to expect a delete event here, but kqueue has - // no way for us to get events on symlinks themselves, because opening them - // opens an fd to the file to which they point. - - if err := ioutil.WriteFile(link, []byte("foo"), 0700); err != nil { - t.Fatalf("could not make symlink: %v", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - - if got := createEventsReceived.value(); got == 0 { - t.Errorf("want at least 1 create event got %v", got) - } - - watcher.Close() -} - -// TestConcurrentRemovalOfWatch tests that concurrent calls to RemoveWatch do not race. -// See https://codereview.appspot.com/103300045/ -// go test -test.run=TestConcurrentRemovalOfWatch -test.cpu=1,1,1,1,1 -race -func TestConcurrentRemovalOfWatch(t *testing.T) { - if runtime.GOOS != "darwin" { - t.Skip("regression test for race only present on darwin") - } - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - watcher := newWatcher(t) - defer watcher.Close() - - addWatch(t, watcher, testDir) - - // Test that RemoveWatch can be invoked concurrently, with no data races. - removed1 := make(chan struct{}) - go func() { - defer close(removed1) - watcher.Remove(testDir) - }() - removed2 := make(chan struct{}) - go func() { - close(removed2) - watcher.Remove(testDir) - }() - <-removed1 - <-removed2 -} - -func TestClose(t *testing.T) { - // Regression test for #59 bad file descriptor from Close - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - watcher := newWatcher(t) - if err := watcher.Add(testDir); err != nil { - t.Fatalf("Expected no error on Add, got %v", err) - } - err := watcher.Close() - if err != nil { - t.Fatalf("Expected no error on Close, got %v.", err) - } -} - -// TestRemoveWithClose tests if one can handle Remove events and, at the same -// time, close Watcher object without any data races. -func TestRemoveWithClose(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - const fileN = 200 - tempFiles := make([]string, 0, fileN) - for i := 0; i < fileN; i++ { - tempFiles = append(tempFiles, tempMkFile(t, testDir)) - } - watcher := newWatcher(t) - if err := watcher.Add(testDir); err != nil { - t.Fatalf("Expected no error on Add, got %v", err) - } - startC, stopC := make(chan struct{}), make(chan struct{}) - errC := make(chan error) - go func() { - for { - select { - case <-watcher.Errors: - case <-watcher.Events: - case <-stopC: - return - } - } - }() - go func() { - <-startC - for _, fileName := range tempFiles { - os.Remove(fileName) - } - }() - go func() { - <-startC - errC <- watcher.Close() - }() - close(startC) - defer close(stopC) - if err := <-errC; err != nil { - t.Fatalf("Expected no error on Close, got %v.", err) - } -} - -func testRename(file1, file2 string) error { - switch runtime.GOOS { - case "windows", "plan9": - return os.Rename(file1, file2) - default: - cmd := exec.Command("mv", file1, file2) - return cmd.Run() - } -} diff --git a/vendor/github.com/fsnotify/fsnotify/kqueue.go b/vendor/github.com/fsnotify/fsnotify/kqueue.go deleted file mode 100644 index 86e76a3d..00000000 --- a/vendor/github.com/fsnotify/fsnotify/kqueue.go +++ /dev/null @@ -1,521 +0,0 @@ -// Copyright 2010 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. - -// +build freebsd openbsd netbsd dragonfly darwin - -package fsnotify - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "sync" - "time" - - "golang.org/x/sys/unix" -) - -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct { - Events chan Event - Errors chan error - done chan struct{} // Channel for sending a "quit message" to the reader goroutine - - kq int // File descriptor (as returned by the kqueue() syscall). - - mu sync.Mutex // Protects access to watcher data - watches map[string]int // Map of watched file descriptors (key: path). - externalWatches map[string]bool // Map of watches added by user of the library. - dirFlags map[string]uint32 // Map of watched directories to fflags used in kqueue. - paths map[int]pathInfo // Map file descriptors to path names for processing kqueue events. - fileExists map[string]bool // Keep track of if we know this file exists (to stop duplicate create events). - isClosed bool // Set to true when Close() is first called -} - -type pathInfo struct { - name string - isDir bool -} - -// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events. -func NewWatcher() (*Watcher, error) { - kq, err := kqueue() - if err != nil { - return nil, err - } - - w := &Watcher{ - kq: kq, - watches: make(map[string]int), - dirFlags: make(map[string]uint32), - paths: make(map[int]pathInfo), - fileExists: make(map[string]bool), - externalWatches: make(map[string]bool), - Events: make(chan Event), - Errors: make(chan error), - done: make(chan struct{}), - } - - go w.readEvents() - return w, nil -} - -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - w.mu.Lock() - if w.isClosed { - w.mu.Unlock() - return nil - } - w.isClosed = true - - // copy paths to remove while locked - var pathsToRemove = make([]string, 0, len(w.watches)) - for name := range w.watches { - pathsToRemove = append(pathsToRemove, name) - } - w.mu.Unlock() - // unlock before calling Remove, which also locks - - for _, name := range pathsToRemove { - w.Remove(name) - } - - // send a "quit" message to the reader goroutine - close(w.done) - - return nil -} - -// Add starts watching the named file or directory (non-recursively). -func (w *Watcher) Add(name string) error { - w.mu.Lock() - w.externalWatches[name] = true - w.mu.Unlock() - _, err := w.addWatch(name, noteAllEvents) - return err -} - -// Remove stops watching the the named file or directory (non-recursively). -func (w *Watcher) Remove(name string) error { - name = filepath.Clean(name) - w.mu.Lock() - watchfd, ok := w.watches[name] - w.mu.Unlock() - if !ok { - return fmt.Errorf("can't remove non-existent kevent watch for: %s", name) - } - - const registerRemove = unix.EV_DELETE - if err := register(w.kq, []int{watchfd}, registerRemove, 0); err != nil { - return err - } - - unix.Close(watchfd) - - w.mu.Lock() - isDir := w.paths[watchfd].isDir - delete(w.watches, name) - delete(w.paths, watchfd) - delete(w.dirFlags, name) - w.mu.Unlock() - - // Find all watched paths that are in this directory that are not external. - if isDir { - var pathsToRemove []string - w.mu.Lock() - for _, path := range w.paths { - wdir, _ := filepath.Split(path.name) - if filepath.Clean(wdir) == name { - if !w.externalWatches[path.name] { - pathsToRemove = append(pathsToRemove, path.name) - } - } - } - w.mu.Unlock() - for _, name := range pathsToRemove { - // Since these are internal, not much sense in propagating error - // to the user, as that will just confuse them with an error about - // a path they did not explicitly watch themselves. - w.Remove(name) - } - } - - return nil -} - -// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE) -const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME - -// keventWaitTime to block on each read from kevent -var keventWaitTime = durationToTimespec(100 * time.Millisecond) - -// addWatch adds name to the watched file set. -// The flags are interpreted as described in kevent(2). -// Returns the real path to the file which was added, if any, which may be different from the one passed in the case of symlinks. -func (w *Watcher) addWatch(name string, flags uint32) (string, error) { - var isDir bool - // Make ./name and name equivalent - name = filepath.Clean(name) - - w.mu.Lock() - if w.isClosed { - w.mu.Unlock() - return "", errors.New("kevent instance already closed") - } - watchfd, alreadyWatching := w.watches[name] - // We already have a watch, but we can still override flags. - if alreadyWatching { - isDir = w.paths[watchfd].isDir - } - w.mu.Unlock() - - if !alreadyWatching { - fi, err := os.Lstat(name) - if err != nil { - return "", err - } - - // Don't watch sockets. - if fi.Mode()&os.ModeSocket == os.ModeSocket { - return "", nil - } - - // Don't watch named pipes. - if fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe { - return "", nil - } - - // Follow Symlinks - // Unfortunately, Linux can add bogus symlinks to watch list without - // issue, and Windows can't do symlinks period (AFAIK). To maintain - // consistency, we will act like everything is fine. There will simply - // be no file events for broken symlinks. - // Hence the returns of nil on errors. - if fi.Mode()&os.ModeSymlink == os.ModeSymlink { - name, err = filepath.EvalSymlinks(name) - if err != nil { - return "", nil - } - - w.mu.Lock() - _, alreadyWatching = w.watches[name] - w.mu.Unlock() - - if alreadyWatching { - return name, nil - } - - fi, err = os.Lstat(name) - if err != nil { - return "", nil - } - } - - watchfd, err = unix.Open(name, openMode, 0700) - if watchfd == -1 { - return "", err - } - - isDir = fi.IsDir() - } - - const registerAdd = unix.EV_ADD | unix.EV_CLEAR | unix.EV_ENABLE - if err := register(w.kq, []int{watchfd}, registerAdd, flags); err != nil { - unix.Close(watchfd) - return "", err - } - - if !alreadyWatching { - w.mu.Lock() - w.watches[name] = watchfd - w.paths[watchfd] = pathInfo{name: name, isDir: isDir} - w.mu.Unlock() - } - - if isDir { - // Watch the directory if it has not been watched before, - // or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles) - w.mu.Lock() - - watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE && - (!alreadyWatching || (w.dirFlags[name]&unix.NOTE_WRITE) != unix.NOTE_WRITE) - // Store flags so this watch can be updated later - w.dirFlags[name] = flags - w.mu.Unlock() - - if watchDir { - if err := w.watchDirectoryFiles(name); err != nil { - return "", err - } - } - } - return name, nil -} - -// readEvents reads from kqueue and converts the received kevents into -// Event values that it sends down the Events channel. -func (w *Watcher) readEvents() { - eventBuffer := make([]unix.Kevent_t, 10) - -loop: - for { - // See if there is a message on the "done" channel - select { - case <-w.done: - break loop - default: - } - - // Get new events - kevents, err := read(w.kq, eventBuffer, &keventWaitTime) - // EINTR is okay, the syscall was interrupted before timeout expired. - if err != nil && err != unix.EINTR { - select { - case w.Errors <- err: - case <-w.done: - break loop - } - continue - } - - // Flush the events we received to the Events channel - for len(kevents) > 0 { - kevent := &kevents[0] - watchfd := int(kevent.Ident) - mask := uint32(kevent.Fflags) - w.mu.Lock() - path := w.paths[watchfd] - w.mu.Unlock() - event := newEvent(path.name, mask) - - if path.isDir && !(event.Op&Remove == Remove) { - // Double check to make sure the directory exists. This can happen when - // we do a rm -fr on a recursively watched folders and we receive a - // modification event first but the folder has been deleted and later - // receive the delete event - if _, err := os.Lstat(event.Name); os.IsNotExist(err) { - // mark is as delete event - event.Op |= Remove - } - } - - if event.Op&Rename == Rename || event.Op&Remove == Remove { - w.Remove(event.Name) - w.mu.Lock() - delete(w.fileExists, event.Name) - w.mu.Unlock() - } - - if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) { - w.sendDirectoryChangeEvents(event.Name) - } else { - // Send the event on the Events channel. - select { - case w.Events <- event: - case <-w.done: - break loop - } - } - - if event.Op&Remove == Remove { - // Look for a file that may have overwritten this. - // For example, mv f1 f2 will delete f2, then create f2. - if path.isDir { - fileDir := filepath.Clean(event.Name) - w.mu.Lock() - _, found := w.watches[fileDir] - w.mu.Unlock() - if found { - // make sure the directory exists before we watch for changes. When we - // do a recursive watch and perform rm -fr, the parent directory might - // have gone missing, ignore the missing directory and let the - // upcoming delete event remove the watch from the parent directory. - if _, err := os.Lstat(fileDir); err == nil { - w.sendDirectoryChangeEvents(fileDir) - } - } - } else { - filePath := filepath.Clean(event.Name) - if fileInfo, err := os.Lstat(filePath); err == nil { - w.sendFileCreatedEventIfNew(filePath, fileInfo) - } - } - } - - // Move to next event - kevents = kevents[1:] - } - } - - // cleanup - err := unix.Close(w.kq) - if err != nil { - // only way the previous loop breaks is if w.done was closed so we need to async send to w.Errors. - select { - case w.Errors <- err: - default: - } - } - close(w.Events) - close(w.Errors) -} - -// newEvent returns an platform-independent Event based on kqueue Fflags. -func newEvent(name string, mask uint32) Event { - e := Event{Name: name} - if mask&unix.NOTE_DELETE == unix.NOTE_DELETE { - e.Op |= Remove - } - if mask&unix.NOTE_WRITE == unix.NOTE_WRITE { - e.Op |= Write - } - if mask&unix.NOTE_RENAME == unix.NOTE_RENAME { - e.Op |= Rename - } - if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB { - e.Op |= Chmod - } - return e -} - -func newCreateEvent(name string) Event { - return Event{Name: name, Op: Create} -} - -// watchDirectoryFiles to mimic inotify when adding a watch on a directory -func (w *Watcher) watchDirectoryFiles(dirPath string) error { - // Get all files - files, err := ioutil.ReadDir(dirPath) - if err != nil { - return err - } - - for _, fileInfo := range files { - filePath := filepath.Join(dirPath, fileInfo.Name()) - filePath, err = w.internalWatch(filePath, fileInfo) - if err != nil { - return err - } - - w.mu.Lock() - w.fileExists[filePath] = true - w.mu.Unlock() - } - - return nil -} - -// sendDirectoryEvents searches the directory for newly created files -// and sends them over the event channel. This functionality is to have -// the BSD version of fsnotify match Linux inotify which provides a -// create event for files created in a watched directory. -func (w *Watcher) sendDirectoryChangeEvents(dirPath string) { - // Get all files - files, err := ioutil.ReadDir(dirPath) - if err != nil { - select { - case w.Errors <- err: - case <-w.done: - return - } - } - - // Search for new files - for _, fileInfo := range files { - filePath := filepath.Join(dirPath, fileInfo.Name()) - err := w.sendFileCreatedEventIfNew(filePath, fileInfo) - - if err != nil { - return - } - } -} - -// sendFileCreatedEvent sends a create event if the file isn't already being tracked. -func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) { - w.mu.Lock() - _, doesExist := w.fileExists[filePath] - w.mu.Unlock() - if !doesExist { - // Send create event - select { - case w.Events <- newCreateEvent(filePath): - case <-w.done: - return - } - } - - // like watchDirectoryFiles (but without doing another ReadDir) - filePath, err = w.internalWatch(filePath, fileInfo) - if err != nil { - return err - } - - w.mu.Lock() - w.fileExists[filePath] = true - w.mu.Unlock() - - return nil -} - -func (w *Watcher) internalWatch(name string, fileInfo os.FileInfo) (string, error) { - if fileInfo.IsDir() { - // mimic Linux providing delete events for subdirectories - // but preserve the flags used if currently watching subdirectory - w.mu.Lock() - flags := w.dirFlags[name] - w.mu.Unlock() - - flags |= unix.NOTE_DELETE | unix.NOTE_RENAME - return w.addWatch(name, flags) - } - - // watch file to mimic Linux inotify - return w.addWatch(name, noteAllEvents) -} - -// kqueue creates a new kernel event queue and returns a descriptor. -func kqueue() (kq int, err error) { - kq, err = unix.Kqueue() - if kq == -1 { - return kq, err - } - return kq, nil -} - -// register events with the queue -func register(kq int, fds []int, flags int, fflags uint32) error { - changes := make([]unix.Kevent_t, len(fds)) - - for i, fd := range fds { - // SetKevent converts int to the platform-specific types: - unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags) - changes[i].Fflags = fflags - } - - // register the events - success, err := unix.Kevent(kq, changes, nil, nil) - if success == -1 { - return err - } - return nil -} - -// read retrieves pending events, or waits until an event occurs. -// A timeout of nil blocks indefinitely, while 0 polls the queue. -func read(kq int, events []unix.Kevent_t, timeout *unix.Timespec) ([]unix.Kevent_t, error) { - n, err := unix.Kevent(kq, nil, events, timeout) - if err != nil { - return nil, err - } - return events[0:n], nil -} - -// durationToTimespec prepares a timeout value -func durationToTimespec(d time.Duration) unix.Timespec { - return unix.NsecToTimespec(d.Nanoseconds()) -} diff --git a/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go b/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go deleted file mode 100644 index 7d8de145..00000000 --- a/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2013 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. - -// +build freebsd openbsd netbsd dragonfly - -package fsnotify - -import "golang.org/x/sys/unix" - -const openMode = unix.O_NONBLOCK | unix.O_RDONLY diff --git a/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go b/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go deleted file mode 100644 index 9139e171..00000000 --- a/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2013 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. - -// +build darwin - -package fsnotify - -import "golang.org/x/sys/unix" - -// note: this constant is not defined on BSD -const openMode = unix.O_EVTONLY diff --git a/vendor/github.com/fsnotify/fsnotify/windows.go b/vendor/github.com/fsnotify/fsnotify/windows.go deleted file mode 100644 index 09436f31..00000000 --- a/vendor/github.com/fsnotify/fsnotify/windows.go +++ /dev/null @@ -1,561 +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. - -// +build windows - -package fsnotify - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "runtime" - "sync" - "syscall" - "unsafe" -) - -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct { - Events chan Event - Errors chan error - isClosed bool // Set to true when Close() is first called - mu sync.Mutex // Map access - port syscall.Handle // Handle to completion port - watches watchMap // Map of watches (key: i-number) - input chan *input // Inputs to the reader are sent on this channel - quit chan chan<- error -} - -// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events. -func NewWatcher() (*Watcher, error) { - port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0) - if e != nil { - return nil, os.NewSyscallError("CreateIoCompletionPort", e) - } - w := &Watcher{ - port: port, - watches: make(watchMap), - input: make(chan *input, 1), - Events: make(chan Event, 50), - Errors: make(chan error), - quit: make(chan chan<- error, 1), - } - go w.readEvents() - return w, nil -} - -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - if w.isClosed { - return nil - } - w.isClosed = true - - // Send "quit" message to the reader goroutine - ch := make(chan error) - w.quit <- ch - if err := w.wakeupReader(); err != nil { - return err - } - return <-ch -} - -// Add starts watching the named file or directory (non-recursively). -func (w *Watcher) Add(name string) error { - if w.isClosed { - return errors.New("watcher already closed") - } - in := &input{ - op: opAddWatch, - path: filepath.Clean(name), - flags: sysFSALLEVENTS, - reply: make(chan error), - } - w.input <- in - if err := w.wakeupReader(); err != nil { - return err - } - return <-in.reply -} - -// Remove stops watching the the named file or directory (non-recursively). -func (w *Watcher) Remove(name string) error { - in := &input{ - op: opRemoveWatch, - path: filepath.Clean(name), - reply: make(chan error), - } - w.input <- in - if err := w.wakeupReader(); err != nil { - return err - } - return <-in.reply -} - -const ( - // Options for AddWatch - sysFSONESHOT = 0x80000000 - sysFSONLYDIR = 0x1000000 - - // Events - sysFSACCESS = 0x1 - sysFSALLEVENTS = 0xfff - sysFSATTRIB = 0x4 - sysFSCLOSE = 0x18 - sysFSCREATE = 0x100 - sysFSDELETE = 0x200 - sysFSDELETESELF = 0x400 - sysFSMODIFY = 0x2 - sysFSMOVE = 0xc0 - sysFSMOVEDFROM = 0x40 - sysFSMOVEDTO = 0x80 - sysFSMOVESELF = 0x800 - - // Special events - sysFSIGNORED = 0x8000 - sysFSQOVERFLOW = 0x4000 -) - -func newEvent(name string, mask uint32) Event { - e := Event{Name: name} - if mask&sysFSCREATE == sysFSCREATE || mask&sysFSMOVEDTO == sysFSMOVEDTO { - e.Op |= Create - } - if mask&sysFSDELETE == sysFSDELETE || mask&sysFSDELETESELF == sysFSDELETESELF { - e.Op |= Remove - } - if mask&sysFSMODIFY == sysFSMODIFY { - e.Op |= Write - } - if mask&sysFSMOVE == sysFSMOVE || mask&sysFSMOVESELF == sysFSMOVESELF || mask&sysFSMOVEDFROM == sysFSMOVEDFROM { - e.Op |= Rename - } - if mask&sysFSATTRIB == sysFSATTRIB { - e.Op |= Chmod - } - return e -} - -const ( - opAddWatch = iota - opRemoveWatch -) - -const ( - provisional uint64 = 1 << (32 + iota) -) - -type input struct { - op int - path string - flags uint32 - reply chan error -} - -type inode struct { - handle syscall.Handle - volume uint32 - index uint64 -} - -type watch struct { - ov syscall.Overlapped - ino *inode // i-number - path string // Directory path - mask uint64 // Directory itself is being watched with these notify flags - names map[string]uint64 // Map of names being watched and their notify flags - rename string // Remembers the old name while renaming a file - buf [4096]byte -} - -type indexMap map[uint64]*watch -type watchMap map[uint32]indexMap - -func (w *Watcher) wakeupReader() error { - e := syscall.PostQueuedCompletionStatus(w.port, 0, 0, nil) - if e != nil { - return os.NewSyscallError("PostQueuedCompletionStatus", e) - } - return nil -} - -func getDir(pathname string) (dir string, err error) { - attr, e := syscall.GetFileAttributes(syscall.StringToUTF16Ptr(pathname)) - if e != nil { - return "", os.NewSyscallError("GetFileAttributes", e) - } - if attr&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 { - dir = pathname - } else { - dir, _ = filepath.Split(pathname) - dir = filepath.Clean(dir) - } - return -} - -func getIno(path string) (ino *inode, err error) { - h, e := syscall.CreateFile(syscall.StringToUTF16Ptr(path), - syscall.FILE_LIST_DIRECTORY, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, - nil, syscall.OPEN_EXISTING, - syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OVERLAPPED, 0) - if e != nil { - return nil, os.NewSyscallError("CreateFile", e) - } - var fi syscall.ByHandleFileInformation - if e = syscall.GetFileInformationByHandle(h, &fi); e != nil { - syscall.CloseHandle(h) - return nil, os.NewSyscallError("GetFileInformationByHandle", e) - } - ino = &inode{ - handle: h, - volume: fi.VolumeSerialNumber, - index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow), - } - return ino, nil -} - -// Must run within the I/O thread. -func (m watchMap) get(ino *inode) *watch { - if i := m[ino.volume]; i != nil { - return i[ino.index] - } - return nil -} - -// Must run within the I/O thread. -func (m watchMap) set(ino *inode, watch *watch) { - i := m[ino.volume] - if i == nil { - i = make(indexMap) - m[ino.volume] = i - } - i[ino.index] = watch -} - -// Must run within the I/O thread. -func (w *Watcher) addWatch(pathname string, flags uint64) error { - dir, err := getDir(pathname) - if err != nil { - return err - } - if flags&sysFSONLYDIR != 0 && pathname != dir { - return nil - } - ino, err := getIno(dir) - if err != nil { - return err - } - w.mu.Lock() - watchEntry := w.watches.get(ino) - w.mu.Unlock() - if watchEntry == nil { - if _, e := syscall.CreateIoCompletionPort(ino.handle, w.port, 0, 0); e != nil { - syscall.CloseHandle(ino.handle) - return os.NewSyscallError("CreateIoCompletionPort", e) - } - watchEntry = &watch{ - ino: ino, - path: dir, - names: make(map[string]uint64), - } - w.mu.Lock() - w.watches.set(ino, watchEntry) - w.mu.Unlock() - flags |= provisional - } else { - syscall.CloseHandle(ino.handle) - } - if pathname == dir { - watchEntry.mask |= flags - } else { - watchEntry.names[filepath.Base(pathname)] |= flags - } - if err = w.startRead(watchEntry); err != nil { - return err - } - if pathname == dir { - watchEntry.mask &= ^provisional - } else { - watchEntry.names[filepath.Base(pathname)] &= ^provisional - } - return nil -} - -// Must run within the I/O thread. -func (w *Watcher) remWatch(pathname string) error { - dir, err := getDir(pathname) - if err != nil { - return err - } - ino, err := getIno(dir) - if err != nil { - return err - } - w.mu.Lock() - watch := w.watches.get(ino) - w.mu.Unlock() - if watch == nil { - return fmt.Errorf("can't remove non-existent watch for: %s", pathname) - } - if pathname == dir { - w.sendEvent(watch.path, watch.mask&sysFSIGNORED) - watch.mask = 0 - } else { - name := filepath.Base(pathname) - w.sendEvent(filepath.Join(watch.path, name), watch.names[name]&sysFSIGNORED) - delete(watch.names, name) - } - return w.startRead(watch) -} - -// Must run within the I/O thread. -func (w *Watcher) deleteWatch(watch *watch) { - for name, mask := range watch.names { - if mask&provisional == 0 { - w.sendEvent(filepath.Join(watch.path, name), mask&sysFSIGNORED) - } - delete(watch.names, name) - } - if watch.mask != 0 { - if watch.mask&provisional == 0 { - w.sendEvent(watch.path, watch.mask&sysFSIGNORED) - } - watch.mask = 0 - } -} - -// Must run within the I/O thread. -func (w *Watcher) startRead(watch *watch) error { - if e := syscall.CancelIo(watch.ino.handle); e != nil { - w.Errors <- os.NewSyscallError("CancelIo", e) - w.deleteWatch(watch) - } - mask := toWindowsFlags(watch.mask) - for _, m := range watch.names { - mask |= toWindowsFlags(m) - } - if mask == 0 { - if e := syscall.CloseHandle(watch.ino.handle); e != nil { - w.Errors <- os.NewSyscallError("CloseHandle", e) - } - w.mu.Lock() - delete(w.watches[watch.ino.volume], watch.ino.index) - w.mu.Unlock() - return nil - } - e := syscall.ReadDirectoryChanges(watch.ino.handle, &watch.buf[0], - uint32(unsafe.Sizeof(watch.buf)), false, mask, nil, &watch.ov, 0) - if e != nil { - err := os.NewSyscallError("ReadDirectoryChanges", e) - if e == syscall.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 { - // Watched directory was probably removed - if w.sendEvent(watch.path, watch.mask&sysFSDELETESELF) { - if watch.mask&sysFSONESHOT != 0 { - watch.mask = 0 - } - } - err = nil - } - w.deleteWatch(watch) - w.startRead(watch) - return err - } - return nil -} - -// readEvents reads from the I/O completion port, converts the -// received events into Event objects and sends them via the Events channel. -// Entry point to the I/O thread. -func (w *Watcher) readEvents() { - var ( - n, key uint32 - ov *syscall.Overlapped - ) - runtime.LockOSThread() - - for { - e := syscall.GetQueuedCompletionStatus(w.port, &n, &key, &ov, syscall.INFINITE) - watch := (*watch)(unsafe.Pointer(ov)) - - if watch == nil { - select { - case ch := <-w.quit: - w.mu.Lock() - var indexes []indexMap - for _, index := range w.watches { - indexes = append(indexes, index) - } - w.mu.Unlock() - for _, index := range indexes { - for _, watch := range index { - w.deleteWatch(watch) - w.startRead(watch) - } - } - var err error - if e := syscall.CloseHandle(w.port); e != nil { - err = os.NewSyscallError("CloseHandle", e) - } - close(w.Events) - close(w.Errors) - ch <- err - return - case in := <-w.input: - switch in.op { - case opAddWatch: - in.reply <- w.addWatch(in.path, uint64(in.flags)) - case opRemoveWatch: - in.reply <- w.remWatch(in.path) - } - default: - } - continue - } - - switch e { - case syscall.ERROR_MORE_DATA: - if watch == nil { - w.Errors <- errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer") - } else { - // The i/o succeeded but the buffer is full. - // In theory we should be building up a full packet. - // In practice we can get away with just carrying on. - n = uint32(unsafe.Sizeof(watch.buf)) - } - case syscall.ERROR_ACCESS_DENIED: - // Watched directory was probably removed - w.sendEvent(watch.path, watch.mask&sysFSDELETESELF) - w.deleteWatch(watch) - w.startRead(watch) - continue - case syscall.ERROR_OPERATION_ABORTED: - // CancelIo was called on this handle - continue - default: - w.Errors <- os.NewSyscallError("GetQueuedCompletionPort", e) - continue - case nil: - } - - var offset uint32 - for { - if n == 0 { - w.Events <- newEvent("", sysFSQOVERFLOW) - w.Errors <- errors.New("short read in readEvents()") - break - } - - // Point "raw" to the event in the buffer - raw := (*syscall.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset])) - buf := (*[syscall.MAX_PATH]uint16)(unsafe.Pointer(&raw.FileName)) - name := syscall.UTF16ToString(buf[:raw.FileNameLength/2]) - fullname := filepath.Join(watch.path, name) - - var mask uint64 - switch raw.Action { - case syscall.FILE_ACTION_REMOVED: - mask = sysFSDELETESELF - case syscall.FILE_ACTION_MODIFIED: - mask = sysFSMODIFY - case syscall.FILE_ACTION_RENAMED_OLD_NAME: - watch.rename = name - case syscall.FILE_ACTION_RENAMED_NEW_NAME: - if watch.names[watch.rename] != 0 { - watch.names[name] |= watch.names[watch.rename] - delete(watch.names, watch.rename) - mask = sysFSMOVESELF - } - } - - sendNameEvent := func() { - if w.sendEvent(fullname, watch.names[name]&mask) { - if watch.names[name]&sysFSONESHOT != 0 { - delete(watch.names, name) - } - } - } - if raw.Action != syscall.FILE_ACTION_RENAMED_NEW_NAME { - sendNameEvent() - } - if raw.Action == syscall.FILE_ACTION_REMOVED { - w.sendEvent(fullname, watch.names[name]&sysFSIGNORED) - delete(watch.names, name) - } - if w.sendEvent(fullname, watch.mask&toFSnotifyFlags(raw.Action)) { - if watch.mask&sysFSONESHOT != 0 { - watch.mask = 0 - } - } - if raw.Action == syscall.FILE_ACTION_RENAMED_NEW_NAME { - fullname = filepath.Join(watch.path, watch.rename) - sendNameEvent() - } - - // Move to the next event in the buffer - if raw.NextEntryOffset == 0 { - break - } - offset += raw.NextEntryOffset - - // Error! - if offset >= n { - w.Errors <- errors.New("Windows system assumed buffer larger than it is, events have likely been missed.") - break - } - } - - if err := w.startRead(watch); err != nil { - w.Errors <- err - } - } -} - -func (w *Watcher) sendEvent(name string, mask uint64) bool { - if mask == 0 { - return false - } - event := newEvent(name, uint32(mask)) - select { - case ch := <-w.quit: - w.quit <- ch - case w.Events <- event: - } - return true -} - -func toWindowsFlags(mask uint64) uint32 { - var m uint32 - if mask&sysFSACCESS != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_LAST_ACCESS - } - if mask&sysFSMODIFY != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_LAST_WRITE - } - if mask&sysFSATTRIB != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_ATTRIBUTES - } - if mask&(sysFSMOVE|sysFSCREATE|sysFSDELETE) != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_FILE_NAME | syscall.FILE_NOTIFY_CHANGE_DIR_NAME - } - return m -} - -func toFSnotifyFlags(action uint32) uint64 { - switch action { - case syscall.FILE_ACTION_ADDED: - return sysFSCREATE - case syscall.FILE_ACTION_REMOVED: - return sysFSDELETE - case syscall.FILE_ACTION_MODIFIED: - return sysFSMODIFY - case syscall.FILE_ACTION_RENAMED_OLD_NAME: - return sysFSMOVEDFROM - case syscall.FILE_ACTION_RENAMED_NEW_NAME: - return sysFSMOVEDTO - } - return 0 -} diff --git a/vendor/github.com/go-kit/kit/.gitignore b/vendor/github.com/go-kit/kit/.gitignore deleted file mode 100644 index 6062401c..00000000 --- a/vendor/github.com/go-kit/kit/.gitignore +++ /dev/null @@ -1,45 +0,0 @@ -examples/addsvc/addsvc -examples/addsvc/client/client -examples/apigateway/apigateway -examples/profilesvc/profilesvc -examples/stringsvc1/stringsvc1 -examples/stringsvc2/stringsvc2 -examples/stringsvc3/stringsvc3 -*.coverprofile - -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test -_old* - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -# https://github.com/github/gitignore/blob/master/Global/Vim.gitignore -# swap -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -# session -Session.vim -# temporary -.netrwhist -*~ -# auto-generated tag files -tags - diff --git a/vendor/github.com/go-kit/kit/.travis.yml b/vendor/github.com/go-kit/kit/.travis.yml deleted file mode 100644 index 31624b2b..00000000 --- a/vendor/github.com/go-kit/kit/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: go - -env: - - COVERALLS_TOKEN=MYSkSqcsWXd6DmP6TnSeiDhtvuL4u6ndp - -before_install: - - go get github.com/mattn/goveralls - - go get github.com/modocache/gover - -script: - - go test -race -v ./... - - ./coveralls.bash - -go: - - 1.9.x - - tip diff --git a/vendor/github.com/go-kit/kit/CONTRIBUTING.md b/vendor/github.com/go-kit/kit/CONTRIBUTING.md deleted file mode 100644 index c0751f85..00000000 --- a/vendor/github.com/go-kit/kit/CONTRIBUTING.md +++ /dev/null @@ -1,18 +0,0 @@ -# Contributing - -First, thank you for contributing! We love and encourage pull requests from everyone. - -Before submitting major changes, here are a few guidelines to follow: - -1. Check the [open issues][issues] and [pull requests][prs] for existing discussions. -1. Open an [issue][issues] first, to discuss a new feature or enhancement. -1. Write tests, and make sure the test suite passes locally and on CI. -1. Open a pull request, and reference the relevant issue(s). -1. After receiving feedback, [squash your commits][squash] and add a [great commit message][message]. -1. Have fun! - -[issues]: https://github.com/go-kit/kit/issues -[prs]: https://github.com/go-kit/kit/pulls -[squash]: http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html -[message]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html - diff --git a/vendor/github.com/go-kit/kit/LICENSE b/vendor/github.com/go-kit/kit/LICENSE deleted file mode 100644 index 9d83342a..00000000 --- a/vendor/github.com/go-kit/kit/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Peter Bourgon - -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. - diff --git a/vendor/github.com/go-kit/kit/README.md b/vendor/github.com/go-kit/kit/README.md deleted file mode 100644 index 2d9a2b4d..00000000 --- a/vendor/github.com/go-kit/kit/README.md +++ /dev/null @@ -1,119 +0,0 @@ -# Go kit [![Circle CI](https://circleci.com/gh/go-kit/kit.svg?style=shield)](https://circleci.com/gh/go-kit/kit) [![Travis CI](https://travis-ci.org/go-kit/kit.svg?branch=master)](https://travis-ci.org/go-kit/kit) [![GoDoc](https://godoc.org/github.com/go-kit/kit?status.svg)](https://godoc.org/github.com/go-kit/kit) [![Coverage Status](https://coveralls.io/repos/go-kit/kit/badge.svg?branch=master&service=github)](https://coveralls.io/github/go-kit/kit?branch=master) [![Go Report Card](https://goreportcard.com/badge/go-kit/kit)](https://goreportcard.com/report/go-kit/kit) [![Sourcegraph](https://sourcegraph.com/github.com/go-kit/kit/-/badge.svg)](https://sourcegraph.com/github.com/go-kit/kit?badge) - -**Go kit** is a **programming toolkit** for building microservices -(or elegant monoliths) in Go. We solve common problems in distributed -systems and application architecture so you can focus on delivering -business value. - -- Website: [gokit.io](https://gokit.io) -- Mailing list: [go-kit](https://groups.google.com/forum/#!forum/go-kit) -- Slack: [gophers.slack.com](https://gophers.slack.com) **#go-kit** ([invite](https://gophersinvite.herokuapp.com/)) - -## Motivation - -Go has emerged as the language of the server, but it remains underrepresented -in so-called "modern enterprise" companies like Facebook, Twitter, Netflix, and -SoundCloud. Many of these organizations have turned to JVM-based stacks for -their business logic, owing in large part to libraries and ecosystems that -directly support their microservice architectures. - -To reach its next level of success, Go needs more than simple primitives and -idioms. It needs a comprehensive toolkit, for coherent distributed programming -in the large. Go kit is a set of packages and best practices, which provide a -comprehensive, robust, and trustable way of building microservices for -organizations of any size. - -For more details, see - [the website](https://gokit.io), - [the motivating blog post](http://peter.bourgon.org/go-kit/) and - [the video of the talk](https://www.youtube.com/watch?v=iFR_7AKkJFU). -See also the - [Go kit talk at GopherCon 2015](https://www.youtube.com/watch?v=1AjaZi4QuGo). - -## Goals - -- Operate in a heterogeneous SOA — expect to interact with mostly non-Go-kit services -- RPC as the primary messaging pattern -- Pluggable serialization and transport — not just JSON over HTTP -- Operate within existing infrastructures — no mandates for specific tools or technologies - -## Non-goals - -- Supporting messaging patterns other than RPC (for now) — e.g. MPI, pub/sub, CQRS, etc. -- Re-implementing functionality that can be provided by adapting existing software -- Having opinions on operational concerns: deployment, configuration, process supervision, orchestration, etc. - -## Contributing - -Please see [CONTRIBUTING.md](/CONTRIBUTING.md). -Thank you, [contributors](https://github.com/go-kit/kit/graphs/contributors)! - -## Dependency management - -Go kit is a library, designed to be imported into a binary package. Vendoring -is currently the best way for binary package authors to ensure reliable, -reproducible builds. Therefore, we strongly recommend our users use vendoring -for all of their dependencies, including Go kit. To avoid compatibility and -availability issues, Go kit doesn't vendor its own dependencies, and -doesn't recommend use of third-party import proxies. - -There are several tools which make vendoring easier, including - [dep](https://github.com/golang/dep), - [gb](http://getgb.io), - [glide](https://github.com/Masterminds/glide), - [gvt](https://github.com/FiloSottile/gvt), and - [govendor](https://github.com/kardianos/govendor). -In addition, Go kit uses a variety of continuous integration providers - to find and fix compatibility problems as soon as they occur. - -## Related projects - -Projects with a ★ have had particular influence on Go kit's design (or vice-versa). - -### Service frameworks - -- [gizmo](https://github.com/nytimes/gizmo), a microservice toolkit from The New York Times ★ -- [go-micro](https://github.com/myodc/go-micro), a microservices client/server library ★ -- [gotalk](https://github.com/rsms/gotalk), async peer communication protocol & library -- [Kite](https://github.com/koding/kite), a micro-service framework -- [gocircuit](https://github.com/gocircuit/circuit), dynamic cloud orchestration - -### Individual components - -- [afex/hystrix-go](https://github.com/afex/hystrix-go), client-side latency and fault tolerance library -- [armon/go-metrics](https://github.com/armon/go-metrics), library for exporting performance and runtime metrics to external metrics systems -- [codahale/lunk](https://github.com/codahale/lunk), structured logging in the style of Google's Dapper or Twitter's Zipkin -- [eapache/go-resiliency](https://github.com/eapache/go-resiliency), resiliency patterns -- [sasbury/logging](https://github.com/sasbury/logging), a tagged style of logging -- [grpc/grpc-go](https://github.com/grpc/grpc-go), HTTP/2 based RPC -- [inconshreveable/log15](https://github.com/inconshreveable/log15), simple, powerful logging for Go ★ -- [mailgun/vulcand](https://github.com/vulcand/vulcand), programmatic load balancer backed by etcd -- [mattheath/phosphor](https://github.com/mondough/phosphor), distributed system tracing -- [pivotal-golang/lager](https://github.com/pivotal-golang/lager), an opinionated logging library -- [rubyist/circuitbreaker](https://github.com/rubyist/circuitbreaker), circuit breaker library -- [Sirupsen/logrus](https://github.com/Sirupsen/logrus), structured, pluggable logging for Go ★ -- [sourcegraph/appdash](https://github.com/sourcegraph/appdash), application tracing system based on Google's Dapper -- [spacemonkeygo/monitor](https://github.com/spacemonkeygo/monitor), data collection, monitoring, instrumentation, and Zipkin client library -- [streadway/handy](https://github.com/streadway/handy), net/http handler filters -- [vitess/rpcplus](https://godoc.org/github.com/youtube/vitess/go/rpcplus), package rpc + context.Context -- [gdamore/mangos](https://github.com/gdamore/mangos), nanomsg implementation in pure Go - -### Web frameworks - -- [Gorilla](http://www.gorillatoolkit.org) -- [Gin](https://gin-gonic.github.io/gin/) -- [Negroni](https://github.com/codegangsta/negroni) -- [Goji](https://github.com/zenazn/goji) -- [Martini](https://github.com/go-martini/martini) -- [Beego](http://beego.me/) -- [Revel](https://revel.github.io/) (considered [harmful](https://github.com/go-kit/kit/issues/350)) - -## Additional reading - -- [Architecting for the Cloud](http://fr.slideshare.net/stonse/architecting-for-the-cloud-using-netflixoss-codemash-workshop-29852233) — Netflix -- [Dapper, a Large-Scale Distributed Systems Tracing Infrastructure](http://research.google.com/pubs/pub36356.html) — Google -- [Your Server as a Function](http://monkey.org/~marius/funsrv.pdf) (PDF) — Twitter - ---- - -Development supported by [DigitalOcean](https://digitalocean.com). diff --git a/vendor/github.com/go-kit/kit/ROADMAP.md b/vendor/github.com/go-kit/kit/ROADMAP.md deleted file mode 100644 index 5c462aa2..00000000 --- a/vendor/github.com/go-kit/kit/ROADMAP.md +++ /dev/null @@ -1,17 +0,0 @@ -# Roadmap - -This is a coarse-grained roadmap of Go kit development direction in the short -to mid-term future. It will be kept reasonably up-to-date by the project -maintainers. Suggest new ideas, enhancements, and features using the standard -[issues](https://github.com/go-kit/kit/issues) model. - -## Prioritized - -1. kitgen code generation (#308, #70) -1. package pubsub (#298, #295) - -## Unprioritized - -- package log/levels refactor (#250, #269, #252) -- package auth/jwt (#255) - diff --git a/vendor/github.com/go-kit/kit/auth/basic/README.md b/vendor/github.com/go-kit/kit/auth/basic/README.md deleted file mode 100644 index 26d6c4b3..00000000 --- a/vendor/github.com/go-kit/kit/auth/basic/README.md +++ /dev/null @@ -1,20 +0,0 @@ -This package provides a Basic Authentication middleware. - -It'll try to compare credentials from Authentication request header to a username/password pair in middleware constructor. - -More details about this type of authentication can be found in [Mozilla article](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). - -## Usage - -```go -import httptransport "github.com/go-kit/kit/transport/http" - -httptransport.NewServer( - AuthMiddleware(cfg.auth.user, cfg.auth.password, "Example Realm")(makeUppercaseEndpoint()), - decodeMappingsRequest, - httptransport.EncodeJSONResponse, - httptransport.ServerBefore(httptransport.PopulateRequestContext), - ) -``` - -For AuthMiddleware to be able to pick up the Authentication header from an HTTP request we need to pass it through the context with something like ```httptransport.ServerBefore(httptransport.PopulateRequestContext)```. \ No newline at end of file diff --git a/vendor/github.com/go-kit/kit/auth/basic/middleware.go b/vendor/github.com/go-kit/kit/auth/basic/middleware.go deleted file mode 100644 index ad7e4085..00000000 --- a/vendor/github.com/go-kit/kit/auth/basic/middleware.go +++ /dev/null @@ -1,94 +0,0 @@ -package basic - -import ( - "bytes" - "context" - "crypto/sha256" - "crypto/subtle" - "encoding/base64" - "fmt" - "net/http" - "strings" - - "github.com/go-kit/kit/endpoint" - httptransport "github.com/go-kit/kit/transport/http" -) - -// AuthError represents an authorization error. -type AuthError struct { - Realm string -} - -// StatusCode is an implementation of the StatusCoder interface in go-kit/http. -func (AuthError) StatusCode() int { - return http.StatusUnauthorized -} - -// Error is an implementation of the Error interface. -func (AuthError) Error() string { - return http.StatusText(http.StatusUnauthorized) -} - -// Headers is an implementation of the Headerer interface in go-kit/http. -func (e AuthError) Headers() http.Header { - return http.Header{ - "Content-Type": []string{"text/plain; charset=utf-8"}, - "X-Content-Type-Options": []string{"nosniff"}, - "WWW-Authenticate": []string{fmt.Sprintf(`Basic realm=%q`, e.Realm)}, - } -} - -// parseBasicAuth parses an HTTP Basic Authentication string. -// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ([]byte("Aladdin"), []byte("open sesame"), true). -func parseBasicAuth(auth string) (username, password []byte, ok bool) { - const prefix = "Basic " - if !strings.HasPrefix(auth, prefix) { - return - } - c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) - if err != nil { - return - } - - s := bytes.IndexByte(c, ':') - if s < 0 { - return - } - return c[:s], c[s+1:], true -} - -// Returns a hash of a given slice. -func toHashSlice(s []byte) []byte { - hash := sha256.Sum256(s) - return hash[:] -} - -// AuthMiddleware returns a Basic Authentication middleware for a particular user and password. -func AuthMiddleware(requiredUser, requiredPassword, realm string) endpoint.Middleware { - requiredUserBytes := toHashSlice([]byte(requiredUser)) - requiredPasswordBytes := toHashSlice([]byte(requiredPassword)) - - return func(next endpoint.Endpoint) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - auth, ok := ctx.Value(httptransport.ContextKeyRequestAuthorization).(string) - if !ok { - return nil, AuthError{realm} - } - - givenUser, givenPassword, ok := parseBasicAuth(auth) - if !ok { - return nil, AuthError{realm} - } - - givenUserBytes := toHashSlice(givenUser) - givenPasswordBytes := toHashSlice(givenPassword) - - if subtle.ConstantTimeCompare(givenUserBytes, requiredUserBytes) == 0 || - subtle.ConstantTimeCompare(givenPasswordBytes, requiredPasswordBytes) == 0 { - return nil, AuthError{realm} - } - - return next(ctx, request) - } - } -} diff --git a/vendor/github.com/go-kit/kit/auth/basic/middleware_test.go b/vendor/github.com/go-kit/kit/auth/basic/middleware_test.go deleted file mode 100644 index 9ad330eb..00000000 --- a/vendor/github.com/go-kit/kit/auth/basic/middleware_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package basic - -import ( - "context" - "encoding/base64" - "fmt" - "testing" - - httptransport "github.com/go-kit/kit/transport/http" -) - -func TestWithBasicAuth(t *testing.T) { - requiredUser := "test-user" - requiredPassword := "test-pass" - realm := "test realm" - - type want struct { - result interface{} - err error - } - tests := []struct { - name string - authHeader interface{} - want want - }{ - {"Isn't valid with nil header", nil, want{nil, AuthError{realm}}}, - {"Isn't valid with non-string header", 42, want{nil, AuthError{realm}}}, - {"Isn't valid without authHeader", "", want{nil, AuthError{realm}}}, - {"Isn't valid for wrong user", makeAuthString("wrong-user", requiredPassword), want{nil, AuthError{realm}}}, - {"Isn't valid for wrong password", makeAuthString(requiredUser, "wrong-password"), want{nil, AuthError{realm}}}, - {"Is valid for correct creds", makeAuthString(requiredUser, requiredPassword), want{true, nil}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ctx := context.WithValue(context.TODO(), httptransport.ContextKeyRequestAuthorization, tt.authHeader) - - result, err := AuthMiddleware(requiredUser, requiredPassword, realm)(passedValidation)(ctx, nil) - if result != tt.want.result || err != tt.want.err { - t.Errorf("WithBasicAuth() = result: %v, err: %v, want result: %v, want error: %v", result, err, tt.want.result, tt.want.err) - } - }) - } -} - -func makeAuthString(user string, password string) string { - data := []byte(fmt.Sprintf("%s:%s", user, password)) - return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString(data)) -} - -func passedValidation(ctx context.Context, request interface{}) (response interface{}, err error) { - return true, nil -} diff --git a/vendor/github.com/go-kit/kit/auth/jwt/README.md b/vendor/github.com/go-kit/kit/auth/jwt/README.md deleted file mode 100644 index d2430bd2..00000000 --- a/vendor/github.com/go-kit/kit/auth/jwt/README.md +++ /dev/null @@ -1,122 +0,0 @@ -# package auth/jwt - -`package auth/jwt` provides a set of interfaces for service authorization -through [JSON Web Tokens](https://jwt.io/). - -## Usage - -NewParser takes a key function and an expected signing method and returns an -`endpoint.Middleware`. The middleware will parse a token passed into the -context via the `jwt.JWTTokenContextKey`. If the token is valid, any claims -will be added to the context via the `jwt.JWTClaimsContextKey`. - -```go -import ( - stdjwt "github.com/dgrijalva/jwt-go" - - "github.com/go-kit/kit/auth/jwt" - "github.com/go-kit/kit/endpoint" -) - -func main() { - var exampleEndpoint endpoint.Endpoint - { - kf := func(token *stdjwt.Token) (interface{}, error) { return []byte("SigningString"), nil } - exampleEndpoint = MakeExampleEndpoint(service) - exampleEndpoint = jwt.NewParser(kf, stdjwt.SigningMethodHS256, jwt.StandardClaimsFactory)(exampleEndpoint) - } -} -``` - -NewSigner takes a JWT key ID header, the signing key, signing method, and a -claims object. It returns an `endpoint.Middleware`. The middleware will build -the token string and add it to the context via the `jwt.JWTTokenContextKey`. - -```go -import ( - stdjwt "github.com/dgrijalva/jwt-go" - - "github.com/go-kit/kit/auth/jwt" - "github.com/go-kit/kit/endpoint" -) - -func main() { - var exampleEndpoint endpoint.Endpoint - { - exampleEndpoint = grpctransport.NewClient(...).Endpoint() - exampleEndpoint = jwt.NewSigner( - "kid-header", - []byte("SigningString"), - stdjwt.SigningMethodHS256, - jwt.Claims{}, - )(exampleEndpoint) - } -} -``` - -In order for the parser and the signer to work, the authorization headers need -to be passed between the request and the context. `ToHTTPContext()`, -`FromHTTPContext()`, `ToGRPCContext()`, and `FromGRPCContext()` are given as -helpers to do this. These functions implement the correlating transport's -RequestFunc interface and can be passed as ClientBefore or ServerBefore -options. - -Example of use in a client: - -```go -import ( - stdjwt "github.com/dgrijalva/jwt-go" - - grpctransport "github.com/go-kit/kit/transport/grpc" - "github.com/go-kit/kit/auth/jwt" - "github.com/go-kit/kit/endpoint" -) - -func main() { - - options := []httptransport.ClientOption{} - var exampleEndpoint endpoint.Endpoint - { - exampleEndpoint = grpctransport.NewClient(..., grpctransport.ClientBefore(jwt.FromGRPCContext())).Endpoint() - exampleEndpoint = jwt.NewSigner( - "kid-header", - []byte("SigningString"), - stdjwt.SigningMethodHS256, - jwt.Claims{}, - )(exampleEndpoint) - } -} -``` - -Example of use in a server: - -```go -import ( - "context" - - "github.com/go-kit/kit/auth/jwt" - "github.com/go-kit/kit/log" - grpctransport "github.com/go-kit/kit/transport/grpc" -) - -func MakeGRPCServer(ctx context.Context, endpoints Endpoints, logger log.Logger) pb.ExampleServer { - options := []grpctransport.ServerOption{grpctransport.ServerErrorLogger(logger)} - - return &grpcServer{ - createUser: grpctransport.NewServer( - ctx, - endpoints.CreateUserEndpoint, - DecodeGRPCCreateUserRequest, - EncodeGRPCCreateUserResponse, - append(options, grpctransport.ServerBefore(jwt.ToGRPCContext()))..., - ), - getUser: grpctransport.NewServer( - ctx, - endpoints.GetUserEndpoint, - DecodeGRPCGetUserRequest, - EncodeGRPCGetUserResponse, - options..., - ), - } -} -``` diff --git a/vendor/github.com/go-kit/kit/auth/jwt/middleware.go b/vendor/github.com/go-kit/kit/auth/jwt/middleware.go deleted file mode 100644 index 0e29e6d6..00000000 --- a/vendor/github.com/go-kit/kit/auth/jwt/middleware.go +++ /dev/null @@ -1,143 +0,0 @@ -package jwt - -import ( - "context" - "errors" - - jwt "github.com/dgrijalva/jwt-go" - - "github.com/go-kit/kit/endpoint" -) - -type contextKey string - -const ( - // JWTTokenContextKey holds the key used to store a JWT Token in the - // context. - JWTTokenContextKey contextKey = "JWTToken" - - // JWTClaimsContextKey holds the key used to store the JWT Claims in the - // context. - JWTClaimsContextKey contextKey = "JWTClaims" -) - -var ( - // ErrTokenContextMissing denotes a token was not passed into the parsing - // middleware's context. - ErrTokenContextMissing = errors.New("token up for parsing was not passed through the context") - - // ErrTokenInvalid denotes a token was not able to be validated. - ErrTokenInvalid = errors.New("JWT Token was invalid") - - // ErrTokenExpired denotes a token's expire header (exp) has since passed. - ErrTokenExpired = errors.New("JWT Token is expired") - - // ErrTokenMalformed denotes a token was not formatted as a JWT token. - ErrTokenMalformed = errors.New("JWT Token is malformed") - - // ErrTokenNotActive denotes a token's not before header (nbf) is in the - // future. - ErrTokenNotActive = errors.New("token is not valid yet") - - // ErrUnexpectedSigningMethod denotes a token was signed with an unexpected - // signing method. - ErrUnexpectedSigningMethod = errors.New("unexpected signing method") -) - -// NewSigner creates a new JWT token generating middleware, specifying key ID, -// signing string, signing method and the claims you would like it to contain. -// Tokens are signed with a Key ID header (kid) which is useful for determining -// the key to use for parsing. Particularly useful for clients. -func NewSigner(kid string, key []byte, method jwt.SigningMethod, claims jwt.Claims) endpoint.Middleware { - return func(next endpoint.Endpoint) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - token := jwt.NewWithClaims(method, claims) - token.Header["kid"] = kid - - // Sign and get the complete encoded token as a string using the secret - tokenString, err := token.SignedString(key) - if err != nil { - return nil, err - } - ctx = context.WithValue(ctx, JWTTokenContextKey, tokenString) - - return next(ctx, request) - } - } -} - -// ClaimsFactory is a factory for jwt.Claims. -// Useful in NewParser middleware. -type ClaimsFactory func() jwt.Claims - -// MapClaimsFactory is a ClaimsFactory that returns -// an empty jwt.MapClaims. -func MapClaimsFactory() jwt.Claims { - return jwt.MapClaims{} -} - -// StandardClaimsFactory is a ClaimsFactory that returns -// an empty jwt.StandardClaims. -func StandardClaimsFactory() jwt.Claims { - return &jwt.StandardClaims{} -} - -// NewParser creates a new JWT token parsing middleware, specifying a -// jwt.Keyfunc interface, the signing method and the claims type to be used. NewParser -// adds the resulting claims to endpoint context or returns error on invalid token. -// Particularly useful for servers. -func NewParser(keyFunc jwt.Keyfunc, method jwt.SigningMethod, newClaims ClaimsFactory) endpoint.Middleware { - return func(next endpoint.Endpoint) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - // tokenString is stored in the context from the transport handlers. - tokenString, ok := ctx.Value(JWTTokenContextKey).(string) - if !ok { - return nil, ErrTokenContextMissing - } - - // Parse takes the token string and a function for looking up the - // key. The latter is especially useful if you use multiple keys - // for your application. The standard is to use 'kid' in the head - // of the token to identify which key to use, but the parsed token - // (head and claims) is provided to the callback, providing - // flexibility. - token, err := jwt.ParseWithClaims(tokenString, newClaims(), func(token *jwt.Token) (interface{}, error) { - // Don't forget to validate the alg is what you expect: - if token.Method != method { - return nil, ErrUnexpectedSigningMethod - } - - return keyFunc(token) - }) - if err != nil { - if e, ok := err.(*jwt.ValidationError); ok { - switch { - case e.Errors&jwt.ValidationErrorMalformed != 0: - // Token is malformed - return nil, ErrTokenMalformed - case e.Errors&jwt.ValidationErrorExpired != 0: - // Token is expired - return nil, ErrTokenExpired - case e.Errors&jwt.ValidationErrorNotValidYet != 0: - // Token is not active yet - return nil, ErrTokenNotActive - case e.Inner != nil: - // report e.Inner - return nil, e.Inner - } - // We have a ValidationError but have no specific Go kit error for it. - // Fall through to return original error. - } - return nil, err - } - - if !token.Valid { - return nil, ErrTokenInvalid - } - - ctx = context.WithValue(ctx, JWTClaimsContextKey, token.Claims) - - return next(ctx, request) - } - } -} diff --git a/vendor/github.com/go-kit/kit/auth/jwt/middleware_test.go b/vendor/github.com/go-kit/kit/auth/jwt/middleware_test.go deleted file mode 100644 index 3278e13a..00000000 --- a/vendor/github.com/go-kit/kit/auth/jwt/middleware_test.go +++ /dev/null @@ -1,221 +0,0 @@ -package jwt - -import ( - "context" - "sync" - "testing" - "time" - - "crypto/subtle" - - jwt "github.com/dgrijalva/jwt-go" - "github.com/go-kit/kit/endpoint" -) - -type customClaims struct { - MyProperty string `json:"my_property"` - jwt.StandardClaims -} - -func (c customClaims) VerifyMyProperty(p string) bool { - return subtle.ConstantTimeCompare([]byte(c.MyProperty), []byte(p)) != 0 -} - -var ( - kid = "kid" - key = []byte("test_signing_key") - myProperty = "some value" - method = jwt.SigningMethodHS256 - invalidMethod = jwt.SigningMethodRS256 - mapClaims = jwt.MapClaims{"user": "go-kit"} - standardClaims = jwt.StandardClaims{Audience: "go-kit"} - myCustomClaims = customClaims{MyProperty: myProperty, StandardClaims: standardClaims} - // Signed tokens generated at https://jwt.io/ - signedKey = "eyJhbGciOiJIUzI1NiIsImtpZCI6ImtpZCIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiZ28ta2l0In0.14M2VmYyApdSlV_LZ88ajjwuaLeIFplB8JpyNy0A19E" - standardSignedKey = "eyJhbGciOiJIUzI1NiIsImtpZCI6ImtpZCIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJnby1raXQifQ.L5ypIJjCOOv3jJ8G5SelaHvR04UJuxmcBN5QW3m_aoY" - customSignedKey = "eyJhbGciOiJIUzI1NiIsImtpZCI6ImtpZCIsInR5cCI6IkpXVCJ9.eyJteV9wcm9wZXJ0eSI6InNvbWUgdmFsdWUiLCJhdWQiOiJnby1raXQifQ.s8F-IDrV4WPJUsqr7qfDi-3GRlcKR0SRnkTeUT_U-i0" - invalidKey = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.e30.vKVCKto-Wn6rgz3vBdaZaCBGfCBDTXOENSo_X2Gq7qA" - malformedKey = "malformed.jwt.token" -) - -func signingValidator(t *testing.T, signer endpoint.Endpoint, expectedKey string) { - ctx, err := signer(context.Background(), struct{}{}) - if err != nil { - t.Fatalf("Signer returned error: %s", err) - } - - token, ok := ctx.(context.Context).Value(JWTTokenContextKey).(string) - if !ok { - t.Fatal("Token did not exist in context") - } - - if token != expectedKey { - t.Fatalf("JWT tokens did not match: expecting %s got %s", expectedKey, token) - } -} - -func TestNewSigner(t *testing.T) { - e := func(ctx context.Context, i interface{}) (interface{}, error) { return ctx, nil } - - signer := NewSigner(kid, key, method, mapClaims)(e) - signingValidator(t, signer, signedKey) - - signer = NewSigner(kid, key, method, standardClaims)(e) - signingValidator(t, signer, standardSignedKey) - - signer = NewSigner(kid, key, method, myCustomClaims)(e) - signingValidator(t, signer, customSignedKey) -} - -func TestJWTParser(t *testing.T) { - e := func(ctx context.Context, i interface{}) (interface{}, error) { return ctx, nil } - - keys := func(token *jwt.Token) (interface{}, error) { - return key, nil - } - - parser := NewParser(keys, method, MapClaimsFactory)(e) - - // No Token is passed into the parser - _, err := parser(context.Background(), struct{}{}) - if err == nil { - t.Error("Parser should have returned an error") - } - - if err != ErrTokenContextMissing { - t.Errorf("unexpected error returned, expected: %s got: %s", ErrTokenContextMissing, err) - } - - // Invalid Token is passed into the parser - ctx := context.WithValue(context.Background(), JWTTokenContextKey, invalidKey) - _, err = parser(ctx, struct{}{}) - if err == nil { - t.Error("Parser should have returned an error") - } - - // Invalid Method is used in the parser - badParser := NewParser(keys, invalidMethod, MapClaimsFactory)(e) - ctx = context.WithValue(context.Background(), JWTTokenContextKey, signedKey) - _, err = badParser(ctx, struct{}{}) - if err == nil { - t.Error("Parser should have returned an error") - } - - if err != ErrUnexpectedSigningMethod { - t.Errorf("unexpected error returned, expected: %s got: %s", ErrUnexpectedSigningMethod, err) - } - - // Invalid key is used in the parser - invalidKeys := func(token *jwt.Token) (interface{}, error) { - return []byte("bad"), nil - } - - badParser = NewParser(invalidKeys, method, MapClaimsFactory)(e) - ctx = context.WithValue(context.Background(), JWTTokenContextKey, signedKey) - _, err = badParser(ctx, struct{}{}) - if err == nil { - t.Error("Parser should have returned an error") - } - - // Correct token is passed into the parser - ctx = context.WithValue(context.Background(), JWTTokenContextKey, signedKey) - ctx1, err := parser(ctx, struct{}{}) - if err != nil { - t.Fatalf("Parser returned error: %s", err) - } - - cl, ok := ctx1.(context.Context).Value(JWTClaimsContextKey).(jwt.MapClaims) - if !ok { - t.Fatal("Claims were not passed into context correctly") - } - - if cl["user"] != mapClaims["user"] { - t.Fatalf("JWT Claims.user did not match: expecting %s got %s", mapClaims["user"], cl["user"]) - } - - // Test for malformed token error response - parser = NewParser(keys, method, StandardClaimsFactory)(e) - ctx = context.WithValue(context.Background(), JWTTokenContextKey, malformedKey) - ctx1, err = parser(ctx, struct{}{}) - if want, have := ErrTokenMalformed, err; want != have { - t.Fatalf("Expected %+v, got %+v", want, have) - } - - // Test for expired token error response - parser = NewParser(keys, method, StandardClaimsFactory)(e) - expired := jwt.NewWithClaims(method, jwt.StandardClaims{ExpiresAt: time.Now().Unix() - 100}) - token, err := expired.SignedString(key) - if err != nil { - t.Fatalf("Unable to Sign Token: %+v", err) - } - ctx = context.WithValue(context.Background(), JWTTokenContextKey, token) - ctx1, err = parser(ctx, struct{}{}) - if want, have := ErrTokenExpired, err; want != have { - t.Fatalf("Expected %+v, got %+v", want, have) - } - - // Test for not activated token error response - parser = NewParser(keys, method, StandardClaimsFactory)(e) - notactive := jwt.NewWithClaims(method, jwt.StandardClaims{NotBefore: time.Now().Unix() + 100}) - token, err = notactive.SignedString(key) - if err != nil { - t.Fatalf("Unable to Sign Token: %+v", err) - } - ctx = context.WithValue(context.Background(), JWTTokenContextKey, token) - ctx1, err = parser(ctx, struct{}{}) - if want, have := ErrTokenNotActive, err; want != have { - t.Fatalf("Expected %+v, got %+v", want, have) - } - - // test valid standard claims token - parser = NewParser(keys, method, StandardClaimsFactory)(e) - ctx = context.WithValue(context.Background(), JWTTokenContextKey, standardSignedKey) - ctx1, err = parser(ctx, struct{}{}) - if err != nil { - t.Fatalf("Parser returned error: %s", err) - } - stdCl, ok := ctx1.(context.Context).Value(JWTClaimsContextKey).(*jwt.StandardClaims) - if !ok { - t.Fatal("Claims were not passed into context correctly") - } - if !stdCl.VerifyAudience("go-kit", true) { - t.Fatalf("JWT jwt.StandardClaims.Audience did not match: expecting %s got %s", standardClaims.Audience, stdCl.Audience) - } - - // test valid customized claims token - parser = NewParser(keys, method, func() jwt.Claims { return &customClaims{} })(e) - ctx = context.WithValue(context.Background(), JWTTokenContextKey, customSignedKey) - ctx1, err = parser(ctx, struct{}{}) - if err != nil { - t.Fatalf("Parser returned error: %s", err) - } - custCl, ok := ctx1.(context.Context).Value(JWTClaimsContextKey).(*customClaims) - if !ok { - t.Fatal("Claims were not passed into context correctly") - } - if !custCl.VerifyAudience("go-kit", true) { - t.Fatalf("JWT customClaims.Audience did not match: expecting %s got %s", standardClaims.Audience, custCl.Audience) - } - if !custCl.VerifyMyProperty(myProperty) { - t.Fatalf("JWT customClaims.MyProperty did not match: expecting %s got %s", myProperty, custCl.MyProperty) - } -} - -func TestIssue562(t *testing.T) { - var ( - kf = func(token *jwt.Token) (interface{}, error) { return []byte("secret"), nil } - e = NewParser(kf, jwt.SigningMethodHS256, MapClaimsFactory)(endpoint.Nop) - key = JWTTokenContextKey - val = "eyJhbGciOiJIUzI1NiIsImtpZCI6ImtpZCIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiZ28ta2l0In0.14M2VmYyApdSlV_LZ88ajjwuaLeIFplB8JpyNy0A19E" - ctx = context.WithValue(context.Background(), key, val) - ) - wg := sync.WaitGroup{} - for i := 0; i < 100; i++ { - wg.Add(1) - go func() { - defer wg.Done() - e(ctx, struct{}{}) // fatal error: concurrent map read and map write - }() - } - wg.Wait() -} diff --git a/vendor/github.com/go-kit/kit/auth/jwt/transport.go b/vendor/github.com/go-kit/kit/auth/jwt/transport.go deleted file mode 100644 index 57b3aaee..00000000 --- a/vendor/github.com/go-kit/kit/auth/jwt/transport.go +++ /dev/null @@ -1,89 +0,0 @@ -package jwt - -import ( - "context" - "fmt" - stdhttp "net/http" - "strings" - - "google.golang.org/grpc/metadata" - - "github.com/go-kit/kit/transport/grpc" - "github.com/go-kit/kit/transport/http" -) - -const ( - bearer string = "bearer" - bearerFormat string = "Bearer %s" -) - -// HTTPToContext moves a JWT from request header to context. Particularly -// useful for servers. -func HTTPToContext() http.RequestFunc { - return func(ctx context.Context, r *stdhttp.Request) context.Context { - token, ok := extractTokenFromAuthHeader(r.Header.Get("Authorization")) - if !ok { - return ctx - } - - return context.WithValue(ctx, JWTTokenContextKey, token) - } -} - -// ContextToHTTP moves a JWT from context to request header. Particularly -// useful for clients. -func ContextToHTTP() http.RequestFunc { - return func(ctx context.Context, r *stdhttp.Request) context.Context { - token, ok := ctx.Value(JWTTokenContextKey).(string) - if ok { - r.Header.Add("Authorization", generateAuthHeaderFromToken(token)) - } - return ctx - } -} - -// GRPCToContext moves a JWT from grpc metadata to context. Particularly -// userful for servers. -func GRPCToContext() grpc.ServerRequestFunc { - return func(ctx context.Context, md metadata.MD) context.Context { - // capital "Key" is illegal in HTTP/2. - authHeader, ok := md["authorization"] - if !ok { - return ctx - } - - token, ok := extractTokenFromAuthHeader(authHeader[0]) - if ok { - ctx = context.WithValue(ctx, JWTTokenContextKey, token) - } - - return ctx - } -} - -// ContextToGRPC moves a JWT from context to grpc metadata. Particularly -// useful for clients. -func ContextToGRPC() grpc.ClientRequestFunc { - return func(ctx context.Context, md *metadata.MD) context.Context { - token, ok := ctx.Value(JWTTokenContextKey).(string) - if ok { - // capital "Key" is illegal in HTTP/2. - (*md)["authorization"] = []string{generateAuthHeaderFromToken(token)} - } - - return ctx - } -} - -func extractTokenFromAuthHeader(val string) (token string, ok bool) { - authHeaderParts := strings.Split(val, " ") - if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != bearer { - return "", false - } - - return authHeaderParts[1], true -} - -func generateAuthHeaderFromToken(token string) string { - return fmt.Sprintf(bearerFormat, token) -} diff --git a/vendor/github.com/go-kit/kit/auth/jwt/transport_test.go b/vendor/github.com/go-kit/kit/auth/jwt/transport_test.go deleted file mode 100644 index 83d0f17f..00000000 --- a/vendor/github.com/go-kit/kit/auth/jwt/transport_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package jwt - -import ( - "context" - "fmt" - "net/http" - "testing" - - "google.golang.org/grpc/metadata" -) - -func TestHTTPToContext(t *testing.T) { - reqFunc := HTTPToContext() - - // When the header doesn't exist - ctx := reqFunc(context.Background(), &http.Request{}) - - if ctx.Value(JWTTokenContextKey) != nil { - t.Error("Context shouldn't contain the encoded JWT") - } - - // Authorization header value has invalid format - header := http.Header{} - header.Set("Authorization", "no expected auth header format value") - ctx = reqFunc(context.Background(), &http.Request{Header: header}) - - if ctx.Value(JWTTokenContextKey) != nil { - t.Error("Context shouldn't contain the encoded JWT") - } - - // Authorization header is correct - header.Set("Authorization", generateAuthHeaderFromToken(signedKey)) - ctx = reqFunc(context.Background(), &http.Request{Header: header}) - - token := ctx.Value(JWTTokenContextKey).(string) - if token != signedKey { - t.Errorf("Context doesn't contain the expected encoded token value; expected: %s, got: %s", signedKey, token) - } -} - -func TestContextToHTTP(t *testing.T) { - reqFunc := ContextToHTTP() - - // No JWT Token is passed in the context - ctx := context.Background() - r := http.Request{} - reqFunc(ctx, &r) - - token := r.Header.Get("Authorization") - if token != "" { - t.Error("authorization key should not exist in metadata") - } - - // Correct JWT Token is passed in the context - ctx = context.WithValue(context.Background(), JWTTokenContextKey, signedKey) - r = http.Request{Header: http.Header{}} - reqFunc(ctx, &r) - - token = r.Header.Get("Authorization") - expected := generateAuthHeaderFromToken(signedKey) - - if token != expected { - t.Errorf("Authorization header does not contain the expected JWT token; expected %s, got %s", expected, token) - } -} - -func TestGRPCToContext(t *testing.T) { - md := metadata.MD{} - reqFunc := GRPCToContext() - - // No Authorization header is passed - ctx := reqFunc(context.Background(), md) - token := ctx.Value(JWTTokenContextKey) - if token != nil { - t.Error("Context should not contain a JWT Token") - } - - // Invalid Authorization header is passed - md["authorization"] = []string{fmt.Sprintf("%s", signedKey)} - ctx = reqFunc(context.Background(), md) - token = ctx.Value(JWTTokenContextKey) - if token != nil { - t.Error("Context should not contain a JWT Token") - } - - // Authorization header is correct - md["authorization"] = []string{fmt.Sprintf("Bearer %s", signedKey)} - ctx = reqFunc(context.Background(), md) - token, ok := ctx.Value(JWTTokenContextKey).(string) - if !ok { - t.Fatal("JWT Token not passed to context correctly") - } - - if token != signedKey { - t.Errorf("JWT tokens did not match: expecting %s got %s", signedKey, token) - } -} - -func TestContextToGRPC(t *testing.T) { - reqFunc := ContextToGRPC() - - // No JWT Token is passed in the context - ctx := context.Background() - md := metadata.MD{} - reqFunc(ctx, &md) - - _, ok := md["authorization"] - if ok { - t.Error("authorization key should not exist in metadata") - } - - // Correct JWT Token is passed in the context - ctx = context.WithValue(context.Background(), JWTTokenContextKey, signedKey) - md = metadata.MD{} - reqFunc(ctx, &md) - - token, ok := md["authorization"] - if !ok { - t.Fatal("JWT Token not passed to metadata correctly") - } - - if token[0] != generateAuthHeaderFromToken(signedKey) { - t.Errorf("JWT tokens did not match: expecting %s got %s", signedKey, token[0]) - } -} diff --git a/vendor/github.com/go-kit/kit/circle.yml b/vendor/github.com/go-kit/kit/circle.yml deleted file mode 100644 index 35ace2ce..00000000 --- a/vendor/github.com/go-kit/kit/circle.yml +++ /dev/null @@ -1,27 +0,0 @@ -machine: - pre: - - curl -sSL https://s3.amazonaws.com/circle-downloads/install-circleci-docker.sh | bash -s -- 1.10.0 - - sudo rm -rf /usr/local/go - - curl -sSL https://storage.googleapis.com/golang/go1.9.linux-amd64.tar.gz | sudo tar xz -C /usr/local - services: - - docker - -dependencies: - pre: - - sudo curl -L "https://github.com/docker/compose/releases/download/1.10.0/docker-compose-linux-x86_64" -o /usr/local/bin/docker-compose - - sudo chmod +x /usr/local/bin/docker-compose - - docker-compose -f docker-compose-integration.yml up -d --force-recreate - -test: - pre: - - mkdir -p /home/ubuntu/.go_workspace/src/github.com/go-kit - - mv /home/ubuntu/kit /home/ubuntu/.go_workspace/src/github.com/go-kit - - ln -s /home/ubuntu/.go_workspace/src/github.com/go-kit/kit /home/ubuntu/kit - - go get -t github.com/go-kit/kit/... - override: - - go test -v -race -tags integration github.com/go-kit/kit/...: - environment: - ETCD_ADDR: http://localhost:2379 - CONSUL_ADDR: localhost:8500 - ZK_ADDR: localhost:2181 - EUREKA_ADDR: http://localhost:8761/eureka diff --git a/vendor/github.com/go-kit/kit/circuitbreaker/doc.go b/vendor/github.com/go-kit/kit/circuitbreaker/doc.go deleted file mode 100644 index fe749575..00000000 --- a/vendor/github.com/go-kit/kit/circuitbreaker/doc.go +++ /dev/null @@ -1,10 +0,0 @@ -// Package circuitbreaker implements the circuit breaker pattern. -// -// Circuit breakers prevent thundering herds, and improve resiliency against -// intermittent errors. Every client-side endpoint should be wrapped in a -// circuit breaker. -// -// We provide several implementations in this package, but if you're looking -// for guidance, Gobreaker is probably the best place to start. It has a -// simple and intuitive API, and is well-tested. -package circuitbreaker diff --git a/vendor/github.com/go-kit/kit/circuitbreaker/gobreaker.go b/vendor/github.com/go-kit/kit/circuitbreaker/gobreaker.go deleted file mode 100644 index cf06304f..00000000 --- a/vendor/github.com/go-kit/kit/circuitbreaker/gobreaker.go +++ /dev/null @@ -1,22 +0,0 @@ -package circuitbreaker - -import ( - "context" - - "github.com/sony/gobreaker" - - "github.com/go-kit/kit/endpoint" -) - -// Gobreaker returns an endpoint.Middleware that implements the circuit -// breaker pattern using the sony/gobreaker package. Only errors returned by -// the wrapped endpoint count against the circuit breaker's error count. -// -// See http://godoc.org/github.com/sony/gobreaker for more information. -func Gobreaker(cb *gobreaker.CircuitBreaker) endpoint.Middleware { - return func(next endpoint.Endpoint) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - return cb.Execute(func() (interface{}, error) { return next(ctx, request) }) - } - } -} diff --git a/vendor/github.com/go-kit/kit/circuitbreaker/gobreaker_test.go b/vendor/github.com/go-kit/kit/circuitbreaker/gobreaker_test.go deleted file mode 100644 index b581cfe5..00000000 --- a/vendor/github.com/go-kit/kit/circuitbreaker/gobreaker_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package circuitbreaker_test - -import ( - "testing" - - "github.com/sony/gobreaker" - - "github.com/go-kit/kit/circuitbreaker" -) - -func TestGobreaker(t *testing.T) { - var ( - breaker = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{})) - primeWith = 100 - shouldPass = func(n int) bool { return n <= 5 } // https://github.com/sony/gobreaker/blob/bfa846d/gobreaker.go#L76 - circuitOpenError = "circuit breaker is open" - ) - testFailingEndpoint(t, breaker, primeWith, shouldPass, 0, circuitOpenError) -} diff --git a/vendor/github.com/go-kit/kit/circuitbreaker/handy_breaker.go b/vendor/github.com/go-kit/kit/circuitbreaker/handy_breaker.go deleted file mode 100644 index a5b60be2..00000000 --- a/vendor/github.com/go-kit/kit/circuitbreaker/handy_breaker.go +++ /dev/null @@ -1,38 +0,0 @@ -package circuitbreaker - -import ( - "context" - "time" - - "github.com/streadway/handy/breaker" - - "github.com/go-kit/kit/endpoint" -) - -// HandyBreaker returns an endpoint.Middleware that implements the circuit -// breaker pattern using the streadway/handy/breaker package. Only errors -// returned by the wrapped endpoint count against the circuit breaker's error -// count. -// -// See http://godoc.org/github.com/streadway/handy/breaker for more -// information. -func HandyBreaker(cb breaker.Breaker) endpoint.Middleware { - return func(next endpoint.Endpoint) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - if !cb.Allow() { - return nil, breaker.ErrCircuitOpen - } - - defer func(begin time.Time) { - if err == nil { - cb.Success(time.Since(begin)) - } else { - cb.Failure(time.Since(begin)) - } - }(time.Now()) - - response, err = next(ctx, request) - return - } - } -} diff --git a/vendor/github.com/go-kit/kit/circuitbreaker/handy_breaker_test.go b/vendor/github.com/go-kit/kit/circuitbreaker/handy_breaker_test.go deleted file mode 100644 index f3642a10..00000000 --- a/vendor/github.com/go-kit/kit/circuitbreaker/handy_breaker_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package circuitbreaker_test - -import ( - "testing" - - handybreaker "github.com/streadway/handy/breaker" - - "github.com/go-kit/kit/circuitbreaker" -) - -func TestHandyBreaker(t *testing.T) { - var ( - failureRatio = 0.05 - breaker = circuitbreaker.HandyBreaker(handybreaker.NewBreaker(failureRatio)) - primeWith = handybreaker.DefaultMinObservations * 10 - shouldPass = func(n int) bool { return (float64(n) / float64(primeWith+n)) <= failureRatio } - openCircuitError = handybreaker.ErrCircuitOpen.Error() - ) - testFailingEndpoint(t, breaker, primeWith, shouldPass, 0, openCircuitError) -} diff --git a/vendor/github.com/go-kit/kit/circuitbreaker/hystrix.go b/vendor/github.com/go-kit/kit/circuitbreaker/hystrix.go deleted file mode 100644 index 3c59ec41..00000000 --- a/vendor/github.com/go-kit/kit/circuitbreaker/hystrix.go +++ /dev/null @@ -1,31 +0,0 @@ -package circuitbreaker - -import ( - "context" - - "github.com/afex/hystrix-go/hystrix" - - "github.com/go-kit/kit/endpoint" -) - -// Hystrix returns an endpoint.Middleware that implements the circuit -// breaker pattern using the afex/hystrix-go package. -// -// When using this circuit breaker, please configure your commands separately. -// -// See https://godoc.org/github.com/afex/hystrix-go/hystrix for more -// information. -func Hystrix(commandName string) endpoint.Middleware { - return func(next endpoint.Endpoint) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - var resp interface{} - if err := hystrix.Do(commandName, func() (err error) { - resp, err = next(ctx, request) - return err - }, nil); err != nil { - return nil, err - } - return resp, nil - } - } -} diff --git a/vendor/github.com/go-kit/kit/circuitbreaker/hystrix_test.go b/vendor/github.com/go-kit/kit/circuitbreaker/hystrix_test.go deleted file mode 100644 index da527576..00000000 --- a/vendor/github.com/go-kit/kit/circuitbreaker/hystrix_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package circuitbreaker_test - -import ( - "io/ioutil" - stdlog "log" - "testing" - "time" - - "github.com/afex/hystrix-go/hystrix" - - "github.com/go-kit/kit/circuitbreaker" -) - -func TestHystrix(t *testing.T) { - stdlog.SetOutput(ioutil.Discard) - - const ( - commandName = "my-endpoint" - errorPercent = 5 - maxConcurrent = 1000 - ) - hystrix.ConfigureCommand(commandName, hystrix.CommandConfig{ - ErrorPercentThreshold: errorPercent, - MaxConcurrentRequests: maxConcurrent, - }) - - var ( - breaker = circuitbreaker.Hystrix(commandName) - primeWith = hystrix.DefaultVolumeThreshold * 2 - shouldPass = func(n int) bool { return (float64(n) / float64(primeWith+n)) <= (float64(errorPercent-1) / 100.0) } - openCircuitError = hystrix.ErrCircuitOpen.Error() - ) - - // hystrix-go uses buffered channels to receive reports on request success/failure, - // and so is basically impossible to test deterministically. We have to make sure - // the report buffer is emptied, by injecting a sleep between each invocation. - requestDelay := 5 * time.Millisecond - - testFailingEndpoint(t, breaker, primeWith, shouldPass, requestDelay, openCircuitError) -} diff --git a/vendor/github.com/go-kit/kit/circuitbreaker/util_test.go b/vendor/github.com/go-kit/kit/circuitbreaker/util_test.go deleted file mode 100644 index 25123805..00000000 --- a/vendor/github.com/go-kit/kit/circuitbreaker/util_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package circuitbreaker_test - -import ( - "context" - "errors" - "fmt" - "path/filepath" - "runtime" - "testing" - "time" - - "github.com/go-kit/kit/endpoint" -) - -func testFailingEndpoint( - t *testing.T, - breaker endpoint.Middleware, - primeWith int, - shouldPass func(int) bool, - requestDelay time.Duration, - openCircuitError string, -) { - _, file, line, _ := runtime.Caller(1) - caller := fmt.Sprintf("%s:%d", filepath.Base(file), line) - - // Create a mock endpoint and wrap it with the breaker. - m := mock{} - var e endpoint.Endpoint - e = m.endpoint - e = breaker(e) - - // Prime the endpoint with successful requests. - for i := 0; i < primeWith; i++ { - if _, err := e(context.Background(), struct{}{}); err != nil { - t.Fatalf("%s: during priming, got error: %v", caller, err) - } - time.Sleep(requestDelay) - } - - // Switch the endpoint to start throwing errors. - m.err = errors.New("tragedy+disaster") - m.through = 0 - - // The first several should be allowed through and yield our error. - for i := 0; shouldPass(i); i++ { - if _, err := e(context.Background(), struct{}{}); err != m.err { - t.Fatalf("%s: want %v, have %v", caller, m.err, err) - } - time.Sleep(requestDelay) - } - through := m.through - - // But the rest should be blocked by an open circuit. - for i := 0; i < 10; i++ { - if _, err := e(context.Background(), struct{}{}); err.Error() != openCircuitError { - t.Fatalf("%s: want %q, have %q", caller, openCircuitError, err.Error()) - } - time.Sleep(requestDelay) - } - - // Make sure none of those got through. - if want, have := through, m.through; want != have { - t.Errorf("%s: want %d, have %d", caller, want, have) - } -} - -type mock struct { - through int - err error -} - -func (m *mock) endpoint(context.Context, interface{}) (interface{}, error) { - m.through++ - return struct{}{}, m.err -} diff --git a/vendor/github.com/go-kit/kit/coveralls.bash b/vendor/github.com/go-kit/kit/coveralls.bash deleted file mode 100755 index cf8fee93..00000000 --- a/vendor/github.com/go-kit/kit/coveralls.bash +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash - -if ! type -P gover -then - echo gover missing: go get github.com/modocache/gover - exit 1 -fi - -if ! type -P goveralls -then - echo goveralls missing: go get github.com/mattn/goveralls - exit 1 -fi - -if [[ "$COVERALLS_TOKEN" == "" ]] -then - echo COVERALLS_TOKEN not set - exit 1 -fi - -go list ./... | grep -v '/examples/' | cut -d'/' -f 4- | while read d -do - cd $d - go test -covermode count -coverprofile coverage.coverprofile - cd - -done - -gover -goveralls -coverprofile gover.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN -find . -name '*.coverprofile' -delete - diff --git a/vendor/github.com/go-kit/kit/docker-compose-integration.yml b/vendor/github.com/go-kit/kit/docker-compose-integration.yml deleted file mode 100644 index 287d97db..00000000 --- a/vendor/github.com/go-kit/kit/docker-compose-integration.yml +++ /dev/null @@ -1,22 +0,0 @@ -version: '2' -services: - etcd: - image: quay.io/coreos/etcd - ports: - - "2379:2379" - command: /usr/local/bin/etcd -advertise-client-urls http://0.0.0.0:2379,http://0.0.0.0:4001 -listen-client-urls "http://0.0.0.0:2379,http://0.0.0.0:4001" - consul: - image: progrium/consul - ports: - - "8500:8500" - command: -server -bootstrap - zk: - image: zookeeper - ports: - - "2181:2181" - eureka: - image: springcloud/eureka - environment: - eureka.server.responseCacheUpdateIntervalMs: 1000 - ports: - - "8761:8761" diff --git a/vendor/github.com/go-kit/kit/endpoint/doc.go b/vendor/github.com/go-kit/kit/endpoint/doc.go deleted file mode 100644 index 84e27b95..00000000 --- a/vendor/github.com/go-kit/kit/endpoint/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package endpoint defines an abstraction for RPCs. -// -// Endpoints are a fundamental building block for many Go kit components. -// Endpoints are implemented by servers, and called by clients. -package endpoint diff --git a/vendor/github.com/go-kit/kit/endpoint/endpoint.go b/vendor/github.com/go-kit/kit/endpoint/endpoint.go deleted file mode 100644 index 1b64f50e..00000000 --- a/vendor/github.com/go-kit/kit/endpoint/endpoint.go +++ /dev/null @@ -1,28 +0,0 @@ -package endpoint - -import ( - "context" -) - -// Endpoint is the fundamental building block of servers and clients. -// It represents a single RPC method. -type Endpoint func(ctx context.Context, request interface{}) (response interface{}, err error) - -// Nop is an endpoint that does nothing and returns a nil error. -// Useful for tests. -func Nop(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil } - -// Middleware is a chainable behavior modifier for endpoints. -type Middleware func(Endpoint) Endpoint - -// Chain is a helper function for composing middlewares. Requests will -// traverse them in the order they're declared. That is, the first middleware -// is treated as the outermost middleware. -func Chain(outer Middleware, others ...Middleware) Middleware { - return func(next Endpoint) Endpoint { - for i := len(others) - 1; i >= 0; i-- { // reverse - next = others[i](next) - } - return outer(next) - } -} diff --git a/vendor/github.com/go-kit/kit/endpoint/endpoint_example_test.go b/vendor/github.com/go-kit/kit/endpoint/endpoint_example_test.go deleted file mode 100644 index e9506230..00000000 --- a/vendor/github.com/go-kit/kit/endpoint/endpoint_example_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package endpoint_test - -import ( - "context" - "fmt" - - "github.com/go-kit/kit/endpoint" -) - -func ExampleChain() { - e := endpoint.Chain( - annotate("first"), - annotate("second"), - annotate("third"), - )(myEndpoint) - - if _, err := e(ctx, req); err != nil { - panic(err) - } - - // Output: - // first pre - // second pre - // third pre - // my endpoint! - // third post - // second post - // first post -} - -var ( - ctx = context.Background() - req = struct{}{} -) - -func annotate(s string) endpoint.Middleware { - return func(next endpoint.Endpoint) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - fmt.Println(s, "pre") - defer fmt.Println(s, "post") - return next(ctx, request) - } - } -} - -func myEndpoint(context.Context, interface{}) (interface{}, error) { - fmt.Println("my endpoint!") - return struct{}{}, nil -} diff --git a/vendor/github.com/go-kit/kit/examples/README.md b/vendor/github.com/go-kit/kit/examples/README.md deleted file mode 100644 index 2891d788..00000000 --- a/vendor/github.com/go-kit/kit/examples/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Examples - -For more information about these examples, - including a walkthrough of the stringsvc example, - see [gokit.io/examples](https://gokit.io/examples). diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/README.md b/vendor/github.com/go-kit/kit/examples/addsvc/README.md deleted file mode 100644 index 08080060..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# addsvc - -addsvc is an example microservice which takes full advantage of most of Go -kit's features, including both service- and transport-level middlewares, -speaking multiple transports simultaneously, distributed tracing, and rich -error definitions. The server binary is available in cmd/addsvc. The client -binary is available in cmd/addcli. - -Finally, the addtransport package provides both server and clients for each -supported transport. The client structs bake-in certain middlewares, in order to -demonstrate the _client library pattern_. But beware: client libraries are -generally a bad idea, because they easily lead to the - [distributed monolith antipattern](https://www.microservices.com/talks/dont-build-a-distributed-monolith/). -If you don't _know_ you need to use one in your organization, it's probably best -avoided: prefer moving that logic to consumers, and relying on - [contract testing](https://docs.pact.io/best_practices/contract_tests_not_functional_tests.html) -to detect incompatibilities. diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addcli/addcli.go b/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addcli/addcli.go deleted file mode 100644 index fe24fc27..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addcli/addcli.go +++ /dev/null @@ -1,198 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "os" - "strconv" - "text/tabwriter" - "time" - - "google.golang.org/grpc" - - "github.com/apache/thrift/lib/go/thrift" - lightstep "github.com/lightstep/lightstep-tracer-go" - stdopentracing "github.com/opentracing/opentracing-go" - zipkin "github.com/openzipkin/zipkin-go-opentracing" - "sourcegraph.com/sourcegraph/appdash" - appdashot "sourcegraph.com/sourcegraph/appdash/opentracing" - - "github.com/go-kit/kit/log" - - "github.com/go-kit/kit/examples/addsvc/pkg/addservice" - "github.com/go-kit/kit/examples/addsvc/pkg/addtransport" - addthrift "github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc" -) - -func main() { - // The addcli presumes no service discovery system, and expects users to - // provide the direct address of an addsvc. This presumption is reflected in - // the addcli binary and the client packages: the -transport.addr flags - // and various client constructors both expect host:port strings. For an - // example service with a client built on top of a service discovery system, - // see profilesvc. - fs := flag.NewFlagSet("addcli", flag.ExitOnError) - var ( - httpAddr = fs.String("http-addr", "", "HTTP address of addsvc") - grpcAddr = fs.String("grpc-addr", "", "gRPC address of addsvc") - thriftAddr = fs.String("thrift-addr", "", "Thrift address of addsvc") - thriftProtocol = fs.String("thrift-protocol", "binary", "binary, compact, json, simplejson") - thriftBuffer = fs.Int("thrift-buffer", 0, "0 for unbuffered") - thriftFramed = fs.Bool("thrift-framed", false, "true to enable framing") - zipkinURL = fs.String("zipkin-url", "", "Enable Zipkin tracing via a collector URL e.g. http://localhost:9411/api/v1/spans") - lightstepToken = flag.String("lightstep-token", "", "Enable LightStep tracing via a LightStep access token") - appdashAddr = flag.String("appdash-addr", "", "Enable Appdash tracing via an Appdash server host:port") - method = fs.String("method", "sum", "sum, concat") - ) - fs.Usage = usageFor(fs, os.Args[0]+" [flags] ") - fs.Parse(os.Args[1:]) - if len(fs.Args()) != 2 { - fs.Usage() - os.Exit(1) - } - - // This is a demonstration client, which supports multiple tracers. - // Your clients will probably just use one tracer. - var tracer stdopentracing.Tracer - { - if *zipkinURL != "" { - collector, err := zipkin.NewHTTPCollector(*zipkinURL) - if err != nil { - fmt.Fprintln(os.Stderr, err.Error()) - os.Exit(1) - } - defer collector.Close() - var ( - debug = false - hostPort = "localhost:80" - serviceName = "addsvc" - ) - recorder := zipkin.NewRecorder(collector, debug, hostPort, serviceName) - tracer, err = zipkin.NewTracer(recorder) - if err != nil { - fmt.Fprintln(os.Stderr, err.Error()) - os.Exit(1) - } - } else if *lightstepToken != "" { - tracer = lightstep.NewTracer(lightstep.Options{ - AccessToken: *lightstepToken, - }) - defer lightstep.FlushLightStepTracer(tracer) - } else if *appdashAddr != "" { - tracer = appdashot.NewTracer(appdash.NewRemoteCollector(*appdashAddr)) - } else { - tracer = stdopentracing.GlobalTracer() // no-op - } - } - - // This is a demonstration client, which supports multiple transports. - // Your clients will probably just define and stick with 1 transport. - var ( - svc addservice.Service - err error - ) - if *httpAddr != "" { - svc, err = addtransport.NewHTTPClient(*httpAddr, tracer, log.NewNopLogger()) - } else if *grpcAddr != "" { - conn, err := grpc.Dial(*grpcAddr, grpc.WithInsecure(), grpc.WithTimeout(time.Second)) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v", err) - os.Exit(1) - } - defer conn.Close() - svc = addtransport.NewGRPCClient(conn, tracer, log.NewNopLogger()) - } else if *thriftAddr != "" { - // It's necessary to do all of this construction in the func main, - // because (among other reasons) we need to control the lifecycle of the - // Thrift transport, i.e. close it eventually. - var protocolFactory thrift.TProtocolFactory - switch *thriftProtocol { - case "compact": - protocolFactory = thrift.NewTCompactProtocolFactory() - case "simplejson": - protocolFactory = thrift.NewTSimpleJSONProtocolFactory() - case "json": - protocolFactory = thrift.NewTJSONProtocolFactory() - case "binary", "": - protocolFactory = thrift.NewTBinaryProtocolFactoryDefault() - default: - fmt.Fprintf(os.Stderr, "error: invalid protocol %q\n", *thriftProtocol) - os.Exit(1) - } - var transportFactory thrift.TTransportFactory - if *thriftBuffer > 0 { - transportFactory = thrift.NewTBufferedTransportFactory(*thriftBuffer) - } else { - transportFactory = thrift.NewTTransportFactory() - } - if *thriftFramed { - transportFactory = thrift.NewTFramedTransportFactory(transportFactory) - } - transportSocket, err := thrift.NewTSocket(*thriftAddr) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } - transport, err := transportFactory.GetTransport(transportSocket) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } - if err := transport.Open(); err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } - defer transport.Close() - client := addthrift.NewAddServiceClientFactory(transport, protocolFactory) - svc = addtransport.NewThriftClient(client) - } else { - fmt.Fprintf(os.Stderr, "error: no remote address specified\n") - os.Exit(1) - } - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } - - switch *method { - case "sum": - a, _ := strconv.ParseInt(fs.Args()[0], 10, 64) - b, _ := strconv.ParseInt(fs.Args()[1], 10, 64) - v, err := svc.Sum(context.Background(), int(a), int(b)) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } - fmt.Fprintf(os.Stdout, "%d + %d = %d\n", a, b, v) - - case "concat": - a := fs.Args()[0] - b := fs.Args()[1] - v, err := svc.Concat(context.Background(), a, b) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } - fmt.Fprintf(os.Stdout, "%q + %q = %q\n", a, b, v) - - default: - fmt.Fprintf(os.Stderr, "error: invalid method %q\n", method) - os.Exit(1) - } -} - -func usageFor(fs *flag.FlagSet, short string) func() { - return func() { - fmt.Fprintf(os.Stderr, "USAGE\n") - fmt.Fprintf(os.Stderr, " %s\n", short) - fmt.Fprintf(os.Stderr, "\n") - fmt.Fprintf(os.Stderr, "FLAGS\n") - w := tabwriter.NewWriter(os.Stderr, 0, 2, 2, ' ', 0) - fs.VisitAll(func(f *flag.Flag) { - fmt.Fprintf(w, "\t-%s %s\t%s\n", f.Name, f.DefValue, f.Usage) - }) - w.Flush() - fmt.Fprintf(os.Stderr, "\n") - } -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addsvc/addsvc.go b/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addsvc/addsvc.go deleted file mode 100644 index b1886e2f..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addsvc/addsvc.go +++ /dev/null @@ -1,279 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "net" - "net/http" - "os" - "os/signal" - "syscall" - "text/tabwriter" - - "github.com/apache/thrift/lib/go/thrift" - lightstep "github.com/lightstep/lightstep-tracer-go" - "github.com/oklog/oklog/pkg/group" - stdopentracing "github.com/opentracing/opentracing-go" - zipkin "github.com/openzipkin/zipkin-go-opentracing" - stdprometheus "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" - "google.golang.org/grpc" - "sourcegraph.com/sourcegraph/appdash" - appdashot "sourcegraph.com/sourcegraph/appdash/opentracing" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/prometheus" - - addpb "github.com/go-kit/kit/examples/addsvc/pb" - "github.com/go-kit/kit/examples/addsvc/pkg/addendpoint" - "github.com/go-kit/kit/examples/addsvc/pkg/addservice" - "github.com/go-kit/kit/examples/addsvc/pkg/addtransport" - addthrift "github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc" -) - -func main() { - // Define our flags. Your service probably won't need to bind listeners for - // *all* supported transports, or support both Zipkin and LightStep, and so - // on, but we do it here for demonstration purposes. - fs := flag.NewFlagSet("addsvc", flag.ExitOnError) - var ( - debugAddr = fs.String("debug.addr", ":8080", "Debug and metrics listen address") - httpAddr = fs.String("http-addr", ":8081", "HTTP listen address") - grpcAddr = fs.String("grpc-addr", ":8082", "gRPC listen address") - thriftAddr = fs.String("thrift-addr", ":8083", "Thrift listen address") - thriftProtocol = fs.String("thrift-protocol", "binary", "binary, compact, json, simplejson") - thriftBuffer = fs.Int("thrift-buffer", 0, "0 for unbuffered") - thriftFramed = fs.Bool("thrift-framed", false, "true to enable framing") - zipkinURL = fs.String("zipkin-url", "", "Enable Zipkin tracing via a collector URL e.g. http://localhost:9411/api/v1/spans") - lightstepToken = flag.String("lightstep-token", "", "Enable LightStep tracing via a LightStep access token") - appdashAddr = flag.String("appdash-addr", "", "Enable Appdash tracing via an Appdash server host:port") - ) - fs.Usage = usageFor(fs, os.Args[0]+" [flags]") - fs.Parse(os.Args[1:]) - - // Create a single logger, which we'll use and give to other components. - var logger log.Logger - { - logger = log.NewLogfmtLogger(os.Stderr) - logger = log.With(logger, "ts", log.DefaultTimestampUTC) - logger = log.With(logger, "caller", log.DefaultCaller) - } - - // Determine which tracer to use. We'll pass the tracer to all the - // components that use it, as a dependency. - var tracer stdopentracing.Tracer - { - if *zipkinURL != "" { - logger.Log("tracer", "Zipkin", "URL", *zipkinURL) - collector, err := zipkin.NewHTTPCollector(*zipkinURL) - if err != nil { - logger.Log("err", err) - os.Exit(1) - } - defer collector.Close() - var ( - debug = false - hostPort = "localhost:80" - serviceName = "addsvc" - ) - recorder := zipkin.NewRecorder(collector, debug, hostPort, serviceName) - tracer, err = zipkin.NewTracer(recorder) - if err != nil { - logger.Log("err", err) - os.Exit(1) - } - } else if *lightstepToken != "" { - logger.Log("tracer", "LightStep") // probably don't want to print out the token :) - tracer = lightstep.NewTracer(lightstep.Options{ - AccessToken: *lightstepToken, - }) - defer lightstep.FlushLightStepTracer(tracer) - } else if *appdashAddr != "" { - logger.Log("tracer", "Appdash", "addr", *appdashAddr) - tracer = appdashot.NewTracer(appdash.NewRemoteCollector(*appdashAddr)) - } else { - logger.Log("tracer", "none") - tracer = stdopentracing.GlobalTracer() // no-op - } - } - - // Create the (sparse) metrics we'll use in the service. They, too, are - // dependencies that we pass to components that use them. - var ints, chars metrics.Counter - { - // Business-level metrics. - ints = prometheus.NewCounterFrom(stdprometheus.CounterOpts{ - Namespace: "example", - Subsystem: "addsvc", - Name: "integers_summed", - Help: "Total count of integers summed via the Sum method.", - }, []string{}) - chars = prometheus.NewCounterFrom(stdprometheus.CounterOpts{ - Namespace: "example", - Subsystem: "addsvc", - Name: "characters_concatenated", - Help: "Total count of characters concatenated via the Concat method.", - }, []string{}) - } - var duration metrics.Histogram - { - // Endpoint-level metrics. - duration = prometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ - Namespace: "example", - Subsystem: "addsvc", - Name: "request_duration_seconds", - Help: "Request duration in seconds.", - }, []string{"method", "success"}) - } - http.DefaultServeMux.Handle("/metrics", promhttp.Handler()) - - // Build the layers of the service "onion" from the inside out. First, the - // business logic service; then, the set of endpoints that wrap the service; - // and finally, a series of concrete transport adapters. The adapters, like - // the HTTP handler or the gRPC server, are the bridge between Go kit and - // the interfaces that the transports expect. Note that we're not binding - // them to ports or anything yet; we'll do that next. - var ( - service = addservice.New(logger, ints, chars) - endpoints = addendpoint.New(service, logger, duration, tracer) - httpHandler = addtransport.NewHTTPHandler(endpoints, tracer, logger) - grpcServer = addtransport.NewGRPCServer(endpoints, tracer, logger) - thriftServer = addtransport.NewThriftServer(endpoints) - ) - - // Now we're to the part of the func main where we want to start actually - // running things, like servers bound to listeners to receive connections. - // - // The method is the same for each component: add a new actor to the group - // struct, which is a combination of 2 anonymous functions: the first - // function actually runs the component, and the second function should - // interrupt the first function and cause it to return. It's in these - // functions that we actually bind the Go kit server/handler structs to the - // concrete transports and run them. - // - // Putting each component into its own block is mostly for aesthetics: it - // clearly demarcates the scope in which each listener/socket may be used. - var g group.Group - { - // The debug listener mounts the http.DefaultServeMux, and serves up - // stuff like the Prometheus metrics route, the Go debug and profiling - // routes, and so on. - debugListener, err := net.Listen("tcp", *debugAddr) - if err != nil { - logger.Log("transport", "debug/HTTP", "during", "Listen", "err", err) - os.Exit(1) - } - g.Add(func() error { - logger.Log("transport", "debug/HTTP", "addr", *debugAddr) - return http.Serve(debugListener, http.DefaultServeMux) - }, func(error) { - debugListener.Close() - }) - } - { - // The HTTP listener mounts the Go kit HTTP handler we created. - httpListener, err := net.Listen("tcp", *httpAddr) - if err != nil { - logger.Log("transport", "HTTP", "during", "Listen", "err", err) - os.Exit(1) - } - g.Add(func() error { - logger.Log("transport", "HTTP", "addr", *httpAddr) - return http.Serve(httpListener, httpHandler) - }, func(error) { - httpListener.Close() - }) - } - { - // The gRPC listener mounts the Go kit gRPC server we created. - grpcListener, err := net.Listen("tcp", *grpcAddr) - if err != nil { - logger.Log("transport", "gRPC", "during", "Listen", "err", err) - os.Exit(1) - } - g.Add(func() error { - logger.Log("transport", "gRPC", "addr", *grpcAddr) - baseServer := grpc.NewServer() - addpb.RegisterAddServer(baseServer, grpcServer) - return baseServer.Serve(grpcListener) - }, func(error) { - grpcListener.Close() - }) - } - { - // The Thrift socket mounts the Go kit Thrift server we created earlier. - // There's a lot of boilerplate involved here, related to configuring - // the protocol and transport; blame Thrift. - thriftSocket, err := thrift.NewTServerSocket(*thriftAddr) - if err != nil { - logger.Log("transport", "Thrift", "during", "Listen", "err", err) - os.Exit(1) - } - g.Add(func() error { - logger.Log("transport", "Thrift", "addr", *thriftAddr) - var protocolFactory thrift.TProtocolFactory - switch *thriftProtocol { - case "binary": - protocolFactory = thrift.NewTBinaryProtocolFactoryDefault() - case "compact": - protocolFactory = thrift.NewTCompactProtocolFactory() - case "json": - protocolFactory = thrift.NewTJSONProtocolFactory() - case "simplejson": - protocolFactory = thrift.NewTSimpleJSONProtocolFactory() - default: - return fmt.Errorf("invalid Thrift protocol %q", *thriftProtocol) - } - var transportFactory thrift.TTransportFactory - if *thriftBuffer > 0 { - transportFactory = thrift.NewTBufferedTransportFactory(*thriftBuffer) - } else { - transportFactory = thrift.NewTTransportFactory() - } - if *thriftFramed { - transportFactory = thrift.NewTFramedTransportFactory(transportFactory) - } - return thrift.NewTSimpleServer4( - addthrift.NewAddServiceProcessor(thriftServer), - thriftSocket, - transportFactory, - protocolFactory, - ).Serve() - }, func(error) { - thriftSocket.Close() - }) - } - { - // This function just sits and waits for ctrl-C. - cancelInterrupt := make(chan struct{}) - g.Add(func() error { - c := make(chan os.Signal, 1) - signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) - select { - case sig := <-c: - return fmt.Errorf("received signal %s", sig) - case <-cancelInterrupt: - return nil - } - }, func(error) { - close(cancelInterrupt) - }) - } - logger.Log("exit", g.Run()) -} - -func usageFor(fs *flag.FlagSet, short string) func() { - return func() { - fmt.Fprintf(os.Stderr, "USAGE\n") - fmt.Fprintf(os.Stderr, " %s\n", short) - fmt.Fprintf(os.Stderr, "\n") - fmt.Fprintf(os.Stderr, "FLAGS\n") - w := tabwriter.NewWriter(os.Stderr, 0, 2, 2, ' ', 0) - fs.VisitAll(func(f *flag.Flag) { - fmt.Fprintf(w, "\t-%s %s\t%s\n", f.Name, f.DefValue, f.Usage) - }) - w.Flush() - fmt.Fprintf(os.Stderr, "\n") - } -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addsvc/pact_test.go b/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addsvc/pact_test.go deleted file mode 100644 index 2c709b58..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addsvc/pact_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "os" - "strings" - "testing" - - "github.com/pact-foundation/pact-go/dsl" -) - -func TestPactStringsvcUppercase(t *testing.T) { - if os.Getenv("WRITE_PACTS") == "" { - t.Skip("skipping Pact contracts; set WRITE_PACTS environment variable to enable") - } - - pact := dsl.Pact{ - Port: 6666, - Consumer: "addsvc", - Provider: "stringsvc", - } - defer pact.Teardown() - - pact.AddInteraction(). - UponReceiving("stringsvc uppercase"). - WithRequest(dsl.Request{ - Headers: map[string]string{"Content-Type": "application/json; charset=utf-8"}, - Method: "POST", - Path: "/uppercase", - Body: `{"s":"foo"}`, - }). - WillRespondWith(dsl.Response{ - Status: 200, - Headers: map[string]string{"Content-Type": "application/json; charset=utf-8"}, - Body: `{"v":"FOO"}`, - }) - - if err := pact.Verify(func() error { - u := fmt.Sprintf("http://localhost:%d/uppercase", pact.Server.Port) - req, err := http.NewRequest("POST", u, strings.NewReader(`{"s":"foo"}`)) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/json; charset=utf-8") - if _, err = http.DefaultClient.Do(req); err != nil { - return err - } - return nil - }); err != nil { - t.Fatal(err) - } - - pact.WritePact() -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addsvc/wiring_test.go b/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addsvc/wiring_test.go deleted file mode 100644 index ca64bac1..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/cmd/addsvc/wiring_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/opentracing/opentracing-go" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/metrics/discard" - - "github.com/go-kit/kit/examples/addsvc/pkg/addendpoint" - "github.com/go-kit/kit/examples/addsvc/pkg/addservice" - "github.com/go-kit/kit/examples/addsvc/pkg/addtransport" -) - -func TestHTTP(t *testing.T) { - svc := addservice.New(log.NewNopLogger(), discard.NewCounter(), discard.NewCounter()) - eps := addendpoint.New(svc, log.NewNopLogger(), discard.NewHistogram(), opentracing.GlobalTracer()) - mux := addtransport.NewHTTPHandler(eps, opentracing.GlobalTracer(), log.NewNopLogger()) - srv := httptest.NewServer(mux) - defer srv.Close() - - for _, testcase := range []struct { - method, url, body, want string - }{ - {"GET", srv.URL + "/concat", `{"a":"1","b":"2"}`, `{"v":"12"}`}, - {"GET", srv.URL + "/sum", `{"a":1,"b":2}`, `{"v":3}`}, - } { - req, _ := http.NewRequest(testcase.method, testcase.url, strings.NewReader(testcase.body)) - resp, _ := http.DefaultClient.Do(req) - body, _ := ioutil.ReadAll(resp.Body) - if want, have := testcase.want, strings.TrimSpace(string(body)); want != have { - t.Errorf("%s %s %s: want %q, have %q", testcase.method, testcase.url, testcase.body, want, have) - } - } -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/pb/addsvc.pb.go b/vendor/github.com/go-kit/kit/examples/addsvc/pb/addsvc.pb.go deleted file mode 100644 index 781b50b7..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/pb/addsvc.pb.go +++ /dev/null @@ -1,270 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: addsvc.proto - -/* -Package pb is a generated protocol buffer package. - -It is generated from these files: - addsvc.proto - -It has these top-level messages: - SumRequest - SumReply - ConcatRequest - ConcatReply -*/ -package pb - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The sum request contains two parameters. -type SumRequest struct { - A int64 `protobuf:"varint,1,opt,name=a" json:"a,omitempty"` - B int64 `protobuf:"varint,2,opt,name=b" json:"b,omitempty"` -} - -func (m *SumRequest) Reset() { *m = SumRequest{} } -func (m *SumRequest) String() string { return proto.CompactTextString(m) } -func (*SumRequest) ProtoMessage() {} -func (*SumRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *SumRequest) GetA() int64 { - if m != nil { - return m.A - } - return 0 -} - -func (m *SumRequest) GetB() int64 { - if m != nil { - return m.B - } - return 0 -} - -// The sum response contains the result of the calculation. -type SumReply struct { - V int64 `protobuf:"varint,1,opt,name=v" json:"v,omitempty"` - Err string `protobuf:"bytes,2,opt,name=err" json:"err,omitempty"` -} - -func (m *SumReply) Reset() { *m = SumReply{} } -func (m *SumReply) String() string { return proto.CompactTextString(m) } -func (*SumReply) ProtoMessage() {} -func (*SumReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *SumReply) GetV() int64 { - if m != nil { - return m.V - } - return 0 -} - -func (m *SumReply) GetErr() string { - if m != nil { - return m.Err - } - return "" -} - -// The Concat request contains two parameters. -type ConcatRequest struct { - A string `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"` - B string `protobuf:"bytes,2,opt,name=b" json:"b,omitempty"` -} - -func (m *ConcatRequest) Reset() { *m = ConcatRequest{} } -func (m *ConcatRequest) String() string { return proto.CompactTextString(m) } -func (*ConcatRequest) ProtoMessage() {} -func (*ConcatRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func (m *ConcatRequest) GetA() string { - if m != nil { - return m.A - } - return "" -} - -func (m *ConcatRequest) GetB() string { - if m != nil { - return m.B - } - return "" -} - -// The Concat response contains the result of the concatenation. -type ConcatReply struct { - V string `protobuf:"bytes,1,opt,name=v" json:"v,omitempty"` - Err string `protobuf:"bytes,2,opt,name=err" json:"err,omitempty"` -} - -func (m *ConcatReply) Reset() { *m = ConcatReply{} } -func (m *ConcatReply) String() string { return proto.CompactTextString(m) } -func (*ConcatReply) ProtoMessage() {} -func (*ConcatReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } - -func (m *ConcatReply) GetV() string { - if m != nil { - return m.V - } - return "" -} - -func (m *ConcatReply) GetErr() string { - if m != nil { - return m.Err - } - return "" -} - -func init() { - proto.RegisterType((*SumRequest)(nil), "pb.SumRequest") - proto.RegisterType((*SumReply)(nil), "pb.SumReply") - proto.RegisterType((*ConcatRequest)(nil), "pb.ConcatRequest") - proto.RegisterType((*ConcatReply)(nil), "pb.ConcatReply") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for Add service - -type AddClient interface { - // Sums two integers. - Sum(ctx context.Context, in *SumRequest, opts ...grpc.CallOption) (*SumReply, error) - // Concatenates two strings - Concat(ctx context.Context, in *ConcatRequest, opts ...grpc.CallOption) (*ConcatReply, error) -} - -type addClient struct { - cc *grpc.ClientConn -} - -func NewAddClient(cc *grpc.ClientConn) AddClient { - return &addClient{cc} -} - -func (c *addClient) Sum(ctx context.Context, in *SumRequest, opts ...grpc.CallOption) (*SumReply, error) { - out := new(SumReply) - err := grpc.Invoke(ctx, "/pb.Add/Sum", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *addClient) Concat(ctx context.Context, in *ConcatRequest, opts ...grpc.CallOption) (*ConcatReply, error) { - out := new(ConcatReply) - err := grpc.Invoke(ctx, "/pb.Add/Concat", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Add service - -type AddServer interface { - // Sums two integers. - Sum(context.Context, *SumRequest) (*SumReply, error) - // Concatenates two strings - Concat(context.Context, *ConcatRequest) (*ConcatReply, error) -} - -func RegisterAddServer(s *grpc.Server, srv AddServer) { - s.RegisterService(&_Add_serviceDesc, srv) -} - -func _Add_Sum_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SumRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AddServer).Sum(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Add/Sum", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AddServer).Sum(ctx, req.(*SumRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Add_Concat_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ConcatRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AddServer).Concat(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pb.Add/Concat", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AddServer).Concat(ctx, req.(*ConcatRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Add_serviceDesc = grpc.ServiceDesc{ - ServiceName: "pb.Add", - HandlerType: (*AddServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Sum", - Handler: _Add_Sum_Handler, - }, - { - MethodName: "Concat", - Handler: _Add_Concat_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "addsvc.proto", -} - -func init() { proto.RegisterFile("addsvc.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 189 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x49, 0x4c, 0x49, 0x29, - 0x2e, 0x4b, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2a, 0x48, 0x52, 0xd2, 0xe0, 0xe2, - 0x0a, 0x2e, 0xcd, 0x0d, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0x11, 0xe2, 0xe1, 0x62, 0x4c, 0x94, - 0x60, 0x54, 0x60, 0xd4, 0x60, 0x0e, 0x62, 0x4c, 0x04, 0xf1, 0x92, 0x24, 0x98, 0x20, 0xbc, 0x24, - 0x25, 0x2d, 0x2e, 0x0e, 0xb0, 0xca, 0x82, 0x9c, 0x4a, 0x90, 0x4c, 0x19, 0x4c, 0x5d, 0x99, 0x90, - 0x00, 0x17, 0x73, 0x6a, 0x51, 0x11, 0x58, 0x25, 0x67, 0x10, 0x88, 0xa9, 0xa4, 0xcd, 0xc5, 0xeb, - 0x9c, 0x9f, 0x97, 0x9c, 0x58, 0x82, 0x61, 0x30, 0x27, 0x8a, 0xc1, 0x9c, 0x20, 0x83, 0x75, 0xb9, - 0xb8, 0x61, 0x8a, 0x51, 0xcc, 0xe6, 0xc4, 0x6a, 0xb6, 0x51, 0x0c, 0x17, 0xb3, 0x63, 0x4a, 0x8a, - 0x90, 0x2a, 0x17, 0x73, 0x70, 0x69, 0xae, 0x10, 0x9f, 0x5e, 0x41, 0x92, 0x1e, 0xc2, 0x07, 0x52, - 0x3c, 0x70, 0x7e, 0x41, 0x4e, 0xa5, 0x12, 0x83, 0x90, 0x1e, 0x17, 0x1b, 0xc4, 0x70, 0x21, 0x41, - 0x90, 0x0c, 0x8a, 0xab, 0xa4, 0xf8, 0x91, 0x85, 0xc0, 0xea, 0x93, 0xd8, 0xc0, 0x41, 0x63, 0x0c, - 0x08, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x37, 0x81, 0x99, 0x2a, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/pb/addsvc.proto b/vendor/github.com/go-kit/kit/examples/addsvc/pb/addsvc.proto deleted file mode 100644 index cf61532f..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/pb/addsvc.proto +++ /dev/null @@ -1,36 +0,0 @@ -syntax = "proto3"; - -package pb; - -// The Add service definition. -service Add { - // Sums two integers. - rpc Sum (SumRequest) returns (SumReply) {} - - // Concatenates two strings - rpc Concat (ConcatRequest) returns (ConcatReply) {} -} - -// The sum request contains two parameters. -message SumRequest { - int64 a = 1; - int64 b = 2; -} - -// The sum response contains the result of the calculation. -message SumReply { - int64 v = 1; - string err = 2; -} - -// The Concat request contains two parameters. -message ConcatRequest { - string a = 1; - string b = 2; -} - -// The Concat response contains the result of the concatenation. -message ConcatReply { - string v = 1; - string err = 2; -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/pb/compile.sh b/vendor/github.com/go-kit/kit/examples/addsvc/pb/compile.sh deleted file mode 100755 index c0268442..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/pb/compile.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env sh - -# Install proto3 from source -# brew install autoconf automake libtool -# git clone https://github.com/google/protobuf -# ./autogen.sh ; ./configure ; make ; make install -# -# Update protoc Go bindings via -# go get -u github.com/golang/protobuf/{proto,protoc-gen-go} -# -# See also -# https://github.com/grpc/grpc-go/tree/master/examples - -protoc addsvc.proto --go_out=plugins=grpc:. diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addendpoint/middleware.go b/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addendpoint/middleware.go deleted file mode 100644 index c83047b7..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addendpoint/middleware.go +++ /dev/null @@ -1,43 +0,0 @@ -package addendpoint - -import ( - "context" - "fmt" - "time" - - "github.com/go-kit/kit/endpoint" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/metrics" -) - -// InstrumentingMiddleware returns an endpoint middleware that records -// the duration of each invocation to the passed histogram. The middleware adds -// a single field: "success", which is "true" if no error is returned, and -// "false" otherwise. -func InstrumentingMiddleware(duration metrics.Histogram) endpoint.Middleware { - return func(next endpoint.Endpoint) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - - defer func(begin time.Time) { - duration.With("success", fmt.Sprint(err == nil)).Observe(time.Since(begin).Seconds()) - }(time.Now()) - return next(ctx, request) - - } - } -} - -// LoggingMiddleware returns an endpoint middleware that logs the -// duration of each invocation, and the resulting error, if any. -func LoggingMiddleware(logger log.Logger) endpoint.Middleware { - return func(next endpoint.Endpoint) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - - defer func(begin time.Time) { - logger.Log("transport_error", err, "took", time.Since(begin)) - }(time.Now()) - return next(ctx, request) - - } - } -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addendpoint/set.go b/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addendpoint/set.go deleted file mode 100644 index 3a65b083..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addendpoint/set.go +++ /dev/null @@ -1,128 +0,0 @@ -package addendpoint - -import ( - "context" - - rl "github.com/juju/ratelimit" - stdopentracing "github.com/opentracing/opentracing-go" - "github.com/sony/gobreaker" - - "github.com/go-kit/kit/circuitbreaker" - "github.com/go-kit/kit/endpoint" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/ratelimit" - "github.com/go-kit/kit/tracing/opentracing" - - "github.com/go-kit/kit/examples/addsvc/pkg/addservice" -) - -// Set collects all of the endpoints that compose an add service. It's meant to -// be used as a helper struct, to collect all of the endpoints into a single -// parameter. -type Set struct { - SumEndpoint endpoint.Endpoint - ConcatEndpoint endpoint.Endpoint -} - -// New returns a Set that wraps the provided server, and wires in all of the -// expected endpoint middlewares via the various parameters. -func New(svc addservice.Service, logger log.Logger, duration metrics.Histogram, trace stdopentracing.Tracer) Set { - var sumEndpoint endpoint.Endpoint - { - sumEndpoint = MakeSumEndpoint(svc) - sumEndpoint = ratelimit.NewTokenBucketLimiter(rl.NewBucketWithRate(1, 1))(sumEndpoint) - sumEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{}))(sumEndpoint) - sumEndpoint = opentracing.TraceServer(trace, "Sum")(sumEndpoint) - sumEndpoint = LoggingMiddleware(log.With(logger, "method", "Sum"))(sumEndpoint) - sumEndpoint = InstrumentingMiddleware(duration.With("method", "Sum"))(sumEndpoint) - } - var concatEndpoint endpoint.Endpoint - { - concatEndpoint = MakeConcatEndpoint(svc) - concatEndpoint = ratelimit.NewTokenBucketLimiter(rl.NewBucketWithRate(100, 100))(concatEndpoint) - concatEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{}))(concatEndpoint) - concatEndpoint = opentracing.TraceServer(trace, "Concat")(concatEndpoint) - concatEndpoint = LoggingMiddleware(log.With(logger, "method", "Concat"))(concatEndpoint) - concatEndpoint = InstrumentingMiddleware(duration.With("method", "Concat"))(concatEndpoint) - } - return Set{ - SumEndpoint: sumEndpoint, - ConcatEndpoint: concatEndpoint, - } -} - -// Sum implements the service interface, so Set may be used as a service. -// This is primarily useful in the context of a client library. -func (s Set) Sum(ctx context.Context, a, b int) (int, error) { - resp, err := s.SumEndpoint(ctx, SumRequest{A: a, B: b}) - if err != nil { - return 0, err - } - response := resp.(SumResponse) - return response.V, response.Err -} - -// Concat implements the service interface, so Set may be used as a -// service. This is primarily useful in the context of a client library. -func (s Set) Concat(ctx context.Context, a, b string) (string, error) { - resp, err := s.ConcatEndpoint(ctx, ConcatRequest{A: a, B: b}) - if err != nil { - return "", err - } - response := resp.(ConcatResponse) - return response.V, response.Err -} - -// MakeSumEndpoint constructs a Sum endpoint wrapping the service. -func MakeSumEndpoint(s addservice.Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(SumRequest) - v, err := s.Sum(ctx, req.A, req.B) - return SumResponse{V: v, Err: err}, nil - } -} - -// MakeConcatEndpoint constructs a Concat endpoint wrapping the service. -func MakeConcatEndpoint(s addservice.Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(ConcatRequest) - v, err := s.Concat(ctx, req.A, req.B) - return ConcatResponse{V: v, Err: err}, nil - } -} - -// Failer is an interface that should be implemented by response types. -// Response encoders can check if responses are Failer, and if so if they've -// failed, and if so encode them using a separate write path based on the error. -type Failer interface { - Failed() error -} - -// SumRequest collects the request parameters for the Sum method. -type SumRequest struct { - A, B int -} - -// SumResponse collects the response values for the Sum method. -type SumResponse struct { - V int `json:"v"` - Err error `json:"-"` // should be intercepted by Failed/errorEncoder -} - -// Failed implements Failer. -func (r SumResponse) Failed() error { return r.Err } - -// ConcatRequest collects the request parameters for the Concat method. -type ConcatRequest struct { - A, B string -} - -// ConcatResponse collects the response values for the Concat method. -type ConcatResponse struct { - V string `json:"v"` - Err error `json:"-"` -} - -// Failed implements Failer. -func (r ConcatResponse) Failed() error { return r.Err } diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addservice/middleware.go b/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addservice/middleware.go deleted file mode 100644 index 5a1d6ee5..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addservice/middleware.go +++ /dev/null @@ -1,69 +0,0 @@ -package addservice - -import ( - "context" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/metrics" -) - -// Middleware describes a service (as opposed to endpoint) middleware. -type Middleware func(Service) Service - -// LoggingMiddleware takes a logger as a dependency -// and returns a ServiceMiddleware. -func LoggingMiddleware(logger log.Logger) Middleware { - return func(next Service) Service { - return loggingMiddleware{logger, next} - } -} - -type loggingMiddleware struct { - logger log.Logger - next Service -} - -func (mw loggingMiddleware) Sum(ctx context.Context, a, b int) (v int, err error) { - defer func() { - mw.logger.Log("method", "Sum", "a", a, "b", b, "v", v, "err", err) - }() - return mw.next.Sum(ctx, a, b) -} - -func (mw loggingMiddleware) Concat(ctx context.Context, a, b string) (v string, err error) { - defer func() { - mw.logger.Log("method", "Concat", "a", a, "b", b, "v", v, "err", err) - }() - return mw.next.Concat(ctx, a, b) -} - -// InstrumentingMiddleware returns a service middleware that instruments -// the number of integers summed and characters concatenated over the lifetime of -// the service. -func InstrumentingMiddleware(ints, chars metrics.Counter) Middleware { - return func(next Service) Service { - return instrumentingMiddleware{ - ints: ints, - chars: chars, - next: next, - } - } -} - -type instrumentingMiddleware struct { - ints metrics.Counter - chars metrics.Counter - next Service -} - -func (mw instrumentingMiddleware) Sum(ctx context.Context, a, b int) (int, error) { - v, err := mw.next.Sum(ctx, a, b) - mw.ints.Add(float64(v)) - return v, err -} - -func (mw instrumentingMiddleware) Concat(ctx context.Context, a, b string) (string, error) { - v, err := mw.next.Concat(ctx, a, b) - mw.chars.Add(float64(len(v))) - return v, err -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addservice/service.go b/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addservice/service.go deleted file mode 100644 index d884373b..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addservice/service.go +++ /dev/null @@ -1,71 +0,0 @@ -package addservice - -import ( - "context" - "errors" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/metrics" -) - -// Service describes a service that adds things together. -type Service interface { - Sum(ctx context.Context, a, b int) (int, error) - Concat(ctx context.Context, a, b string) (string, error) -} - -// New returns a basic Service with all of the expected middlewares wired in. -func New(logger log.Logger, ints, chars metrics.Counter) Service { - var svc Service - { - svc = NewBasicService() - svc = LoggingMiddleware(logger)(svc) - svc = InstrumentingMiddleware(ints, chars)(svc) - } - return svc -} - -var ( - // ErrTwoZeroes is an arbitrary business rule for the Add method. - ErrTwoZeroes = errors.New("can't sum two zeroes") - - // ErrIntOverflow protects the Add method. We've decided that this error - // indicates a misbehaving service and should count against e.g. circuit - // breakers. So, we return it directly in endpoints, to illustrate the - // difference. In a real service, this probably wouldn't be the case. - ErrIntOverflow = errors.New("integer overflow") - - // ErrMaxSizeExceeded protects the Concat method. - ErrMaxSizeExceeded = errors.New("result exceeds maximum size") -) - -// NewBasicService returns a naïve, stateless implementation of Service. -func NewBasicService() Service { - return basicService{} -} - -type basicService struct{} - -const ( - intMax = 1<<31 - 1 - intMin = -(intMax + 1) - maxLen = 10 -) - -func (s basicService) Sum(_ context.Context, a, b int) (int, error) { - if a == 0 && b == 0 { - return 0, ErrTwoZeroes - } - if (b > 0 && a > (intMax-b)) || (b < 0 && a < (intMin-b)) { - return 0, ErrIntOverflow - } - return a + b, nil -} - -// Concat implements Service. -func (s basicService) Concat(_ context.Context, a, b string) (string, error) { - if len(a)+len(b) > maxLen { - return "", ErrMaxSizeExceeded - } - return a + b, nil -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addtransport/grpc.go b/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addtransport/grpc.go deleted file mode 100644 index ec05baa8..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addtransport/grpc.go +++ /dev/null @@ -1,210 +0,0 @@ -package addtransport - -import ( - "context" - "errors" - "time" - - "google.golang.org/grpc" - - jujuratelimit "github.com/juju/ratelimit" - stdopentracing "github.com/opentracing/opentracing-go" - "github.com/sony/gobreaker" - oldcontext "golang.org/x/net/context" - - "github.com/go-kit/kit/circuitbreaker" - "github.com/go-kit/kit/endpoint" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/ratelimit" - "github.com/go-kit/kit/tracing/opentracing" - grpctransport "github.com/go-kit/kit/transport/grpc" - - "github.com/go-kit/kit/examples/addsvc/pb" - "github.com/go-kit/kit/examples/addsvc/pkg/addendpoint" - "github.com/go-kit/kit/examples/addsvc/pkg/addservice" -) - -type grpcServer struct { - sum grpctransport.Handler - concat grpctransport.Handler -} - -// NewGRPCServer makes a set of endpoints available as a gRPC AddServer. -func NewGRPCServer(endpoints addendpoint.Set, tracer stdopentracing.Tracer, logger log.Logger) pb.AddServer { - options := []grpctransport.ServerOption{ - grpctransport.ServerErrorLogger(logger), - } - return &grpcServer{ - sum: grpctransport.NewServer( - endpoints.SumEndpoint, - decodeGRPCSumRequest, - encodeGRPCSumResponse, - append(options, grpctransport.ServerBefore(opentracing.GRPCToContext(tracer, "Sum", logger)))..., - ), - concat: grpctransport.NewServer( - endpoints.ConcatEndpoint, - decodeGRPCConcatRequest, - encodeGRPCConcatResponse, - append(options, grpctransport.ServerBefore(opentracing.GRPCToContext(tracer, "Concat", logger)))..., - ), - } -} - -func (s *grpcServer) Sum(ctx oldcontext.Context, req *pb.SumRequest) (*pb.SumReply, error) { - _, rep, err := s.sum.ServeGRPC(ctx, req) - if err != nil { - return nil, err - } - return rep.(*pb.SumReply), nil -} - -func (s *grpcServer) Concat(ctx oldcontext.Context, req *pb.ConcatRequest) (*pb.ConcatReply, error) { - _, rep, err := s.concat.ServeGRPC(ctx, req) - if err != nil { - return nil, err - } - return rep.(*pb.ConcatReply), nil -} - -// NewGRPCClient returns an AddService backed by a gRPC server at the other end -// of the conn. The caller is responsible for constructing the conn, and -// eventually closing the underlying transport. We bake-in certain middlewares, -// implementing the client library pattern. -func NewGRPCClient(conn *grpc.ClientConn, tracer stdopentracing.Tracer, logger log.Logger) addservice.Service { - // We construct a single ratelimiter middleware, to limit the total outgoing - // QPS from this client to all methods on the remote instance. We also - // construct per-endpoint circuitbreaker middlewares to demonstrate how - // that's done, although they could easily be combined into a single breaker - // for the entire remote instance, too. - limiter := ratelimit.NewTokenBucketLimiter(jujuratelimit.NewBucketWithRate(100, 100)) - - // Each individual endpoint is an http/transport.Client (which implements - // endpoint.Endpoint) that gets wrapped with various middlewares. If you - // made your own client library, you'd do this work there, so your server - // could rely on a consistent set of client behavior. - var sumEndpoint endpoint.Endpoint - { - sumEndpoint = grpctransport.NewClient( - conn, - "pb.Add", - "Sum", - encodeGRPCSumRequest, - decodeGRPCSumResponse, - pb.SumReply{}, - grpctransport.ClientBefore(opentracing.ContextToGRPC(tracer, logger)), - ).Endpoint() - sumEndpoint = opentracing.TraceClient(tracer, "Sum")(sumEndpoint) - sumEndpoint = limiter(sumEndpoint) - sumEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{ - Name: "Sum", - Timeout: 30 * time.Second, - }))(sumEndpoint) - } - - // The Concat endpoint is the same thing, with slightly different - // middlewares to demonstrate how to specialize per-endpoint. - var concatEndpoint endpoint.Endpoint - { - concatEndpoint = grpctransport.NewClient( - conn, - "pb.Add", - "Concat", - encodeGRPCConcatRequest, - decodeGRPCConcatResponse, - pb.ConcatReply{}, - grpctransport.ClientBefore(opentracing.ContextToGRPC(tracer, logger)), - ).Endpoint() - concatEndpoint = opentracing.TraceClient(tracer, "Concat")(concatEndpoint) - concatEndpoint = limiter(concatEndpoint) - concatEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{ - Name: "Concat", - Timeout: 10 * time.Second, - }))(concatEndpoint) - } - - // Returning the endpoint.Set as a service.Service relies on the - // endpoint.Set implementing the Service methods. That's just a simple bit - // of glue code. - return addendpoint.Set{ - SumEndpoint: sumEndpoint, - ConcatEndpoint: concatEndpoint, - } -} - -// decodeGRPCSumRequest is a transport/grpc.DecodeRequestFunc that converts a -// gRPC sum request to a user-domain sum request. Primarily useful in a server. -func decodeGRPCSumRequest(_ context.Context, grpcReq interface{}) (interface{}, error) { - req := grpcReq.(*pb.SumRequest) - return addendpoint.SumRequest{A: int(req.A), B: int(req.B)}, nil -} - -// decodeGRPCConcatRequest is a transport/grpc.DecodeRequestFunc that converts a -// gRPC concat request to a user-domain concat request. Primarily useful in a -// server. -func decodeGRPCConcatRequest(_ context.Context, grpcReq interface{}) (interface{}, error) { - req := grpcReq.(*pb.ConcatRequest) - return addendpoint.ConcatRequest{A: req.A, B: req.B}, nil -} - -// decodeGRPCSumResponse is a transport/grpc.DecodeResponseFunc that converts a -// gRPC sum reply to a user-domain sum response. Primarily useful in a client. -func decodeGRPCSumResponse(_ context.Context, grpcReply interface{}) (interface{}, error) { - reply := grpcReply.(*pb.SumReply) - return addendpoint.SumResponse{V: int(reply.V), Err: str2err(reply.Err)}, nil -} - -// decodeGRPCConcatResponse is a transport/grpc.DecodeResponseFunc that converts -// a gRPC concat reply to a user-domain concat response. Primarily useful in a -// client. -func decodeGRPCConcatResponse(_ context.Context, grpcReply interface{}) (interface{}, error) { - reply := grpcReply.(*pb.ConcatReply) - return addendpoint.ConcatResponse{V: reply.V, Err: str2err(reply.Err)}, nil -} - -// encodeGRPCSumResponse is a transport/grpc.EncodeResponseFunc that converts a -// user-domain sum response to a gRPC sum reply. Primarily useful in a server. -func encodeGRPCSumResponse(_ context.Context, response interface{}) (interface{}, error) { - resp := response.(addendpoint.SumResponse) - return &pb.SumReply{V: int64(resp.V), Err: err2str(resp.Err)}, nil -} - -// encodeGRPCConcatResponse is a transport/grpc.EncodeResponseFunc that converts -// a user-domain concat response to a gRPC concat reply. Primarily useful in a -// server. -func encodeGRPCConcatResponse(_ context.Context, response interface{}) (interface{}, error) { - resp := response.(addendpoint.ConcatResponse) - return &pb.ConcatReply{V: resp.V, Err: err2str(resp.Err)}, nil -} - -// encodeGRPCSumRequest is a transport/grpc.EncodeRequestFunc that converts a -// user-domain sum request to a gRPC sum request. Primarily useful in a client. -func encodeGRPCSumRequest(_ context.Context, request interface{}) (interface{}, error) { - req := request.(addendpoint.SumRequest) - return &pb.SumRequest{A: int64(req.A), B: int64(req.B)}, nil -} - -// encodeGRPCConcatRequest is a transport/grpc.EncodeRequestFunc that converts a -// user-domain concat request to a gRPC concat request. Primarily useful in a -// client. -func encodeGRPCConcatRequest(_ context.Context, request interface{}) (interface{}, error) { - req := request.(addendpoint.ConcatRequest) - return &pb.ConcatRequest{A: req.A, B: req.B}, nil -} - -// These annoying helper functions are required to translate Go error types to -// and from strings, which is the type we use in our IDLs to represent errors. -// There is special casing to treat empty strings as nil errors. - -func str2err(s string) error { - if s == "" { - return nil - } - return errors.New(s) -} - -func err2str(err error) string { - if err == nil { - return "" - } - return err.Error() -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addtransport/http.go b/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addtransport/http.go deleted file mode 100644 index ecdee928..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addtransport/http.go +++ /dev/null @@ -1,219 +0,0 @@ -package addtransport - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" - - jujuratelimit "github.com/juju/ratelimit" - stdopentracing "github.com/opentracing/opentracing-go" - "github.com/sony/gobreaker" - - "github.com/go-kit/kit/circuitbreaker" - "github.com/go-kit/kit/endpoint" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/ratelimit" - "github.com/go-kit/kit/tracing/opentracing" - httptransport "github.com/go-kit/kit/transport/http" - - "github.com/go-kit/kit/examples/addsvc/pkg/addendpoint" - "github.com/go-kit/kit/examples/addsvc/pkg/addservice" -) - -// NewHTTPHandler returns an HTTP handler that makes a set of endpoints -// available on predefined paths. -func NewHTTPHandler(endpoints addendpoint.Set, tracer stdopentracing.Tracer, logger log.Logger) http.Handler { - options := []httptransport.ServerOption{ - httptransport.ServerErrorEncoder(errorEncoder), - httptransport.ServerErrorLogger(logger), - } - m := http.NewServeMux() - m.Handle("/sum", httptransport.NewServer( - endpoints.SumEndpoint, - decodeHTTPSumRequest, - encodeHTTPGenericResponse, - append(options, httptransport.ServerBefore(opentracing.HTTPToContext(tracer, "Sum", logger)))..., - )) - m.Handle("/concat", httptransport.NewServer( - endpoints.ConcatEndpoint, - decodeHTTPConcatRequest, - encodeHTTPGenericResponse, - append(options, httptransport.ServerBefore(opentracing.HTTPToContext(tracer, "Concat", logger)))..., - )) - return m -} - -// NewHTTPClient returns an AddService backed by an HTTP server living at the -// remote instance. We expect instance to come from a service discovery system, -// so likely of the form "host:port". We bake-in certain middlewares, -// implementing the client library pattern. -func NewHTTPClient(instance string, tracer stdopentracing.Tracer, logger log.Logger) (addservice.Service, error) { - // Quickly sanitize the instance string. - if !strings.HasPrefix(instance, "http") { - instance = "http://" + instance - } - u, err := url.Parse(instance) - if err != nil { - return nil, err - } - - // We construct a single ratelimiter middleware, to limit the total outgoing - // QPS from this client to all methods on the remote instance. We also - // construct per-endpoint circuitbreaker middlewares to demonstrate how - // that's done, although they could easily be combined into a single breaker - // for the entire remote instance, too. - limiter := ratelimit.NewTokenBucketLimiter(jujuratelimit.NewBucketWithRate(100, 100)) - - // Each individual endpoint is an http/transport.Client (which implements - // endpoint.Endpoint) that gets wrapped with various middlewares. If you - // made your own client library, you'd do this work there, so your server - // could rely on a consistent set of client behavior. - var sumEndpoint endpoint.Endpoint - { - sumEndpoint = httptransport.NewClient( - "POST", - copyURL(u, "/sum"), - encodeHTTPGenericRequest, - decodeHTTPSumResponse, - httptransport.ClientBefore(opentracing.ContextToHTTP(tracer, logger)), - ).Endpoint() - sumEndpoint = opentracing.TraceClient(tracer, "Sum")(sumEndpoint) - sumEndpoint = limiter(sumEndpoint) - sumEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{ - Name: "Sum", - Timeout: 30 * time.Second, - }))(sumEndpoint) - } - - // The Concat endpoint is the same thing, with slightly different - // middlewares to demonstrate how to specialize per-endpoint. - var concatEndpoint endpoint.Endpoint - { - concatEndpoint = httptransport.NewClient( - "POST", - copyURL(u, "/concat"), - encodeHTTPGenericRequest, - decodeHTTPConcatResponse, - httptransport.ClientBefore(opentracing.ContextToHTTP(tracer, logger)), - ).Endpoint() - concatEndpoint = opentracing.TraceClient(tracer, "Concat")(concatEndpoint) - concatEndpoint = limiter(concatEndpoint) - concatEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{ - Name: "Concat", - Timeout: 10 * time.Second, - }))(concatEndpoint) - } - - // Returning the endpoint.Set as a service.Service relies on the - // endpoint.Set implementing the Service methods. That's just a simple bit - // of glue code. - return addendpoint.Set{ - SumEndpoint: sumEndpoint, - ConcatEndpoint: concatEndpoint, - }, nil -} - -func copyURL(base *url.URL, path string) *url.URL { - next := *base - next.Path = path - return &next -} - -func errorEncoder(_ context.Context, err error, w http.ResponseWriter) { - w.WriteHeader(err2code(err)) - json.NewEncoder(w).Encode(errorWrapper{Error: err.Error()}) -} - -func err2code(err error) int { - switch err { - case addservice.ErrTwoZeroes, addservice.ErrMaxSizeExceeded, addservice.ErrIntOverflow: - return http.StatusBadRequest - } - return http.StatusInternalServerError -} - -func errorDecoder(r *http.Response) error { - var w errorWrapper - if err := json.NewDecoder(r.Body).Decode(&w); err != nil { - return err - } - return errors.New(w.Error) -} - -type errorWrapper struct { - Error string `json:"error"` -} - -// decodeHTTPSumRequest is a transport/http.DecodeRequestFunc that decodes a -// JSON-encoded sum request from the HTTP request body. Primarily useful in a -// server. -func decodeHTTPSumRequest(_ context.Context, r *http.Request) (interface{}, error) { - var req addendpoint.SumRequest - err := json.NewDecoder(r.Body).Decode(&req) - return req, err -} - -// decodeHTTPConcatRequest is a transport/http.DecodeRequestFunc that decodes a -// JSON-encoded concat request from the HTTP request body. Primarily useful in a -// server. -func decodeHTTPConcatRequest(_ context.Context, r *http.Request) (interface{}, error) { - var req addendpoint.ConcatRequest - err := json.NewDecoder(r.Body).Decode(&req) - return req, err -} - -// decodeHTTPSumResponse is a transport/http.DecodeResponseFunc that decodes a -// JSON-encoded sum response from the HTTP response body. If the response has a -// non-200 status code, we will interpret that as an error and attempt to decode -// the specific error message from the response body. Primarily useful in a -// client. -func decodeHTTPSumResponse(_ context.Context, r *http.Response) (interface{}, error) { - if r.StatusCode != http.StatusOK { - return nil, errors.New(r.Status) - } - var resp addendpoint.SumResponse - err := json.NewDecoder(r.Body).Decode(&resp) - return resp, err -} - -// decodeHTTPConcatResponse is a transport/http.DecodeResponseFunc that decodes -// a JSON-encoded concat response from the HTTP response body. If the response -// has a non-200 status code, we will interpret that as an error and attempt to -// decode the specific error message from the response body. Primarily useful in -// a client. -func decodeHTTPConcatResponse(_ context.Context, r *http.Response) (interface{}, error) { - if r.StatusCode != http.StatusOK { - return nil, errors.New(r.Status) - } - var resp addendpoint.ConcatResponse - err := json.NewDecoder(r.Body).Decode(&resp) - return resp, err -} - -// encodeHTTPGenericRequest is a transport/http.EncodeRequestFunc that -// JSON-encodes any request to the request body. Primarily useful in a client. -func encodeHTTPGenericRequest(_ context.Context, r *http.Request, request interface{}) error { - var buf bytes.Buffer - if err := json.NewEncoder(&buf).Encode(request); err != nil { - return err - } - r.Body = ioutil.NopCloser(&buf) - return nil -} - -// encodeHTTPGenericResponse is a transport/http.EncodeResponseFunc that encodes -// the response as JSON to the response writer. Primarily useful in a server. -func encodeHTTPGenericResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { - if f, ok := response.(addendpoint.Failer); ok && f.Failed() != nil { - errorEncoder(ctx, f.Failed(), w) - return nil - } - w.Header().Set("Content-Type", "application/json; charset=utf-8") - return json.NewEncoder(w).Encode(response) -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addtransport/thrift.go b/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addtransport/thrift.go deleted file mode 100644 index c6797ecb..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/pkg/addtransport/thrift.go +++ /dev/null @@ -1,119 +0,0 @@ -package addtransport - -import ( - "context" - "time" - - jujuratelimit "github.com/juju/ratelimit" - "github.com/sony/gobreaker" - - "github.com/go-kit/kit/circuitbreaker" - "github.com/go-kit/kit/endpoint" - "github.com/go-kit/kit/ratelimit" - - "github.com/go-kit/kit/examples/addsvc/pkg/addendpoint" - "github.com/go-kit/kit/examples/addsvc/pkg/addservice" - addthrift "github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc" -) - -type thriftServer struct { - ctx context.Context - endpoints addendpoint.Set -} - -// NewThriftServer makes a set of endpoints available as a Thrift service. -func NewThriftServer(endpoints addendpoint.Set) addthrift.AddService { - return &thriftServer{ - endpoints: endpoints, - } -} - -func (s *thriftServer) Sum(ctx context.Context, a int64, b int64) (*addthrift.SumReply, error) { - request := addendpoint.SumRequest{A: int(a), B: int(b)} - response, err := s.endpoints.SumEndpoint(ctx, request) - if err != nil { - return nil, err - } - resp := response.(addendpoint.SumResponse) - return &addthrift.SumReply{Value: int64(resp.V), Err: err2str(resp.Err)}, nil -} - -func (s *thriftServer) Concat(ctx context.Context, a string, b string) (*addthrift.ConcatReply, error) { - request := addendpoint.ConcatRequest{A: a, B: b} - response, err := s.endpoints.ConcatEndpoint(ctx, request) - if err != nil { - return nil, err - } - resp := response.(addendpoint.ConcatResponse) - return &addthrift.ConcatReply{Value: resp.V, Err: err2str(resp.Err)}, nil -} - -// NewThriftClient returns an AddService backed by a Thrift server described by -// the provided client. The caller is responsible for constructing the client, -// and eventually closing the underlying transport. We bake-in certain middlewares, -// implementing the client library pattern. -func NewThriftClient(client *addthrift.AddServiceClient) addservice.Service { - // We construct a single ratelimiter middleware, to limit the total outgoing - // QPS from this client to all methods on the remote instance. We also - // construct per-endpoint circuitbreaker middlewares to demonstrate how - // that's done, although they could easily be combined into a single breaker - // for the entire remote instance, too. - limiter := ratelimit.NewTokenBucketLimiter(jujuratelimit.NewBucketWithRate(100, 100)) - - // Each individual endpoint is an http/transport.Client (which implements - // endpoint.Endpoint) that gets wrapped with various middlewares. If you - // could rely on a consistent set of client behavior. - var sumEndpoint endpoint.Endpoint - { - sumEndpoint = MakeThriftSumEndpoint(client) - sumEndpoint = limiter(sumEndpoint) - sumEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{ - Name: "Sum", - Timeout: 30 * time.Second, - }))(sumEndpoint) - } - - // The Concat endpoint is the same thing, with slightly different - // middlewares to demonstrate how to specialize per-endpoint. - var concatEndpoint endpoint.Endpoint - { - concatEndpoint = MakeThriftConcatEndpoint(client) - concatEndpoint = limiter(concatEndpoint) - concatEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{ - Name: "Concat", - Timeout: 10 * time.Second, - }))(concatEndpoint) - } - - // Returning the endpoint.Set as a service.Service relies on the - // endpoint.Set implementing the Service methods. That's just a simple bit - // of glue code. - return addendpoint.Set{ - SumEndpoint: sumEndpoint, - ConcatEndpoint: concatEndpoint, - } -} - -// MakeThriftSumEndpoint returns an endpoint that invokes the passed Thrift client. -// Useful only in clients, and only until a proper transport/thrift.Client exists. -func MakeThriftSumEndpoint(client *addthrift.AddServiceClient) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(addendpoint.SumRequest) - reply, err := client.Sum(ctx, int64(req.A), int64(req.B)) - if err == addservice.ErrIntOverflow { - return nil, err // special case; see comment on ErrIntOverflow - } - return addendpoint.SumResponse{V: int(reply.Value), Err: err}, nil - } -} - -// MakeThriftConcatEndpoint returns an endpoint that invokes the passed Thrift -// client. Useful only in clients, and only until a proper -// transport/thrift.Client exists. -func MakeThriftConcatEndpoint(client *addthrift.AddServiceClient) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(addendpoint.ConcatRequest) - reply, err := client.Concat(ctx, req.A, req.B) - return addendpoint.ConcatResponse{V: reply.Value, Err: err}, nil - } -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/addsvc.thrift b/vendor/github.com/go-kit/kit/examples/addsvc/thrift/addsvc.thrift deleted file mode 100644 index e67ce1b2..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/addsvc.thrift +++ /dev/null @@ -1,14 +0,0 @@ -struct SumReply { - 1: i64 value - 2: string err -} - -struct ConcatReply { - 1: string value - 2: string err -} - -service AddService { - SumReply Sum(1: i64 a, 2: i64 b) - ConcatReply Concat(1: string a, 2: string b) -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/compile.sh b/vendor/github.com/go-kit/kit/examples/addsvc/thrift/compile.sh deleted file mode 100755 index 2ecce5b2..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/compile.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env sh - -# See also https://thrift.apache.org/tutorial/go - -thrift -r --gen "go:package_prefix=github.com/go-kit/kit/examples/addsvc/thrift/gen-go/,thrift_import=github.com/apache/thrift/lib/go/thrift" addsvc.thrift diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/GoUnusedProtection__.go b/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/GoUnusedProtection__.go deleted file mode 100644 index 88387e14..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/GoUnusedProtection__.go +++ /dev/null @@ -1,7 +0,0 @@ -// Autogenerated by Thrift Compiler (1.0.0-dev) -// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - -package addsvc - -var GoUnusedProtection__ int; - diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/add_service-remote/add_service-remote.go b/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/add_service-remote/add_service-remote.go deleted file mode 100755 index 2063763a..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/add_service-remote/add_service-remote.go +++ /dev/null @@ -1,159 +0,0 @@ -// Autogenerated by Thrift Compiler (1.0.0-dev) -// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - -package main - -import ( - "context" - "flag" - "fmt" - "math" - "net" - "net/url" - "os" - "strconv" - "strings" - "github.com/apache/thrift/lib/go/thrift" - "github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc" -) - - -func Usage() { - fmt.Fprintln(os.Stderr, "Usage of ", os.Args[0], " [-h host:port] [-u url] [-f[ramed]] function [arg1 [arg2...]]:") - flag.PrintDefaults() - fmt.Fprintln(os.Stderr, "\nFunctions:") - fmt.Fprintln(os.Stderr, " SumReply Sum(i64 a, i64 b)") - fmt.Fprintln(os.Stderr, " ConcatReply Concat(string a, string b)") - fmt.Fprintln(os.Stderr) - os.Exit(0) -} - -func main() { - flag.Usage = Usage - var host string - var port int - var protocol string - var urlString string - var framed bool - var useHttp bool - var parsedUrl url.URL - var trans thrift.TTransport - _ = strconv.Atoi - _ = math.Abs - flag.Usage = Usage - flag.StringVar(&host, "h", "localhost", "Specify host and port") - flag.IntVar(&port, "p", 9090, "Specify port") - flag.StringVar(&protocol, "P", "binary", "Specify the protocol (binary, compact, simplejson, json)") - flag.StringVar(&urlString, "u", "", "Specify the url") - flag.BoolVar(&framed, "framed", false, "Use framed transport") - flag.BoolVar(&useHttp, "http", false, "Use http") - flag.Parse() - - if len(urlString) > 0 { - parsedUrl, err := url.Parse(urlString) - if err != nil { - fmt.Fprintln(os.Stderr, "Error parsing URL: ", err) - flag.Usage() - } - host = parsedUrl.Host - useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == "http" - } else if useHttp { - _, err := url.Parse(fmt.Sprint("http://", host, ":", port)) - if err != nil { - fmt.Fprintln(os.Stderr, "Error parsing URL: ", err) - flag.Usage() - } - } - - cmd := flag.Arg(0) - var err error - if useHttp { - trans, err = thrift.NewTHttpClient(parsedUrl.String()) - } else { - portStr := fmt.Sprint(port) - if strings.Contains(host, ":") { - host, portStr, err = net.SplitHostPort(host) - if err != nil { - fmt.Fprintln(os.Stderr, "error with host:", err) - os.Exit(1) - } - } - trans, err = thrift.NewTSocket(net.JoinHostPort(host, portStr)) - if err != nil { - fmt.Fprintln(os.Stderr, "error resolving address:", err) - os.Exit(1) - } - if framed { - trans = thrift.NewTFramedTransport(trans) - } - } - if err != nil { - fmt.Fprintln(os.Stderr, "Error creating transport", err) - os.Exit(1) - } - defer trans.Close() - var protocolFactory thrift.TProtocolFactory - switch protocol { - case "compact": - protocolFactory = thrift.NewTCompactProtocolFactory() - break - case "simplejson": - protocolFactory = thrift.NewTSimpleJSONProtocolFactory() - break - case "json": - protocolFactory = thrift.NewTJSONProtocolFactory() - break - case "binary", "": - protocolFactory = thrift.NewTBinaryProtocolFactoryDefault() - break - default: - fmt.Fprintln(os.Stderr, "Invalid protocol specified: ", protocol) - Usage() - os.Exit(1) - } - client := addsvc.NewAddServiceClientFactory(trans, protocolFactory) - if err := trans.Open(); err != nil { - fmt.Fprintln(os.Stderr, "Error opening socket to ", host, ":", port, " ", err) - os.Exit(1) - } - - switch cmd { - case "Sum": - if flag.NArg() - 1 != 2 { - fmt.Fprintln(os.Stderr, "Sum requires 2 args") - flag.Usage() - } - argvalue0, err6 := (strconv.ParseInt(flag.Arg(1), 10, 64)) - if err6 != nil { - Usage() - return - } - value0 := argvalue0 - argvalue1, err7 := (strconv.ParseInt(flag.Arg(2), 10, 64)) - if err7 != nil { - Usage() - return - } - value1 := argvalue1 - fmt.Print(client.Sum(context.Background(), value0, value1)) - fmt.Print("\n") - break - case "Concat": - if flag.NArg() - 1 != 2 { - fmt.Fprintln(os.Stderr, "Concat requires 2 args") - flag.Usage() - } - argvalue0 := flag.Arg(1) - value0 := argvalue0 - argvalue1 := flag.Arg(2) - value1 := argvalue1 - fmt.Print(client.Concat(context.Background(), value0, value1)) - fmt.Print("\n") - break - case "": - Usage() - break - default: - fmt.Fprintln(os.Stderr, "Invalid function ", cmd) - } -} diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/addsvc-consts.go b/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/addsvc-consts.go deleted file mode 100644 index 3222f510..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/addsvc-consts.go +++ /dev/null @@ -1,24 +0,0 @@ -// Autogenerated by Thrift Compiler (1.0.0-dev) -// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - -package addsvc - -import ( - "bytes" - "reflect" - "context" - "fmt" - "github.com/apache/thrift/lib/go/thrift" -) - -// (needed to ensure safety because of naive import list construction.) -var _ = thrift.ZERO -var _ = fmt.Printf -var _ = context.Background -var _ = reflect.DeepEqual -var _ = bytes.Equal - - -func init() { -} - diff --git a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/addsvc.go b/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/addsvc.go deleted file mode 100644 index 4f695b93..00000000 --- a/vendor/github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc/addsvc.go +++ /dev/null @@ -1,1065 +0,0 @@ -// Autogenerated by Thrift Compiler (1.0.0-dev) -// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - -package addsvc - -import ( - "bytes" - "reflect" - "context" - "fmt" - "github.com/apache/thrift/lib/go/thrift" -) - -// (needed to ensure safety because of naive import list construction.) -var _ = thrift.ZERO -var _ = fmt.Printf -var _ = context.Background -var _ = reflect.DeepEqual -var _ = bytes.Equal - -// Attributes: -// - Value -// - Err -type SumReply struct { - Value int64 `thrift:"value,1" db:"value" json:"value"` - Err string `thrift:"err,2" db:"err" json:"err"` -} - -func NewSumReply() *SumReply { - return &SumReply{} -} - - -func (p *SumReply) GetValue() int64 { - return p.Value -} - -func (p *SumReply) GetErr() string { - return p.Err -} -func (p *SumReply) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { break; } - switch fieldId { - case 1: - if fieldTypeId == thrift.I64 { - if err := p.ReadField1(iprot); err != nil { - return err - } - } else { - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - case 2: - if fieldTypeId == thrift.STRING { - if err := p.ReadField2(iprot); err != nil { - return err - } - } else { - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *SumReply) ReadField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 1: ", err) -} else { - p.Value = v -} - return nil -} - -func (p *SumReply) ReadField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) -} else { - p.Err = v -} - return nil -} - -func (p *SumReply) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("SumReply"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) } - if p != nil { - if err := p.writeField1(oprot); err != nil { return err } - if err := p.writeField2(oprot); err != nil { return err } - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) } - return nil -} - -func (p *SumReply) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("value", thrift.I64, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:value: ", p), err) } - if err := oprot.WriteI64(int64(p.Value)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.value (1) field write error: ", p), err) } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:value: ", p), err) } - return err -} - -func (p *SumReply) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("err", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:err: ", p), err) } - if err := oprot.WriteString(string(p.Err)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.err (2) field write error: ", p), err) } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:err: ", p), err) } - return err -} - -func (p *SumReply) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("SumReply(%+v)", *p) -} - -// Attributes: -// - Value -// - Err -type ConcatReply struct { - Value string `thrift:"value,1" db:"value" json:"value"` - Err string `thrift:"err,2" db:"err" json:"err"` -} - -func NewConcatReply() *ConcatReply { - return &ConcatReply{} -} - - -func (p *ConcatReply) GetValue() string { - return p.Value -} - -func (p *ConcatReply) GetErr() string { - return p.Err -} -func (p *ConcatReply) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { break; } - switch fieldId { - case 1: - if fieldTypeId == thrift.STRING { - if err := p.ReadField1(iprot); err != nil { - return err - } - } else { - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - case 2: - if fieldTypeId == thrift.STRING { - if err := p.ReadField2(iprot); err != nil { - return err - } - } else { - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *ConcatReply) ReadField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) -} else { - p.Value = v -} - return nil -} - -func (p *ConcatReply) ReadField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) -} else { - p.Err = v -} - return nil -} - -func (p *ConcatReply) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("ConcatReply"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) } - if p != nil { - if err := p.writeField1(oprot); err != nil { return err } - if err := p.writeField2(oprot); err != nil { return err } - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) } - return nil -} - -func (p *ConcatReply) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("value", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:value: ", p), err) } - if err := oprot.WriteString(string(p.Value)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.value (1) field write error: ", p), err) } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:value: ", p), err) } - return err -} - -func (p *ConcatReply) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("err", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:err: ", p), err) } - if err := oprot.WriteString(string(p.Err)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.err (2) field write error: ", p), err) } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:err: ", p), err) } - return err -} - -func (p *ConcatReply) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("ConcatReply(%+v)", *p) -} - -type AddService interface { - // Parameters: - // - A - // - B - Sum(ctx context.Context, a int64, b int64) (r *SumReply, err error) - // Parameters: - // - A - // - B - Concat(ctx context.Context, a string, b string) (r *ConcatReply, err error) -} - -type AddServiceClient struct { - Transport thrift.TTransport - ProtocolFactory thrift.TProtocolFactory - InputProtocol thrift.TProtocol - OutputProtocol thrift.TProtocol - SeqId int32 -} - -func NewAddServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *AddServiceClient { - return &AddServiceClient{Transport: t, - ProtocolFactory: f, - InputProtocol: f.GetProtocol(t), - OutputProtocol: f.GetProtocol(t), - SeqId: 0, - } -} - -func NewAddServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *AddServiceClient { - return &AddServiceClient{Transport: t, - ProtocolFactory: nil, - InputProtocol: iprot, - OutputProtocol: oprot, - SeqId: 0, - } -} - -// Parameters: -// - A -// - B -func (p *AddServiceClient) Sum(ctx context.Context, a int64, b int64) (r *SumReply, err error) { - if err = p.sendSum(a, b); err != nil { return } - return p.recvSum() -} - -func (p *AddServiceClient) sendSum(a int64, b int64)(err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("Sum", thrift.CALL, p.SeqId); err != nil { - return - } - args := AddServiceSumArgs{ - A : a, - B : b, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - - -func (p *AddServiceClient) recvSum() (value *SumReply, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "Sum" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "Sum failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "Sum failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error0 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error1 error - error1, err = error0.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error1 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "Sum failed: invalid message type") - return - } - result := AddServiceSumResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - -// Parameters: -// - A -// - B -func (p *AddServiceClient) Concat(ctx context.Context, a string, b string) (r *ConcatReply, err error) { - if err = p.sendConcat(a, b); err != nil { return } - return p.recvConcat() -} - -func (p *AddServiceClient) sendConcat(a string, b string)(err error) { - oprot := p.OutputProtocol - if oprot == nil { - oprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.OutputProtocol = oprot - } - p.SeqId++ - if err = oprot.WriteMessageBegin("Concat", thrift.CALL, p.SeqId); err != nil { - return - } - args := AddServiceConcatArgs{ - A : a, - B : b, - } - if err = args.Write(oprot); err != nil { - return - } - if err = oprot.WriteMessageEnd(); err != nil { - return - } - return oprot.Flush() -} - - -func (p *AddServiceClient) recvConcat() (value *ConcatReply, err error) { - iprot := p.InputProtocol - if iprot == nil { - iprot = p.ProtocolFactory.GetProtocol(p.Transport) - p.InputProtocol = iprot - } - method, mTypeId, seqId, err := iprot.ReadMessageBegin() - if err != nil { - return - } - if method != "Concat" { - err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "Concat failed: wrong method name") - return - } - if p.SeqId != seqId { - err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "Concat failed: out of sequence response") - return - } - if mTypeId == thrift.EXCEPTION { - error2 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception") - var error3 error - error3, err = error2.Read(iprot) - if err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - err = error3 - return - } - if mTypeId != thrift.REPLY { - err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "Concat failed: invalid message type") - return - } - result := AddServiceConcatResult{} - if err = result.Read(iprot); err != nil { - return - } - if err = iprot.ReadMessageEnd(); err != nil { - return - } - value = result.GetSuccess() - return -} - - -type AddServiceProcessor struct { - processorMap map[string]thrift.TProcessorFunction - handler AddService -} - -func (p *AddServiceProcessor) AddToProcessorMap(key string, processor thrift.TProcessorFunction) { - p.processorMap[key] = processor -} - -func (p *AddServiceProcessor) GetProcessorFunction(key string) (processor thrift.TProcessorFunction, ok bool) { - processor, ok = p.processorMap[key] - return processor, ok -} - -func (p *AddServiceProcessor) ProcessorMap() map[string]thrift.TProcessorFunction { - return p.processorMap -} - -func NewAddServiceProcessor(handler AddService) *AddServiceProcessor { - - self4 := &AddServiceProcessor{handler:handler, processorMap:make(map[string]thrift.TProcessorFunction)} - self4.processorMap["Sum"] = &addServiceProcessorSum{handler:handler} - self4.processorMap["Concat"] = &addServiceProcessorConcat{handler:handler} -return self4 -} - -func (p *AddServiceProcessor) Process(ctx context.Context, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - name, _, seqId, err := iprot.ReadMessageBegin() - if err != nil { return false, err } - if processor, ok := p.GetProcessorFunction(name); ok { - return processor.Process(ctx, seqId, iprot, oprot) - } - iprot.Skip(thrift.STRUCT) - iprot.ReadMessageEnd() - x5 := thrift.NewTApplicationException(thrift.UNKNOWN_METHOD, "Unknown function " + name) - oprot.WriteMessageBegin(name, thrift.EXCEPTION, seqId) - x5.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, x5 - -} - -type addServiceProcessorSum struct { - handler AddService -} - -func (p *addServiceProcessorSum) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AddServiceSumArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("Sum", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AddServiceSumResult{} -var retval *SumReply - var err2 error - if retval, err2 = p.handler.Sum(ctx, args.A, args.B); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing Sum: " + err2.Error()) - oprot.WriteMessageBegin("Sum", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval -} - if err2 = oprot.WriteMessageBegin("Sum", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - -type addServiceProcessorConcat struct { - handler AddService -} - -func (p *addServiceProcessorConcat) Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) { - args := AddServiceConcatArgs{} - if err = args.Read(iprot); err != nil { - iprot.ReadMessageEnd() - x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error()) - oprot.WriteMessageBegin("Concat", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return false, err - } - - iprot.ReadMessageEnd() - result := AddServiceConcatResult{} -var retval *ConcatReply - var err2 error - if retval, err2 = p.handler.Concat(ctx, args.A, args.B); err2 != nil { - x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing Concat: " + err2.Error()) - oprot.WriteMessageBegin("Concat", thrift.EXCEPTION, seqId) - x.Write(oprot) - oprot.WriteMessageEnd() - oprot.Flush() - return true, err2 - } else { - result.Success = retval -} - if err2 = oprot.WriteMessageBegin("Concat", thrift.REPLY, seqId); err2 != nil { - err = err2 - } - if err2 = result.Write(oprot); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil { - err = err2 - } - if err2 = oprot.Flush(); err == nil && err2 != nil { - err = err2 - } - if err != nil { - return - } - return true, err -} - - -// HELPER FUNCTIONS AND STRUCTURES - -// Attributes: -// - A -// - B -type AddServiceSumArgs struct { - A int64 `thrift:"a,1" db:"a" json:"a"` - B int64 `thrift:"b,2" db:"b" json:"b"` -} - -func NewAddServiceSumArgs() *AddServiceSumArgs { - return &AddServiceSumArgs{} -} - - -func (p *AddServiceSumArgs) GetA() int64 { - return p.A -} - -func (p *AddServiceSumArgs) GetB() int64 { - return p.B -} -func (p *AddServiceSumArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { break; } - switch fieldId { - case 1: - if fieldTypeId == thrift.I64 { - if err := p.ReadField1(iprot); err != nil { - return err - } - } else { - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - case 2: - if fieldTypeId == thrift.I64 { - if err := p.ReadField2(iprot); err != nil { - return err - } - } else { - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AddServiceSumArgs) ReadField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 1: ", err) -} else { - p.A = v -} - return nil -} - -func (p *AddServiceSumArgs) ReadField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadI64(); err != nil { - return thrift.PrependError("error reading field 2: ", err) -} else { - p.B = v -} - return nil -} - -func (p *AddServiceSumArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Sum_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) } - if p != nil { - if err := p.writeField1(oprot); err != nil { return err } - if err := p.writeField2(oprot); err != nil { return err } - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) } - return nil -} - -func (p *AddServiceSumArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("a", thrift.I64, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:a: ", p), err) } - if err := oprot.WriteI64(int64(p.A)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.a (1) field write error: ", p), err) } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:a: ", p), err) } - return err -} - -func (p *AddServiceSumArgs) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("b", thrift.I64, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:b: ", p), err) } - if err := oprot.WriteI64(int64(p.B)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.b (2) field write error: ", p), err) } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:b: ", p), err) } - return err -} - -func (p *AddServiceSumArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AddServiceSumArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AddServiceSumResult struct { - Success *SumReply `thrift:"success,0" db:"success" json:"success,omitempty"` -} - -func NewAddServiceSumResult() *AddServiceSumResult { - return &AddServiceSumResult{} -} - -var AddServiceSumResult_Success_DEFAULT *SumReply -func (p *AddServiceSumResult) GetSuccess() *SumReply { - if !p.IsSetSuccess() { - return AddServiceSumResult_Success_DEFAULT - } -return p.Success -} -func (p *AddServiceSumResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AddServiceSumResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { break; } - switch fieldId { - case 0: - if fieldTypeId == thrift.STRUCT { - if err := p.ReadField0(iprot); err != nil { - return err - } - } else { - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AddServiceSumResult) ReadField0(iprot thrift.TProtocol) error { - p.Success = &SumReply{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AddServiceSumResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Sum_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) } - if p != nil { - if err := p.writeField0(oprot); err != nil { return err } - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) } - return nil -} - -func (p *AddServiceSumResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) } - } - return err -} - -func (p *AddServiceSumResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AddServiceSumResult(%+v)", *p) -} - -// Attributes: -// - A -// - B -type AddServiceConcatArgs struct { - A string `thrift:"a,1" db:"a" json:"a"` - B string `thrift:"b,2" db:"b" json:"b"` -} - -func NewAddServiceConcatArgs() *AddServiceConcatArgs { - return &AddServiceConcatArgs{} -} - - -func (p *AddServiceConcatArgs) GetA() string { - return p.A -} - -func (p *AddServiceConcatArgs) GetB() string { - return p.B -} -func (p *AddServiceConcatArgs) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { break; } - switch fieldId { - case 1: - if fieldTypeId == thrift.STRING { - if err := p.ReadField1(iprot); err != nil { - return err - } - } else { - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - case 2: - if fieldTypeId == thrift.STRING { - if err := p.ReadField2(iprot); err != nil { - return err - } - } else { - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AddServiceConcatArgs) ReadField1(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 1: ", err) -} else { - p.A = v -} - return nil -} - -func (p *AddServiceConcatArgs) ReadField2(iprot thrift.TProtocol) error { - if v, err := iprot.ReadString(); err != nil { - return thrift.PrependError("error reading field 2: ", err) -} else { - p.B = v -} - return nil -} - -func (p *AddServiceConcatArgs) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Concat_args"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) } - if p != nil { - if err := p.writeField1(oprot); err != nil { return err } - if err := p.writeField2(oprot); err != nil { return err } - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) } - return nil -} - -func (p *AddServiceConcatArgs) writeField1(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("a", thrift.STRING, 1); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:a: ", p), err) } - if err := oprot.WriteString(string(p.A)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.a (1) field write error: ", p), err) } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 1:a: ", p), err) } - return err -} - -func (p *AddServiceConcatArgs) writeField2(oprot thrift.TProtocol) (err error) { - if err := oprot.WriteFieldBegin("b", thrift.STRING, 2); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:b: ", p), err) } - if err := oprot.WriteString(string(p.B)); err != nil { - return thrift.PrependError(fmt.Sprintf("%T.b (2) field write error: ", p), err) } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 2:b: ", p), err) } - return err -} - -func (p *AddServiceConcatArgs) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AddServiceConcatArgs(%+v)", *p) -} - -// Attributes: -// - Success -type AddServiceConcatResult struct { - Success *ConcatReply `thrift:"success,0" db:"success" json:"success,omitempty"` -} - -func NewAddServiceConcatResult() *AddServiceConcatResult { - return &AddServiceConcatResult{} -} - -var AddServiceConcatResult_Success_DEFAULT *ConcatReply -func (p *AddServiceConcatResult) GetSuccess() *ConcatReply { - if !p.IsSetSuccess() { - return AddServiceConcatResult_Success_DEFAULT - } -return p.Success -} -func (p *AddServiceConcatResult) IsSetSuccess() bool { - return p.Success != nil -} - -func (p *AddServiceConcatResult) Read(iprot thrift.TProtocol) error { - if _, err := iprot.ReadStructBegin(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err) - } - - - for { - _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin() - if err != nil { - return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err) - } - if fieldTypeId == thrift.STOP { break; } - switch fieldId { - case 0: - if fieldTypeId == thrift.STRUCT { - if err := p.ReadField0(iprot); err != nil { - return err - } - } else { - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - default: - if err := iprot.Skip(fieldTypeId); err != nil { - return err - } - } - if err := iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err) - } - return nil -} - -func (p *AddServiceConcatResult) ReadField0(iprot thrift.TProtocol) error { - p.Success = &ConcatReply{} - if err := p.Success.Read(iprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err) - } - return nil -} - -func (p *AddServiceConcatResult) Write(oprot thrift.TProtocol) error { - if err := oprot.WriteStructBegin("Concat_result"); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err) } - if p != nil { - if err := p.writeField0(oprot); err != nil { return err } - } - if err := oprot.WriteFieldStop(); err != nil { - return thrift.PrependError("write field stop error: ", err) } - if err := oprot.WriteStructEnd(); err != nil { - return thrift.PrependError("write struct stop error: ", err) } - return nil -} - -func (p *AddServiceConcatResult) writeField0(oprot thrift.TProtocol) (err error) { - if p.IsSetSuccess() { - if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err) } - if err := p.Success.Write(oprot); err != nil { - return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err) - } - if err := oprot.WriteFieldEnd(); err != nil { - return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err) } - } - return err -} - -func (p *AddServiceConcatResult) String() string { - if p == nil { - return "" - } - return fmt.Sprintf("AddServiceConcatResult(%+v)", *p) -} - - diff --git a/vendor/github.com/go-kit/kit/examples/apigateway/main.go b/vendor/github.com/go-kit/kit/examples/apigateway/main.go deleted file mode 100644 index 3b4cd675..00000000 --- a/vendor/github.com/go-kit/kit/examples/apigateway/main.go +++ /dev/null @@ -1,285 +0,0 @@ -package main - -import ( - "bytes" - "context" - "encoding/json" - "flag" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - "os/signal" - "strings" - "syscall" - "time" - - consulsd "github.com/go-kit/kit/sd/consul" - "github.com/gorilla/mux" - "github.com/hashicorp/consul/api" - stdopentracing "github.com/opentracing/opentracing-go" - "google.golang.org/grpc" - - "github.com/go-kit/kit/endpoint" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/sd" - "github.com/go-kit/kit/sd/lb" - httptransport "github.com/go-kit/kit/transport/http" - - "github.com/go-kit/kit/examples/addsvc/pkg/addendpoint" - "github.com/go-kit/kit/examples/addsvc/pkg/addservice" - "github.com/go-kit/kit/examples/addsvc/pkg/addtransport" -) - -func main() { - var ( - httpAddr = flag.String("http.addr", ":8000", "Address for HTTP (JSON) server") - consulAddr = flag.String("consul.addr", "", "Consul agent address") - retryMax = flag.Int("retry.max", 3, "per-request retries to different instances") - retryTimeout = flag.Duration("retry.timeout", 500*time.Millisecond, "per-request timeout, including retries") - ) - flag.Parse() - - // Logging domain. - var logger log.Logger - { - logger = log.NewLogfmtLogger(os.Stderr) - logger = log.With(logger, "ts", log.DefaultTimestampUTC) - logger = log.With(logger, "caller", log.DefaultCaller) - } - - // Service discovery domain. In this example we use Consul. - var client consulsd.Client - { - consulConfig := api.DefaultConfig() - if len(*consulAddr) > 0 { - consulConfig.Address = *consulAddr - } - consulClient, err := api.NewClient(consulConfig) - if err != nil { - logger.Log("err", err) - os.Exit(1) - } - client = consulsd.NewClient(consulClient) - } - - // Transport domain. - tracer := stdopentracing.GlobalTracer() // no-op - ctx := context.Background() - r := mux.NewRouter() - - // Now we begin installing the routes. Each route corresponds to a single - // method: sum, concat, uppercase, and count. - - // addsvc routes. - { - // Each method gets constructed with a factory. Factories take an - // instance string, and return a specific endpoint. In the factory we - // dial the instance string we get from Consul, and then leverage an - // addsvc client package to construct a complete service. We can then - // leverage the addsvc.Make{Sum,Concat}Endpoint constructors to convert - // the complete service to specific endpoint. - var ( - tags = []string{} - passingOnly = true - endpoints = addendpoint.Set{} - instancer = consulsd.NewInstancer(client, logger, "addsvc", tags, passingOnly) - ) - { - factory := addsvcFactory(addendpoint.MakeSumEndpoint, tracer, logger) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(*retryMax, *retryTimeout, balancer) - endpoints.SumEndpoint = retry - } - { - factory := addsvcFactory(addendpoint.MakeConcatEndpoint, tracer, logger) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(*retryMax, *retryTimeout, balancer) - endpoints.ConcatEndpoint = retry - } - - // Here we leverage the fact that addsvc comes with a constructor for an - // HTTP handler, and just install it under a particular path prefix in - // our router. - - r.PathPrefix("/addsvc").Handler(http.StripPrefix("/addsvc", addtransport.NewHTTPHandler(endpoints, tracer, logger))) - } - - // stringsvc routes. - { - // addsvc had lots of nice importable Go packages we could leverage. - // With stringsvc we are not so fortunate, it just has some endpoints - // that we assume will exist. So we have to write that logic here. This - // is by design, so you can see two totally different methods of - // proxying to a remote service. - - var ( - tags = []string{} - passingOnly = true - uppercase endpoint.Endpoint - count endpoint.Endpoint - instancer = consulsd.NewInstancer(client, logger, "stringsvc", tags, passingOnly) - ) - { - factory := stringsvcFactory(ctx, "GET", "/uppercase") - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(*retryMax, *retryTimeout, balancer) - uppercase = retry - } - { - factory := stringsvcFactory(ctx, "GET", "/count") - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(*retryMax, *retryTimeout, balancer) - count = retry - } - - // We can use the transport/http.Server to act as our handler, all we - // have to do provide it with the encode and decode functions for our - // stringsvc methods. - - r.Handle("/stringsvc/uppercase", httptransport.NewServer(uppercase, decodeUppercaseRequest, encodeJSONResponse)) - r.Handle("/stringsvc/count", httptransport.NewServer(count, decodeCountRequest, encodeJSONResponse)) - } - - // Interrupt handler. - errc := make(chan error) - go func() { - c := make(chan os.Signal) - signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) - errc <- fmt.Errorf("%s", <-c) - }() - - // HTTP transport. - go func() { - logger.Log("transport", "HTTP", "addr", *httpAddr) - errc <- http.ListenAndServe(*httpAddr, r) - }() - - // Run! - logger.Log("exit", <-errc) -} - -func addsvcFactory(makeEndpoint func(addservice.Service) endpoint.Endpoint, tracer stdopentracing.Tracer, logger log.Logger) sd.Factory { - return func(instance string) (endpoint.Endpoint, io.Closer, error) { - // We could just as easily use the HTTP or Thrift client package to make - // the connection to addsvc. We've chosen gRPC arbitrarily. Note that - // the transport is an implementation detail: it doesn't leak out of - // this function. Nice! - - conn, err := grpc.Dial(instance, grpc.WithInsecure()) - if err != nil { - return nil, nil, err - } - service := addtransport.NewGRPCClient(conn, tracer, logger) - endpoint := makeEndpoint(service) - - // Notice that the addsvc gRPC client converts the connection to a - // complete addsvc, and we just throw away everything except the method - // we're interested in. A smarter factory would mux multiple methods - // over the same connection. But that would require more work to manage - // the returned io.Closer, e.g. reference counting. Since this is for - // the purposes of demonstration, we'll just keep it simple. - - return endpoint, conn, nil - } -} - -func stringsvcFactory(ctx context.Context, method, path string) sd.Factory { - return func(instance string) (endpoint.Endpoint, io.Closer, error) { - if !strings.HasPrefix(instance, "http") { - instance = "http://" + instance - } - tgt, err := url.Parse(instance) - if err != nil { - return nil, nil, err - } - tgt.Path = path - - // Since stringsvc doesn't have any kind of package we can import, or - // any formal spec, we are forced to just assert where the endpoints - // live, and write our own code to encode and decode requests and - // responses. Ideally, if you write the service, you will want to - // provide stronger guarantees to your clients. - - var ( - enc httptransport.EncodeRequestFunc - dec httptransport.DecodeResponseFunc - ) - switch path { - case "/uppercase": - enc, dec = encodeJSONRequest, decodeUppercaseResponse - case "/count": - enc, dec = encodeJSONRequest, decodeCountResponse - default: - return nil, nil, fmt.Errorf("unknown stringsvc path %q", path) - } - - return httptransport.NewClient(method, tgt, enc, dec).Endpoint(), nil, nil - } -} - -func encodeJSONRequest(_ context.Context, req *http.Request, request interface{}) error { - // Both uppercase and count requests are encoded in the same way: - // simple JSON serialization to the request body. - var buf bytes.Buffer - if err := json.NewEncoder(&buf).Encode(request); err != nil { - return err - } - req.Body = ioutil.NopCloser(&buf) - return nil -} - -func encodeJSONResponse(_ context.Context, w http.ResponseWriter, response interface{}) error { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - return json.NewEncoder(w).Encode(response) -} - -// I've just copied these functions from stringsvc3/transport.go, inlining the -// struct definitions. - -func decodeUppercaseResponse(ctx context.Context, resp *http.Response) (interface{}, error) { - var response struct { - V string `json:"v"` - Err string `json:"err,omitempty"` - } - if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { - return nil, err - } - return response, nil -} - -func decodeCountResponse(ctx context.Context, resp *http.Response) (interface{}, error) { - var response struct { - V int `json:"v"` - } - if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { - return nil, err - } - return response, nil -} - -func decodeUppercaseRequest(ctx context.Context, req *http.Request) (interface{}, error) { - var request struct { - S string `json:"s"` - } - if err := json.NewDecoder(req.Body).Decode(&request); err != nil { - return nil, err - } - return request, nil -} - -func decodeCountRequest(ctx context.Context, req *http.Request) (interface{}, error) { - var request struct { - S string `json:"s"` - } - if err := json.NewDecoder(req.Body).Decode(&request); err != nil { - return nil, err - } - return request, nil -} diff --git a/vendor/github.com/go-kit/kit/examples/profilesvc/README.md b/vendor/github.com/go-kit/kit/examples/profilesvc/README.md deleted file mode 100644 index 68c41252..00000000 --- a/vendor/github.com/go-kit/kit/examples/profilesvc/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# profilesvc - -This example demonstrates how to use Go kit to implement a REST-y HTTP service. -It leverages the excellent [gorilla mux package](https://github.com/gorilla/mux) for routing. diff --git a/vendor/github.com/go-kit/kit/examples/profilesvc/client/client.go b/vendor/github.com/go-kit/kit/examples/profilesvc/client/client.go deleted file mode 100644 index 03c1dc7a..00000000 --- a/vendor/github.com/go-kit/kit/examples/profilesvc/client/client.go +++ /dev/null @@ -1,121 +0,0 @@ -// Package client provides a profilesvc client based on a predefined Consul -// service name and relevant tags. Users must only provide the address of a -// Consul server. -package client - -import ( - "io" - "time" - - consulapi "github.com/hashicorp/consul/api" - - "github.com/go-kit/kit/endpoint" - "github.com/go-kit/kit/examples/profilesvc" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/sd" - "github.com/go-kit/kit/sd/consul" - "github.com/go-kit/kit/sd/lb" -) - -// New returns a service that's load-balanced over instances of profilesvc found -// in the provided Consul server. The mechanism of looking up profilesvc -// instances in Consul is hard-coded into the client. -func New(consulAddr string, logger log.Logger) (profilesvc.Service, error) { - apiclient, err := consulapi.NewClient(&consulapi.Config{ - Address: consulAddr, - }) - if err != nil { - return nil, err - } - - // As the implementer of profilesvc, we declare and enforce these - // parameters for all of the profilesvc consumers. - var ( - consulService = "profilesvc" - consulTags = []string{"prod"} - passingOnly = true - retryMax = 3 - retryTimeout = 500 * time.Millisecond - ) - - var ( - sdclient = consul.NewClient(apiclient) - instancer = consul.NewInstancer(sdclient, logger, consulService, consulTags, passingOnly) - endpoints profilesvc.Endpoints - ) - { - factory := factoryFor(profilesvc.MakePostProfileEndpoint) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(retryMax, retryTimeout, balancer) - endpoints.PostProfileEndpoint = retry - } - { - factory := factoryFor(profilesvc.MakeGetProfileEndpoint) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(retryMax, retryTimeout, balancer) - endpoints.GetProfileEndpoint = retry - } - { - factory := factoryFor(profilesvc.MakePutProfileEndpoint) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(retryMax, retryTimeout, balancer) - endpoints.PutProfileEndpoint = retry - } - { - factory := factoryFor(profilesvc.MakePatchProfileEndpoint) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(retryMax, retryTimeout, balancer) - endpoints.PatchProfileEndpoint = retry - } - { - factory := factoryFor(profilesvc.MakeDeleteProfileEndpoint) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(retryMax, retryTimeout, balancer) - endpoints.DeleteProfileEndpoint = retry - } - { - factory := factoryFor(profilesvc.MakeGetAddressesEndpoint) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(retryMax, retryTimeout, balancer) - endpoints.GetAddressesEndpoint = retry - } - { - factory := factoryFor(profilesvc.MakeGetAddressEndpoint) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(retryMax, retryTimeout, balancer) - endpoints.GetAddressEndpoint = retry - } - { - factory := factoryFor(profilesvc.MakePostAddressEndpoint) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(retryMax, retryTimeout, balancer) - endpoints.PostAddressEndpoint = retry - } - { - factory := factoryFor(profilesvc.MakeDeleteAddressEndpoint) - endpointer := sd.NewEndpointer(instancer, factory, logger) - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(retryMax, retryTimeout, balancer) - endpoints.DeleteAddressEndpoint = retry - } - - return endpoints, nil -} - -func factoryFor(makeEndpoint func(profilesvc.Service) endpoint.Endpoint) sd.Factory { - return func(instance string) (endpoint.Endpoint, io.Closer, error) { - service, err := profilesvc.MakeClientEndpoints(instance) - if err != nil { - return nil, nil, err - } - return makeEndpoint(service), nil, nil - } -} diff --git a/vendor/github.com/go-kit/kit/examples/profilesvc/cmd/profilesvc/main.go b/vendor/github.com/go-kit/kit/examples/profilesvc/cmd/profilesvc/main.go deleted file mode 100644 index fda75295..00000000 --- a/vendor/github.com/go-kit/kit/examples/profilesvc/cmd/profilesvc/main.go +++ /dev/null @@ -1,52 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "net/http" - "os" - "os/signal" - "syscall" - - "github.com/go-kit/kit/examples/profilesvc" - "github.com/go-kit/kit/log" -) - -func main() { - var ( - httpAddr = flag.String("http.addr", ":8080", "HTTP listen address") - ) - flag.Parse() - - var logger log.Logger - { - logger = log.NewLogfmtLogger(os.Stderr) - logger = log.With(logger, "ts", log.DefaultTimestampUTC) - logger = log.With(logger, "caller", log.DefaultCaller) - } - - var s profilesvc.Service - { - s = profilesvc.NewInmemService() - s = profilesvc.LoggingMiddleware(logger)(s) - } - - var h http.Handler - { - h = profilesvc.MakeHTTPHandler(s, log.With(logger, "component", "HTTP")) - } - - errs := make(chan error) - go func() { - c := make(chan os.Signal) - signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) - errs <- fmt.Errorf("%s", <-c) - }() - - go func() { - logger.Log("transport", "HTTP", "addr", *httpAddr) - errs <- http.ListenAndServe(*httpAddr, h) - }() - - logger.Log("exit", <-errs) -} diff --git a/vendor/github.com/go-kit/kit/examples/profilesvc/endpoints.go b/vendor/github.com/go-kit/kit/examples/profilesvc/endpoints.go deleted file mode 100644 index 3da29b4a..00000000 --- a/vendor/github.com/go-kit/kit/examples/profilesvc/endpoints.go +++ /dev/null @@ -1,387 +0,0 @@ -package profilesvc - -import ( - "context" - "net/url" - "strings" - - "github.com/go-kit/kit/endpoint" - httptransport "github.com/go-kit/kit/transport/http" -) - -// Endpoints collects all of the endpoints that compose a profile service. It's -// meant to be used as a helper struct, to collect all of the endpoints into a -// single parameter. -// -// In a server, it's useful for functions that need to operate on a per-endpoint -// basis. For example, you might pass an Endpoints to a function that produces -// an http.Handler, with each method (endpoint) wired up to a specific path. (It -// is probably a mistake in design to invoke the Service methods on the -// Endpoints struct in a server.) -// -// In a client, it's useful to collect individually constructed endpoints into a -// single type that implements the Service interface. For example, you might -// construct individual endpoints using transport/http.NewClient, combine them -// into an Endpoints, and return it to the caller as a Service. -type Endpoints struct { - PostProfileEndpoint endpoint.Endpoint - GetProfileEndpoint endpoint.Endpoint - PutProfileEndpoint endpoint.Endpoint - PatchProfileEndpoint endpoint.Endpoint - DeleteProfileEndpoint endpoint.Endpoint - GetAddressesEndpoint endpoint.Endpoint - GetAddressEndpoint endpoint.Endpoint - PostAddressEndpoint endpoint.Endpoint - DeleteAddressEndpoint endpoint.Endpoint -} - -// MakeServerEndpoints returns an Endpoints struct where each endpoint invokes -// the corresponding method on the provided service. Useful in a profilesvc -// server. -func MakeServerEndpoints(s Service) Endpoints { - return Endpoints{ - PostProfileEndpoint: MakePostProfileEndpoint(s), - GetProfileEndpoint: MakeGetProfileEndpoint(s), - PutProfileEndpoint: MakePutProfileEndpoint(s), - PatchProfileEndpoint: MakePatchProfileEndpoint(s), - DeleteProfileEndpoint: MakeDeleteProfileEndpoint(s), - GetAddressesEndpoint: MakeGetAddressesEndpoint(s), - GetAddressEndpoint: MakeGetAddressEndpoint(s), - PostAddressEndpoint: MakePostAddressEndpoint(s), - DeleteAddressEndpoint: MakeDeleteAddressEndpoint(s), - } -} - -// MakeClientEndpoints returns an Endpoints struct where each endpoint invokes -// the corresponding method on the remote instance, via a transport/http.Client. -// Useful in a profilesvc client. -func MakeClientEndpoints(instance string) (Endpoints, error) { - if !strings.HasPrefix(instance, "http") { - instance = "http://" + instance - } - tgt, err := url.Parse(instance) - if err != nil { - return Endpoints{}, err - } - tgt.Path = "" - - options := []httptransport.ClientOption{} - - // Note that the request encoders need to modify the request URL, changing - // the path and method. That's fine: we simply need to provide specific - // encoders for each endpoint. - - return Endpoints{ - PostProfileEndpoint: httptransport.NewClient("POST", tgt, encodePostProfileRequest, decodePostProfileResponse, options...).Endpoint(), - GetProfileEndpoint: httptransport.NewClient("GET", tgt, encodeGetProfileRequest, decodeGetProfileResponse, options...).Endpoint(), - PutProfileEndpoint: httptransport.NewClient("PUT", tgt, encodePutProfileRequest, decodePutProfileResponse, options...).Endpoint(), - PatchProfileEndpoint: httptransport.NewClient("PATCH", tgt, encodePatchProfileRequest, decodePatchProfileResponse, options...).Endpoint(), - DeleteProfileEndpoint: httptransport.NewClient("DELETE", tgt, encodeDeleteProfileRequest, decodeDeleteProfileResponse, options...).Endpoint(), - GetAddressesEndpoint: httptransport.NewClient("GET", tgt, encodeGetAddressesRequest, decodeGetAddressesResponse, options...).Endpoint(), - GetAddressEndpoint: httptransport.NewClient("GET", tgt, encodeGetAddressRequest, decodeGetAddressResponse, options...).Endpoint(), - PostAddressEndpoint: httptransport.NewClient("POST", tgt, encodePostAddressRequest, decodePostAddressResponse, options...).Endpoint(), - DeleteAddressEndpoint: httptransport.NewClient("DELETE", tgt, encodeDeleteAddressRequest, decodeDeleteAddressResponse, options...).Endpoint(), - }, nil -} - -// PostProfile implements Service. Primarily useful in a client. -func (e Endpoints) PostProfile(ctx context.Context, p Profile) error { - request := postProfileRequest{Profile: p} - response, err := e.PostProfileEndpoint(ctx, request) - if err != nil { - return err - } - resp := response.(postProfileResponse) - return resp.Err -} - -// GetProfile implements Service. Primarily useful in a client. -func (e Endpoints) GetProfile(ctx context.Context, id string) (Profile, error) { - request := getProfileRequest{ID: id} - response, err := e.GetProfileEndpoint(ctx, request) - if err != nil { - return Profile{}, err - } - resp := response.(getProfileResponse) - return resp.Profile, resp.Err -} - -// PutProfile implements Service. Primarily useful in a client. -func (e Endpoints) PutProfile(ctx context.Context, id string, p Profile) error { - request := putProfileRequest{ID: id, Profile: p} - response, err := e.PutProfileEndpoint(ctx, request) - if err != nil { - return err - } - resp := response.(putProfileResponse) - return resp.Err -} - -// PatchProfile implements Service. Primarily useful in a client. -func (e Endpoints) PatchProfile(ctx context.Context, id string, p Profile) error { - request := patchProfileRequest{ID: id, Profile: p} - response, err := e.PatchProfileEndpoint(ctx, request) - if err != nil { - return err - } - resp := response.(patchProfileResponse) - return resp.Err -} - -// DeleteProfile implements Service. Primarily useful in a client. -func (e Endpoints) DeleteProfile(ctx context.Context, id string) error { - request := deleteProfileRequest{ID: id} - response, err := e.DeleteProfileEndpoint(ctx, request) - if err != nil { - return err - } - resp := response.(deleteProfileResponse) - return resp.Err -} - -// GetAddresses implements Service. Primarily useful in a client. -func (e Endpoints) GetAddresses(ctx context.Context, profileID string) ([]Address, error) { - request := getAddressesRequest{ProfileID: profileID} - response, err := e.GetAddressesEndpoint(ctx, request) - if err != nil { - return nil, err - } - resp := response.(getAddressesResponse) - return resp.Addresses, resp.Err -} - -// GetAddress implements Service. Primarily useful in a client. -func (e Endpoints) GetAddress(ctx context.Context, profileID string, addressID string) (Address, error) { - request := getAddressRequest{ProfileID: profileID, AddressID: addressID} - response, err := e.GetAddressEndpoint(ctx, request) - if err != nil { - return Address{}, err - } - resp := response.(getAddressResponse) - return resp.Address, resp.Err -} - -// PostAddress implements Service. Primarily useful in a client. -func (e Endpoints) PostAddress(ctx context.Context, profileID string, a Address) error { - request := postAddressRequest{ProfileID: profileID, Address: a} - response, err := e.PostAddressEndpoint(ctx, request) - if err != nil { - return err - } - resp := response.(postAddressResponse) - return resp.Err -} - -// DeleteAddress implements Service. Primarily useful in a client. -func (e Endpoints) DeleteAddress(ctx context.Context, profileID string, addressID string) error { - request := deleteAddressRequest{ProfileID: profileID, AddressID: addressID} - response, err := e.DeleteAddressEndpoint(ctx, request) - if err != nil { - return err - } - resp := response.(deleteAddressResponse) - return resp.Err -} - -// MakePostProfileEndpoint returns an endpoint via the passed service. -// Primarily useful in a server. -func MakePostProfileEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(postProfileRequest) - e := s.PostProfile(ctx, req.Profile) - return postProfileResponse{Err: e}, nil - } -} - -// MakeGetProfileEndpoint returns an endpoint via the passed service. -// Primarily useful in a server. -func MakeGetProfileEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(getProfileRequest) - p, e := s.GetProfile(ctx, req.ID) - return getProfileResponse{Profile: p, Err: e}, nil - } -} - -// MakePutProfileEndpoint returns an endpoint via the passed service. -// Primarily useful in a server. -func MakePutProfileEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(putProfileRequest) - e := s.PutProfile(ctx, req.ID, req.Profile) - return putProfileResponse{Err: e}, nil - } -} - -// MakePatchProfileEndpoint returns an endpoint via the passed service. -// Primarily useful in a server. -func MakePatchProfileEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(patchProfileRequest) - e := s.PatchProfile(ctx, req.ID, req.Profile) - return patchProfileResponse{Err: e}, nil - } -} - -// MakeDeleteProfileEndpoint returns an endpoint via the passed service. -// Primarily useful in a server. -func MakeDeleteProfileEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(deleteProfileRequest) - e := s.DeleteProfile(ctx, req.ID) - return deleteProfileResponse{Err: e}, nil - } -} - -// MakeGetAddressesEndpoint returns an endpoint via the passed service. -// Primarily useful in a server. -func MakeGetAddressesEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(getAddressesRequest) - a, e := s.GetAddresses(ctx, req.ProfileID) - return getAddressesResponse{Addresses: a, Err: e}, nil - } -} - -// MakeGetAddressEndpoint returns an endpoint via the passed service. -// Primarily useful in a server. -func MakeGetAddressEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(getAddressRequest) - a, e := s.GetAddress(ctx, req.ProfileID, req.AddressID) - return getAddressResponse{Address: a, Err: e}, nil - } -} - -// MakePostAddressEndpoint returns an endpoint via the passed service. -// Primarily useful in a server. -func MakePostAddressEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(postAddressRequest) - e := s.PostAddress(ctx, req.ProfileID, req.Address) - return postAddressResponse{Err: e}, nil - } -} - -// MakeDeleteAddressEndpoint returns an endpoint via the passed service. -// Primarily useful in a server. -func MakeDeleteAddressEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(deleteAddressRequest) - e := s.DeleteAddress(ctx, req.ProfileID, req.AddressID) - return deleteAddressResponse{Err: e}, nil - } -} - -// We have two options to return errors from the business logic. -// -// We could return the error via the endpoint itself. That makes certain things -// a little bit easier, like providing non-200 HTTP responses to the client. But -// Go kit assumes that endpoint errors are (or may be treated as) -// transport-domain errors. For example, an endpoint error will count against a -// circuit breaker error count. -// -// Therefore, it's often better to return service (business logic) errors in the -// response object. This means we have to do a bit more work in the HTTP -// response encoder to detect e.g. a not-found error and provide a proper HTTP -// status code. That work is done with the errorer interface, in transport.go. -// Response types that may contain business-logic errors implement that -// interface. - -type postProfileRequest struct { - Profile Profile -} - -type postProfileResponse struct { - Err error `json:"err,omitempty"` -} - -func (r postProfileResponse) error() error { return r.Err } - -type getProfileRequest struct { - ID string -} - -type getProfileResponse struct { - Profile Profile `json:"profile,omitempty"` - Err error `json:"err,omitempty"` -} - -func (r getProfileResponse) error() error { return r.Err } - -type putProfileRequest struct { - ID string - Profile Profile -} - -type putProfileResponse struct { - Err error `json:"err,omitempty"` -} - -func (r putProfileResponse) error() error { return nil } - -type patchProfileRequest struct { - ID string - Profile Profile -} - -type patchProfileResponse struct { - Err error `json:"err,omitempty"` -} - -func (r patchProfileResponse) error() error { return r.Err } - -type deleteProfileRequest struct { - ID string -} - -type deleteProfileResponse struct { - Err error `json:"err,omitempty"` -} - -func (r deleteProfileResponse) error() error { return r.Err } - -type getAddressesRequest struct { - ProfileID string -} - -type getAddressesResponse struct { - Addresses []Address `json:"addresses,omitempty"` - Err error `json:"err,omitempty"` -} - -func (r getAddressesResponse) error() error { return r.Err } - -type getAddressRequest struct { - ProfileID string - AddressID string -} - -type getAddressResponse struct { - Address Address `json:"address,omitempty"` - Err error `json:"err,omitempty"` -} - -func (r getAddressResponse) error() error { return r.Err } - -type postAddressRequest struct { - ProfileID string - Address Address -} - -type postAddressResponse struct { - Err error `json:"err,omitempty"` -} - -func (r postAddressResponse) error() error { return r.Err } - -type deleteAddressRequest struct { - ProfileID string - AddressID string -} - -type deleteAddressResponse struct { - Err error `json:"err,omitempty"` -} - -func (r deleteAddressResponse) error() error { return r.Err } diff --git a/vendor/github.com/go-kit/kit/examples/profilesvc/middlewares.go b/vendor/github.com/go-kit/kit/examples/profilesvc/middlewares.go deleted file mode 100644 index 1b738f5b..00000000 --- a/vendor/github.com/go-kit/kit/examples/profilesvc/middlewares.go +++ /dev/null @@ -1,88 +0,0 @@ -package profilesvc - -import ( - "context" - "time" - - "github.com/go-kit/kit/log" -) - -// Middleware describes a service (as opposed to endpoint) middleware. -type Middleware func(Service) Service - -func LoggingMiddleware(logger log.Logger) Middleware { - return func(next Service) Service { - return &loggingMiddleware{ - next: next, - logger: logger, - } - } -} - -type loggingMiddleware struct { - next Service - logger log.Logger -} - -func (mw loggingMiddleware) PostProfile(ctx context.Context, p Profile) (err error) { - defer func(begin time.Time) { - mw.logger.Log("method", "PostProfile", "id", p.ID, "took", time.Since(begin), "err", err) - }(time.Now()) - return mw.next.PostProfile(ctx, p) -} - -func (mw loggingMiddleware) GetProfile(ctx context.Context, id string) (p Profile, err error) { - defer func(begin time.Time) { - mw.logger.Log("method", "GetProfile", "id", id, "took", time.Since(begin), "err", err) - }(time.Now()) - return mw.next.GetProfile(ctx, id) -} - -func (mw loggingMiddleware) PutProfile(ctx context.Context, id string, p Profile) (err error) { - defer func(begin time.Time) { - mw.logger.Log("method", "PutProfile", "id", id, "took", time.Since(begin), "err", err) - }(time.Now()) - return mw.next.PutProfile(ctx, id, p) -} - -func (mw loggingMiddleware) PatchProfile(ctx context.Context, id string, p Profile) (err error) { - defer func(begin time.Time) { - mw.logger.Log("method", "PatchProfile", "id", id, "took", time.Since(begin), "err", err) - }(time.Now()) - return mw.next.PatchProfile(ctx, id, p) -} - -func (mw loggingMiddleware) DeleteProfile(ctx context.Context, id string) (err error) { - defer func(begin time.Time) { - mw.logger.Log("method", "DeleteProfile", "id", id, "took", time.Since(begin), "err", err) - }(time.Now()) - return mw.next.DeleteProfile(ctx, id) -} - -func (mw loggingMiddleware) GetAddresses(ctx context.Context, profileID string) (addresses []Address, err error) { - defer func(begin time.Time) { - mw.logger.Log("method", "GetAddresses", "profileID", profileID, "took", time.Since(begin), "err", err) - }(time.Now()) - return mw.next.GetAddresses(ctx, profileID) -} - -func (mw loggingMiddleware) GetAddress(ctx context.Context, profileID string, addressID string) (a Address, err error) { - defer func(begin time.Time) { - mw.logger.Log("method", "GetAddress", "profileID", profileID, "addressID", addressID, "took", time.Since(begin), "err", err) - }(time.Now()) - return mw.next.GetAddress(ctx, profileID, addressID) -} - -func (mw loggingMiddleware) PostAddress(ctx context.Context, profileID string, a Address) (err error) { - defer func(begin time.Time) { - mw.logger.Log("method", "PostAddress", "profileID", profileID, "took", time.Since(begin), "err", err) - }(time.Now()) - return mw.next.PostAddress(ctx, profileID, a) -} - -func (mw loggingMiddleware) DeleteAddress(ctx context.Context, profileID string, addressID string) (err error) { - defer func(begin time.Time) { - mw.logger.Log("method", "DeleteAddress", "profileID", profileID, "addressID", addressID, "took", time.Since(begin), "err", err) - }(time.Now()) - return mw.next.DeleteAddress(ctx, profileID, addressID) -} diff --git a/vendor/github.com/go-kit/kit/examples/profilesvc/service.go b/vendor/github.com/go-kit/kit/examples/profilesvc/service.go deleted file mode 100644 index cd34ecd9..00000000 --- a/vendor/github.com/go-kit/kit/examples/profilesvc/service.go +++ /dev/null @@ -1,185 +0,0 @@ -package profilesvc - -import ( - "context" - "errors" - "sync" -) - -// Service is a simple CRUD interface for user profiles. -type Service interface { - PostProfile(ctx context.Context, p Profile) error - GetProfile(ctx context.Context, id string) (Profile, error) - PutProfile(ctx context.Context, id string, p Profile) error - PatchProfile(ctx context.Context, id string, p Profile) error - DeleteProfile(ctx context.Context, id string) error - GetAddresses(ctx context.Context, profileID string) ([]Address, error) - GetAddress(ctx context.Context, profileID string, addressID string) (Address, error) - PostAddress(ctx context.Context, profileID string, a Address) error - DeleteAddress(ctx context.Context, profileID string, addressID string) error -} - -// Profile represents a single user profile. -// ID should be globally unique. -type Profile struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Addresses []Address `json:"addresses,omitempty"` -} - -// Address is a field of a user profile. -// ID should be unique within the profile (at a minimum). -type Address struct { - ID string `json:"id"` - Location string `json:"location,omitempty"` -} - -var ( - ErrInconsistentIDs = errors.New("inconsistent IDs") - ErrAlreadyExists = errors.New("already exists") - ErrNotFound = errors.New("not found") -) - -type inmemService struct { - mtx sync.RWMutex - m map[string]Profile -} - -func NewInmemService() Service { - return &inmemService{ - m: map[string]Profile{}, - } -} - -func (s *inmemService) PostProfile(ctx context.Context, p Profile) error { - s.mtx.Lock() - defer s.mtx.Unlock() - if _, ok := s.m[p.ID]; ok { - return ErrAlreadyExists // POST = create, don't overwrite - } - s.m[p.ID] = p - return nil -} - -func (s *inmemService) GetProfile(ctx context.Context, id string) (Profile, error) { - s.mtx.RLock() - defer s.mtx.RUnlock() - p, ok := s.m[id] - if !ok { - return Profile{}, ErrNotFound - } - return p, nil -} - -func (s *inmemService) PutProfile(ctx context.Context, id string, p Profile) error { - if id != p.ID { - return ErrInconsistentIDs - } - s.mtx.Lock() - defer s.mtx.Unlock() - s.m[id] = p // PUT = create or update - return nil -} - -func (s *inmemService) PatchProfile(ctx context.Context, id string, p Profile) error { - if p.ID != "" && id != p.ID { - return ErrInconsistentIDs - } - - s.mtx.Lock() - defer s.mtx.Unlock() - - existing, ok := s.m[id] - if !ok { - return ErrNotFound // PATCH = update existing, don't create - } - - // We assume that it's not possible to PATCH the ID, and that it's not - // possible to PATCH any field to its zero value. That is, the zero value - // means not specified. The way around this is to use e.g. Name *string in - // the Profile definition. But since this is just a demonstrative example, - // I'm leaving that out. - - if p.Name != "" { - existing.Name = p.Name - } - if len(p.Addresses) > 0 { - existing.Addresses = p.Addresses - } - s.m[id] = existing - return nil -} - -func (s *inmemService) DeleteProfile(ctx context.Context, id string) error { - s.mtx.Lock() - defer s.mtx.Unlock() - if _, ok := s.m[id]; !ok { - return ErrNotFound - } - delete(s.m, id) - return nil -} - -func (s *inmemService) GetAddresses(ctx context.Context, profileID string) ([]Address, error) { - s.mtx.RLock() - defer s.mtx.RUnlock() - p, ok := s.m[profileID] - if !ok { - return []Address{}, ErrNotFound - } - return p.Addresses, nil -} - -func (s *inmemService) GetAddress(ctx context.Context, profileID string, addressID string) (Address, error) { - s.mtx.RLock() - defer s.mtx.RUnlock() - p, ok := s.m[profileID] - if !ok { - return Address{}, ErrNotFound - } - for _, address := range p.Addresses { - if address.ID == addressID { - return address, nil - } - } - return Address{}, ErrNotFound -} - -func (s *inmemService) PostAddress(ctx context.Context, profileID string, a Address) error { - s.mtx.Lock() - defer s.mtx.Unlock() - p, ok := s.m[profileID] - if !ok { - return ErrNotFound - } - for _, address := range p.Addresses { - if address.ID == a.ID { - return ErrAlreadyExists - } - } - p.Addresses = append(p.Addresses, a) - s.m[profileID] = p - return nil -} - -func (s *inmemService) DeleteAddress(ctx context.Context, profileID string, addressID string) error { - s.mtx.Lock() - defer s.mtx.Unlock() - p, ok := s.m[profileID] - if !ok { - return ErrNotFound - } - newAddresses := make([]Address, 0, len(p.Addresses)) - for _, address := range p.Addresses { - if address.ID == addressID { - continue // delete - } - newAddresses = append(newAddresses, address) - } - if len(newAddresses) == len(p.Addresses) { - return ErrNotFound - } - p.Addresses = newAddresses - s.m[profileID] = p - return nil -} diff --git a/vendor/github.com/go-kit/kit/examples/profilesvc/transport.go b/vendor/github.com/go-kit/kit/examples/profilesvc/transport.go deleted file mode 100644 index a0136ee4..00000000 --- a/vendor/github.com/go-kit/kit/examples/profilesvc/transport.go +++ /dev/null @@ -1,400 +0,0 @@ -package profilesvc - -// The profilesvc is just over HTTP, so we just have a single transport.go. - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "io/ioutil" - "net/http" - "net/url" - - "github.com/gorilla/mux" - - "github.com/go-kit/kit/log" - httptransport "github.com/go-kit/kit/transport/http" -) - -var ( - // ErrBadRouting is returned when an expected path variable is missing. - // It always indicates programmer error. - ErrBadRouting = errors.New("inconsistent mapping between route and handler (programmer error)") -) - -// MakeHTTPHandler mounts all of the service endpoints into an http.Handler. -// Useful in a profilesvc server. -func MakeHTTPHandler(s Service, logger log.Logger) http.Handler { - r := mux.NewRouter() - e := MakeServerEndpoints(s) - options := []httptransport.ServerOption{ - httptransport.ServerErrorLogger(logger), - httptransport.ServerErrorEncoder(encodeError), - } - - // POST /profiles/ adds another profile - // GET /profiles/:id retrieves the given profile by id - // PUT /profiles/:id post updated profile information about the profile - // PATCH /profiles/:id partial updated profile information - // DELETE /profiles/:id remove the given profile - // GET /profiles/:id/addresses/ retrieve addresses associated with the profile - // GET /profiles/:id/addresses/:addressID retrieve a particular profile address - // POST /profiles/:id/addresses/ add a new address - // DELETE /profiles/:id/addresses/:addressID remove an address - - r.Methods("POST").Path("/profiles/").Handler(httptransport.NewServer( - e.PostProfileEndpoint, - decodePostProfileRequest, - encodeResponse, - options..., - )) - r.Methods("GET").Path("/profiles/{id}").Handler(httptransport.NewServer( - e.GetProfileEndpoint, - decodeGetProfileRequest, - encodeResponse, - options..., - )) - r.Methods("PUT").Path("/profiles/{id}").Handler(httptransport.NewServer( - e.PutProfileEndpoint, - decodePutProfileRequest, - encodeResponse, - options..., - )) - r.Methods("PATCH").Path("/profiles/{id}").Handler(httptransport.NewServer( - e.PatchProfileEndpoint, - decodePatchProfileRequest, - encodeResponse, - options..., - )) - r.Methods("DELETE").Path("/profiles/{id}").Handler(httptransport.NewServer( - e.DeleteProfileEndpoint, - decodeDeleteProfileRequest, - encodeResponse, - options..., - )) - r.Methods("GET").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer( - e.GetAddressesEndpoint, - decodeGetAddressesRequest, - encodeResponse, - options..., - )) - r.Methods("GET").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer( - e.GetAddressEndpoint, - decodeGetAddressRequest, - encodeResponse, - options..., - )) - r.Methods("POST").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer( - e.PostAddressEndpoint, - decodePostAddressRequest, - encodeResponse, - options..., - )) - r.Methods("DELETE").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer( - e.DeleteAddressEndpoint, - decodeDeleteAddressRequest, - encodeResponse, - options..., - )) - return r -} - -func decodePostProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) { - var req postProfileRequest - if e := json.NewDecoder(r.Body).Decode(&req.Profile); e != nil { - return nil, e - } - return req, nil -} - -func decodeGetProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, ErrBadRouting - } - return getProfileRequest{ID: id}, nil -} - -func decodePutProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, ErrBadRouting - } - var profile Profile - if err := json.NewDecoder(r.Body).Decode(&profile); err != nil { - return nil, err - } - return putProfileRequest{ - ID: id, - Profile: profile, - }, nil -} - -func decodePatchProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, ErrBadRouting - } - var profile Profile - if err := json.NewDecoder(r.Body).Decode(&profile); err != nil { - return nil, err - } - return patchProfileRequest{ - ID: id, - Profile: profile, - }, nil -} - -func decodeDeleteProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, ErrBadRouting - } - return deleteProfileRequest{ID: id}, nil -} - -func decodeGetAddressesRequest(_ context.Context, r *http.Request) (request interface{}, err error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, ErrBadRouting - } - return getAddressesRequest{ProfileID: id}, nil -} - -func decodeGetAddressRequest(_ context.Context, r *http.Request) (request interface{}, err error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, ErrBadRouting - } - addressID, ok := vars["addressID"] - if !ok { - return nil, ErrBadRouting - } - return getAddressRequest{ - ProfileID: id, - AddressID: addressID, - }, nil -} - -func decodePostAddressRequest(_ context.Context, r *http.Request) (request interface{}, err error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, ErrBadRouting - } - var address Address - if err := json.NewDecoder(r.Body).Decode(&address); err != nil { - return nil, err - } - return postAddressRequest{ - ProfileID: id, - Address: address, - }, nil -} - -func decodeDeleteAddressRequest(_ context.Context, r *http.Request) (request interface{}, err error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, ErrBadRouting - } - addressID, ok := vars["addressID"] - if !ok { - return nil, ErrBadRouting - } - return deleteAddressRequest{ - ProfileID: id, - AddressID: addressID, - }, nil -} - -func encodePostProfileRequest(ctx context.Context, req *http.Request, request interface{}) error { - // r.Methods("POST").Path("/profiles/") - req.Method, req.URL.Path = "POST", "/profiles/" - return encodeRequest(ctx, req, request) -} - -func encodeGetProfileRequest(ctx context.Context, req *http.Request, request interface{}) error { - // r.Methods("GET").Path("/profiles/{id}") - r := request.(getProfileRequest) - profileID := url.QueryEscape(r.ID) - req.Method, req.URL.Path = "GET", "/profiles/"+profileID - return encodeRequest(ctx, req, request) -} - -func encodePutProfileRequest(ctx context.Context, req *http.Request, request interface{}) error { - // r.Methods("PUT").Path("/profiles/{id}") - r := request.(putProfileRequest) - profileID := url.QueryEscape(r.ID) - req.Method, req.URL.Path = "PUT", "/profiles/"+profileID - return encodeRequest(ctx, req, request) -} - -func encodePatchProfileRequest(ctx context.Context, req *http.Request, request interface{}) error { - // r.Methods("PATCH").Path("/profiles/{id}") - r := request.(patchProfileRequest) - profileID := url.QueryEscape(r.ID) - req.Method, req.URL.Path = "PATCH", "/profiles/"+profileID - return encodeRequest(ctx, req, request) -} - -func encodeDeleteProfileRequest(ctx context.Context, req *http.Request, request interface{}) error { - // r.Methods("DELETE").Path("/profiles/{id}") - r := request.(deleteProfileRequest) - profileID := url.QueryEscape(r.ID) - req.Method, req.URL.Path = "DELETE", "/profiles/"+profileID - return encodeRequest(ctx, req, request) -} - -func encodeGetAddressesRequest(ctx context.Context, req *http.Request, request interface{}) error { - // r.Methods("GET").Path("/profiles/{id}/addresses/") - r := request.(getAddressesRequest) - profileID := url.QueryEscape(r.ProfileID) - req.Method, req.URL.Path = "GET", "/profiles/"+profileID+"/addresses/" - return encodeRequest(ctx, req, request) -} - -func encodeGetAddressRequest(ctx context.Context, req *http.Request, request interface{}) error { - // r.Methods("GET").Path("/profiles/{id}/addresses/{addressID}") - r := request.(getAddressRequest) - profileID := url.QueryEscape(r.ProfileID) - addressID := url.QueryEscape(r.AddressID) - req.Method, req.URL.Path = "GET", "/profiles/"+profileID+"/addresses/"+addressID - return encodeRequest(ctx, req, request) -} - -func encodePostAddressRequest(ctx context.Context, req *http.Request, request interface{}) error { - // r.Methods("POST").Path("/profiles/{id}/addresses/") - r := request.(postAddressRequest) - profileID := url.QueryEscape(r.ProfileID) - req.Method, req.URL.Path = "POST", "/profiles/"+profileID+"/addresses/" - return encodeRequest(ctx, req, request) -} - -func encodeDeleteAddressRequest(ctx context.Context, req *http.Request, request interface{}) error { - // r.Methods("DELETE").Path("/profiles/{id}/addresses/{addressID}") - r := request.(deleteAddressRequest) - profileID := url.QueryEscape(r.ProfileID) - addressID := url.QueryEscape(r.AddressID) - req.Method, req.URL.Path = "DELETE", "/profiles/"+profileID+"/addresses/"+addressID - return encodeRequest(ctx, req, request) -} - -func decodePostProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) { - var response postProfileResponse - err := json.NewDecoder(resp.Body).Decode(&response) - return response, err -} - -func decodeGetProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) { - var response getProfileResponse - err := json.NewDecoder(resp.Body).Decode(&response) - return response, err -} - -func decodePutProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) { - var response putProfileResponse - err := json.NewDecoder(resp.Body).Decode(&response) - return response, err -} - -func decodePatchProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) { - var response patchProfileResponse - err := json.NewDecoder(resp.Body).Decode(&response) - return response, err -} - -func decodeDeleteProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) { - var response deleteProfileResponse - err := json.NewDecoder(resp.Body).Decode(&response) - return response, err -} - -func decodeGetAddressesResponse(_ context.Context, resp *http.Response) (interface{}, error) { - var response getAddressesResponse - err := json.NewDecoder(resp.Body).Decode(&response) - return response, err -} - -func decodeGetAddressResponse(_ context.Context, resp *http.Response) (interface{}, error) { - var response getAddressResponse - err := json.NewDecoder(resp.Body).Decode(&response) - return response, err -} - -func decodePostAddressResponse(_ context.Context, resp *http.Response) (interface{}, error) { - var response postAddressResponse - err := json.NewDecoder(resp.Body).Decode(&response) - return response, err -} - -func decodeDeleteAddressResponse(_ context.Context, resp *http.Response) (interface{}, error) { - var response deleteAddressResponse - err := json.NewDecoder(resp.Body).Decode(&response) - return response, err -} - -// errorer is implemented by all concrete response types that may contain -// errors. It allows us to change the HTTP response code without needing to -// trigger an endpoint (transport-level) error. For more information, read the -// big comment in endpoints.go. -type errorer interface { - error() error -} - -// encodeResponse is the common method to encode all response types to the -// client. I chose to do it this way because, since we're using JSON, there's no -// reason to provide anything more specific. It's certainly possible to -// specialize on a per-response (per-method) basis. -func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { - if e, ok := response.(errorer); ok && e.error() != nil { - // Not a Go kit transport error, but a business-logic error. - // Provide those as HTTP errors. - encodeError(ctx, e.error(), w) - return nil - } - w.Header().Set("Content-Type", "application/json; charset=utf-8") - return json.NewEncoder(w).Encode(response) -} - -// encodeRequest likewise JSON-encodes the request to the HTTP request body. -// Don't use it directly as a transport/http.Client EncodeRequestFunc: -// profilesvc endpoints require mutating the HTTP method and request path. -func encodeRequest(_ context.Context, req *http.Request, request interface{}) error { - var buf bytes.Buffer - err := json.NewEncoder(&buf).Encode(request) - if err != nil { - return err - } - req.Body = ioutil.NopCloser(&buf) - return nil -} - -func encodeError(_ context.Context, err error, w http.ResponseWriter) { - if err == nil { - panic("encodeError with nil error") - } - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(codeFrom(err)) - json.NewEncoder(w).Encode(map[string]interface{}{ - "error": err.Error(), - }) -} - -func codeFrom(err error) int { - switch err { - case ErrNotFound: - return http.StatusNotFound - case ErrAlreadyExists, ErrInconsistentIDs: - return http.StatusBadRequest - default: - return http.StatusInternalServerError - } -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/README.md b/vendor/github.com/go-kit/kit/examples/shipping/README.md deleted file mode 100644 index 1a9a14ee..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# shipping - -This example demonstrates a more real-world application consisting of multiple services. - -## Description - -The implementation is based on the container shipping domain from the [Domain Driven Design](http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215) book by Eric Evans, which was [originally](http://dddsample.sourceforge.net/) implemented in Java but has since been ported to Go. This example is a somewhat stripped down version to demonstrate the use of Go kit. The [original Go application](https://github.com/marcusolsson/goddd) is maintained separately and accompanied by an [AngularJS application](https://github.com/marcusolsson/dddelivery-angularjs) as well as a mock [routing service](https://github.com/marcusolsson/pathfinder). - -### Organization - -The application consists of three application services, `booking`, `handling` and `tracking`. Each of these is an individual Go kit service as seen in previous examples. - -- __booking__ - used by the shipping company to book and route cargos. -- __handling__ - used by our staff around the world to register whenever the cargo has been received, loaded etc. -- __tracking__ - used by the customer to track the cargo along the route - -There are also a few pure domain packages that contain some intricate business-logic. They provide domain objects and services that are used by each application service to provide interesting use-cases for the user. - -`inmem` contains in-memory implementations for the repositories found in the domain packages. - -The `routing` package provides a _domain service_ that is used to query an external application for possible routes. - -## Contributing - -As with all Go kit examples you are more than welcome to contribute. If you do however, please consider contributing back to the original project as well. diff --git a/vendor/github.com/go-kit/kit/examples/shipping/booking/endpoint.go b/vendor/github.com/go-kit/kit/examples/shipping/booking/endpoint.go deleted file mode 100644 index abe83f75..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/booking/endpoint.go +++ /dev/null @@ -1,139 +0,0 @@ -package booking - -import ( - "context" - "time" - - "github.com/go-kit/kit/endpoint" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" -) - -type bookCargoRequest struct { - Origin location.UNLocode - Destination location.UNLocode - ArrivalDeadline time.Time -} - -type bookCargoResponse struct { - ID cargo.TrackingID `json:"tracking_id,omitempty"` - Err error `json:"error,omitempty"` -} - -func (r bookCargoResponse) error() error { return r.Err } - -func makeBookCargoEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(bookCargoRequest) - id, err := s.BookNewCargo(req.Origin, req.Destination, req.ArrivalDeadline) - return bookCargoResponse{ID: id, Err: err}, nil - } -} - -type loadCargoRequest struct { - ID cargo.TrackingID -} - -type loadCargoResponse struct { - Cargo *Cargo `json:"cargo,omitempty"` - Err error `json:"error,omitempty"` -} - -func (r loadCargoResponse) error() error { return r.Err } - -func makeLoadCargoEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(loadCargoRequest) - c, err := s.LoadCargo(req.ID) - return loadCargoResponse{Cargo: &c, Err: err}, nil - } -} - -type requestRoutesRequest struct { - ID cargo.TrackingID -} - -type requestRoutesResponse struct { - Routes []cargo.Itinerary `json:"routes,omitempty"` - Err error `json:"error,omitempty"` -} - -func (r requestRoutesResponse) error() error { return r.Err } - -func makeRequestRoutesEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(requestRoutesRequest) - itin := s.RequestPossibleRoutesForCargo(req.ID) - return requestRoutesResponse{Routes: itin, Err: nil}, nil - } -} - -type assignToRouteRequest struct { - ID cargo.TrackingID - Itinerary cargo.Itinerary -} - -type assignToRouteResponse struct { - Err error `json:"error,omitempty"` -} - -func (r assignToRouteResponse) error() error { return r.Err } - -func makeAssignToRouteEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(assignToRouteRequest) - err := s.AssignCargoToRoute(req.ID, req.Itinerary) - return assignToRouteResponse{Err: err}, nil - } -} - -type changeDestinationRequest struct { - ID cargo.TrackingID - Destination location.UNLocode -} - -type changeDestinationResponse struct { - Err error `json:"error,omitempty"` -} - -func (r changeDestinationResponse) error() error { return r.Err } - -func makeChangeDestinationEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(changeDestinationRequest) - err := s.ChangeDestination(req.ID, req.Destination) - return changeDestinationResponse{Err: err}, nil - } -} - -type listCargosRequest struct{} - -type listCargosResponse struct { - Cargos []Cargo `json:"cargos,omitempty"` - Err error `json:"error,omitempty"` -} - -func (r listCargosResponse) error() error { return r.Err } - -func makeListCargosEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - _ = request.(listCargosRequest) - return listCargosResponse{Cargos: s.Cargos(), Err: nil}, nil - } -} - -type listLocationsRequest struct { -} - -type listLocationsResponse struct { - Locations []Location `json:"locations,omitempty"` - Err error `json:"error,omitempty"` -} - -func makeListLocationsEndpoint(s Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - _ = request.(listLocationsRequest) - return listLocationsResponse{Locations: s.Locations(), Err: nil}, nil - } -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/booking/instrumenting.go b/vendor/github.com/go-kit/kit/examples/shipping/booking/instrumenting.go deleted file mode 100644 index b9b03b91..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/booking/instrumenting.go +++ /dev/null @@ -1,88 +0,0 @@ -package booking - -import ( - "time" - - "github.com/go-kit/kit/metrics" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" -) - -type instrumentingService struct { - requestCount metrics.Counter - requestLatency metrics.Histogram - Service -} - -// NewInstrumentingService returns an instance of an instrumenting Service. -func NewInstrumentingService(counter metrics.Counter, latency metrics.Histogram, s Service) Service { - return &instrumentingService{ - requestCount: counter, - requestLatency: latency, - Service: s, - } -} - -func (s *instrumentingService) BookNewCargo(origin, destination location.UNLocode, deadline time.Time) (cargo.TrackingID, error) { - defer func(begin time.Time) { - s.requestCount.With("method", "book").Add(1) - s.requestLatency.With("method", "book").Observe(time.Since(begin).Seconds()) - }(time.Now()) - - return s.Service.BookNewCargo(origin, destination, deadline) -} - -func (s *instrumentingService) LoadCargo(id cargo.TrackingID) (c Cargo, err error) { - defer func(begin time.Time) { - s.requestCount.With("method", "load").Add(1) - s.requestLatency.With("method", "load").Observe(time.Since(begin).Seconds()) - }(time.Now()) - - return s.Service.LoadCargo(id) -} - -func (s *instrumentingService) RequestPossibleRoutesForCargo(id cargo.TrackingID) []cargo.Itinerary { - defer func(begin time.Time) { - s.requestCount.With("method", "request_routes").Add(1) - s.requestLatency.With("method", "request_routes").Observe(time.Since(begin).Seconds()) - }(time.Now()) - - return s.Service.RequestPossibleRoutesForCargo(id) -} - -func (s *instrumentingService) AssignCargoToRoute(id cargo.TrackingID, itinerary cargo.Itinerary) (err error) { - defer func(begin time.Time) { - s.requestCount.With("method", "assign_to_route").Add(1) - s.requestLatency.With("method", "assign_to_route").Observe(time.Since(begin).Seconds()) - }(time.Now()) - - return s.Service.AssignCargoToRoute(id, itinerary) -} - -func (s *instrumentingService) ChangeDestination(id cargo.TrackingID, l location.UNLocode) (err error) { - defer func(begin time.Time) { - s.requestCount.With("method", "change_destination").Add(1) - s.requestLatency.With("method", "change_destination").Observe(time.Since(begin).Seconds()) - }(time.Now()) - - return s.Service.ChangeDestination(id, l) -} - -func (s *instrumentingService) Cargos() []Cargo { - defer func(begin time.Time) { - s.requestCount.With("method", "list_cargos").Add(1) - s.requestLatency.With("method", "list_cargos").Observe(time.Since(begin).Seconds()) - }(time.Now()) - - return s.Service.Cargos() -} - -func (s *instrumentingService) Locations() []Location { - defer func(begin time.Time) { - s.requestCount.With("method", "list_locations").Add(1) - s.requestLatency.With("method", "list_locations").Observe(time.Since(begin).Seconds()) - }(time.Now()) - - return s.Service.Locations() -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/booking/logging.go b/vendor/github.com/go-kit/kit/examples/shipping/booking/logging.go deleted file mode 100644 index 931d4307..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/booking/logging.go +++ /dev/null @@ -1,102 +0,0 @@ -package booking - -import ( - "time" - - "github.com/go-kit/kit/log" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" -) - -type loggingService struct { - logger log.Logger - Service -} - -// NewLoggingService returns a new instance of a logging Service. -func NewLoggingService(logger log.Logger, s Service) Service { - return &loggingService{logger, s} -} - -func (s *loggingService) BookNewCargo(origin location.UNLocode, destination location.UNLocode, deadline time.Time) (id cargo.TrackingID, err error) { - defer func(begin time.Time) { - s.logger.Log( - "method", "book", - "origin", origin, - "destination", destination, - "arrival_deadline", deadline, - "took", time.Since(begin), - "err", err, - ) - }(time.Now()) - return s.Service.BookNewCargo(origin, destination, deadline) -} - -func (s *loggingService) LoadCargo(id cargo.TrackingID) (c Cargo, err error) { - defer func(begin time.Time) { - s.logger.Log( - "method", "load", - "tracking_id", id, - "took", time.Since(begin), - "err", err, - ) - }(time.Now()) - return s.Service.LoadCargo(id) -} - -func (s *loggingService) RequestPossibleRoutesForCargo(id cargo.TrackingID) []cargo.Itinerary { - defer func(begin time.Time) { - s.logger.Log( - "method", "request_routes", - "tracking_id", id, - "took", time.Since(begin), - ) - }(time.Now()) - return s.Service.RequestPossibleRoutesForCargo(id) -} - -func (s *loggingService) AssignCargoToRoute(id cargo.TrackingID, itinerary cargo.Itinerary) (err error) { - defer func(begin time.Time) { - s.logger.Log( - "method", "assign_to_route", - "tracking_id", id, - "took", time.Since(begin), - "err", err, - ) - }(time.Now()) - return s.Service.AssignCargoToRoute(id, itinerary) -} - -func (s *loggingService) ChangeDestination(id cargo.TrackingID, l location.UNLocode) (err error) { - defer func(begin time.Time) { - s.logger.Log( - "method", "change_destination", - "tracking_id", id, - "destination", l, - "took", time.Since(begin), - "err", err, - ) - }(time.Now()) - return s.Service.ChangeDestination(id, l) -} - -func (s *loggingService) Cargos() []Cargo { - defer func(begin time.Time) { - s.logger.Log( - "method", "list_cargos", - "took", time.Since(begin), - ) - }(time.Now()) - return s.Service.Cargos() -} - -func (s *loggingService) Locations() []Location { - defer func(begin time.Time) { - s.logger.Log( - "method", "list_locations", - "took", time.Since(begin), - ) - }(time.Now()) - return s.Service.Locations() -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/booking/service.go b/vendor/github.com/go-kit/kit/examples/shipping/booking/service.go deleted file mode 100644 index 8689a5a5..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/booking/service.go +++ /dev/null @@ -1,197 +0,0 @@ -// Package booking provides the use-case of booking a cargo. Used by views -// facing an administrator. -package booking - -import ( - "errors" - "time" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/routing" -) - -// ErrInvalidArgument is returned when one or more arguments are invalid. -var ErrInvalidArgument = errors.New("invalid argument") - -// Service is the interface that provides booking methods. -type Service interface { - // BookNewCargo registers a new cargo in the tracking system, not yet - // routed. - BookNewCargo(origin location.UNLocode, destination location.UNLocode, deadline time.Time) (cargo.TrackingID, error) - - // LoadCargo returns a read model of a cargo. - LoadCargo(id cargo.TrackingID) (Cargo, error) - - // RequestPossibleRoutesForCargo requests a list of itineraries describing - // possible routes for this cargo. - RequestPossibleRoutesForCargo(id cargo.TrackingID) []cargo.Itinerary - - // AssignCargoToRoute assigns a cargo to the route specified by the - // itinerary. - AssignCargoToRoute(id cargo.TrackingID, itinerary cargo.Itinerary) error - - // ChangeDestination changes the destination of a cargo. - ChangeDestination(id cargo.TrackingID, destination location.UNLocode) error - - // Cargos returns a list of all cargos that have been booked. - Cargos() []Cargo - - // Locations returns a list of registered locations. - Locations() []Location -} - -type service struct { - cargos cargo.Repository - locations location.Repository - handlingEvents cargo.HandlingEventRepository - routingService routing.Service -} - -func (s *service) AssignCargoToRoute(id cargo.TrackingID, itinerary cargo.Itinerary) error { - if id == "" || len(itinerary.Legs) == 0 { - return ErrInvalidArgument - } - - c, err := s.cargos.Find(id) - if err != nil { - return err - } - - c.AssignToRoute(itinerary) - - return s.cargos.Store(c) -} - -func (s *service) BookNewCargo(origin, destination location.UNLocode, deadline time.Time) (cargo.TrackingID, error) { - if origin == "" || destination == "" || deadline.IsZero() { - return "", ErrInvalidArgument - } - - id := cargo.NextTrackingID() - rs := cargo.RouteSpecification{ - Origin: origin, - Destination: destination, - ArrivalDeadline: deadline, - } - - c := cargo.New(id, rs) - - if err := s.cargos.Store(c); err != nil { - return "", err - } - - return c.TrackingID, nil -} - -func (s *service) LoadCargo(id cargo.TrackingID) (Cargo, error) { - if id == "" { - return Cargo{}, ErrInvalidArgument - } - - c, err := s.cargos.Find(id) - if err != nil { - return Cargo{}, err - } - - return assemble(c, s.handlingEvents), nil -} - -func (s *service) ChangeDestination(id cargo.TrackingID, destination location.UNLocode) error { - if id == "" || destination == "" { - return ErrInvalidArgument - } - - c, err := s.cargos.Find(id) - if err != nil { - return err - } - - l, err := s.locations.Find(destination) - if err != nil { - return err - } - - c.SpecifyNewRoute(cargo.RouteSpecification{ - Origin: c.Origin, - Destination: l.UNLocode, - ArrivalDeadline: c.RouteSpecification.ArrivalDeadline, - }) - - if err := s.cargos.Store(c); err != nil { - return err - } - - return nil -} - -func (s *service) RequestPossibleRoutesForCargo(id cargo.TrackingID) []cargo.Itinerary { - if id == "" { - return nil - } - - c, err := s.cargos.Find(id) - if err != nil { - return []cargo.Itinerary{} - } - - return s.routingService.FetchRoutesForSpecification(c.RouteSpecification) -} - -func (s *service) Cargos() []Cargo { - var result []Cargo - for _, c := range s.cargos.FindAll() { - result = append(result, assemble(c, s.handlingEvents)) - } - return result -} - -func (s *service) Locations() []Location { - var result []Location - for _, v := range s.locations.FindAll() { - result = append(result, Location{ - UNLocode: string(v.UNLocode), - Name: v.Name, - }) - } - return result -} - -// NewService creates a booking service with necessary dependencies. -func NewService(cargos cargo.Repository, locations location.Repository, events cargo.HandlingEventRepository, rs routing.Service) Service { - return &service{ - cargos: cargos, - locations: locations, - handlingEvents: events, - routingService: rs, - } -} - -// Location is a read model for booking views. -type Location struct { - UNLocode string `json:"locode"` - Name string `json:"name"` -} - -// Cargo is a read model for booking views. -type Cargo struct { - ArrivalDeadline time.Time `json:"arrival_deadline"` - Destination string `json:"destination"` - Legs []cargo.Leg `json:"legs,omitempty"` - Misrouted bool `json:"misrouted"` - Origin string `json:"origin"` - Routed bool `json:"routed"` - TrackingID string `json:"tracking_id"` -} - -func assemble(c *cargo.Cargo, events cargo.HandlingEventRepository) Cargo { - return Cargo{ - TrackingID: string(c.TrackingID), - Origin: string(c.Origin), - Destination: string(c.RouteSpecification.Destination), - Misrouted: c.Delivery.RoutingStatus == cargo.Misrouted, - Routed: !c.Itinerary.IsEmpty(), - ArrivalDeadline: c.RouteSpecification.ArrivalDeadline, - Legs: c.Itinerary.Legs, - } -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/booking/transport.go b/vendor/github.com/go-kit/kit/examples/shipping/booking/transport.go deleted file mode 100644 index 8cf11a26..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/booking/transport.go +++ /dev/null @@ -1,194 +0,0 @@ -package booking - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "time" - - "github.com/gorilla/mux" - - kitlog "github.com/go-kit/kit/log" - kithttp "github.com/go-kit/kit/transport/http" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" -) - -// MakeHandler returns a handler for the booking service. -func MakeHandler(bs Service, logger kitlog.Logger) http.Handler { - opts := []kithttp.ServerOption{ - kithttp.ServerErrorLogger(logger), - kithttp.ServerErrorEncoder(encodeError), - } - - bookCargoHandler := kithttp.NewServer( - makeBookCargoEndpoint(bs), - decodeBookCargoRequest, - encodeResponse, - opts..., - ) - loadCargoHandler := kithttp.NewServer( - makeLoadCargoEndpoint(bs), - decodeLoadCargoRequest, - encodeResponse, - opts..., - ) - requestRoutesHandler := kithttp.NewServer( - makeRequestRoutesEndpoint(bs), - decodeRequestRoutesRequest, - encodeResponse, - opts..., - ) - assignToRouteHandler := kithttp.NewServer( - makeAssignToRouteEndpoint(bs), - decodeAssignToRouteRequest, - encodeResponse, - opts..., - ) - changeDestinationHandler := kithttp.NewServer( - makeChangeDestinationEndpoint(bs), - decodeChangeDestinationRequest, - encodeResponse, - opts..., - ) - listCargosHandler := kithttp.NewServer( - makeListCargosEndpoint(bs), - decodeListCargosRequest, - encodeResponse, - opts..., - ) - listLocationsHandler := kithttp.NewServer( - makeListLocationsEndpoint(bs), - decodeListLocationsRequest, - encodeResponse, - opts..., - ) - - r := mux.NewRouter() - - r.Handle("/booking/v1/cargos", bookCargoHandler).Methods("POST") - r.Handle("/booking/v1/cargos", listCargosHandler).Methods("GET") - r.Handle("/booking/v1/cargos/{id}", loadCargoHandler).Methods("GET") - r.Handle("/booking/v1/cargos/{id}/request_routes", requestRoutesHandler).Methods("GET") - r.Handle("/booking/v1/cargos/{id}/assign_to_route", assignToRouteHandler).Methods("POST") - r.Handle("/booking/v1/cargos/{id}/change_destination", changeDestinationHandler).Methods("POST") - r.Handle("/booking/v1/locations", listLocationsHandler).Methods("GET") - - return r -} - -var errBadRoute = errors.New("bad route") - -func decodeBookCargoRequest(_ context.Context, r *http.Request) (interface{}, error) { - var body struct { - Origin string `json:"origin"` - Destination string `json:"destination"` - ArrivalDeadline time.Time `json:"arrival_deadline"` - } - - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - return nil, err - } - - return bookCargoRequest{ - Origin: location.UNLocode(body.Origin), - Destination: location.UNLocode(body.Destination), - ArrivalDeadline: body.ArrivalDeadline, - }, nil -} - -func decodeLoadCargoRequest(_ context.Context, r *http.Request) (interface{}, error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, errBadRoute - } - return loadCargoRequest{ID: cargo.TrackingID(id)}, nil -} - -func decodeRequestRoutesRequest(_ context.Context, r *http.Request) (interface{}, error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, errBadRoute - } - return requestRoutesRequest{ID: cargo.TrackingID(id)}, nil -} - -func decodeAssignToRouteRequest(_ context.Context, r *http.Request) (interface{}, error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, errBadRoute - } - - var itinerary cargo.Itinerary - if err := json.NewDecoder(r.Body).Decode(&itinerary); err != nil { - return nil, err - } - - return assignToRouteRequest{ - ID: cargo.TrackingID(id), - Itinerary: itinerary, - }, nil -} - -func decodeChangeDestinationRequest(_ context.Context, r *http.Request) (interface{}, error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, errBadRoute - } - - var body struct { - Destination string `json:"destination"` - } - - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - return nil, err - } - - return changeDestinationRequest{ - ID: cargo.TrackingID(id), - Destination: location.UNLocode(body.Destination), - }, nil -} - -func decodeListCargosRequest(_ context.Context, r *http.Request) (interface{}, error) { - return listCargosRequest{}, nil -} - -func decodeListLocationsRequest(_ context.Context, r *http.Request) (interface{}, error) { - return listLocationsRequest{}, nil -} - -func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { - if e, ok := response.(errorer); ok && e.error() != nil { - encodeError(ctx, e.error(), w) - return nil - } - w.Header().Set("Content-Type", "application/json; charset=utf-8") - return json.NewEncoder(w).Encode(response) -} - -type errorer interface { - error() error -} - -// encode errors from business-logic -func encodeError(_ context.Context, err error, w http.ResponseWriter) { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - switch err { - case cargo.ErrUnknown: - w.WriteHeader(http.StatusNotFound) - case ErrInvalidArgument: - w.WriteHeader(http.StatusBadRequest) - default: - w.WriteHeader(http.StatusInternalServerError) - } - json.NewEncoder(w).Encode(map[string]interface{}{ - "error": err.Error(), - }) -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/cargo/cargo.go b/vendor/github.com/go-kit/kit/examples/shipping/cargo/cargo.go deleted file mode 100644 index a9440f51..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/cargo/cargo.go +++ /dev/null @@ -1,137 +0,0 @@ -// Package cargo contains the heart of the domain model. -package cargo - -import ( - "errors" - "strings" - "time" - - "github.com/pborman/uuid" - - "github.com/go-kit/kit/examples/shipping/location" -) - -// TrackingID uniquely identifies a particular cargo. -type TrackingID string - -// Cargo is the central class in the domain model. -type Cargo struct { - TrackingID TrackingID - Origin location.UNLocode - RouteSpecification RouteSpecification - Itinerary Itinerary - Delivery Delivery -} - -// SpecifyNewRoute specifies a new route for this cargo. -func (c *Cargo) SpecifyNewRoute(rs RouteSpecification) { - c.RouteSpecification = rs - c.Delivery = c.Delivery.UpdateOnRouting(c.RouteSpecification, c.Itinerary) -} - -// AssignToRoute attaches a new itinerary to this cargo. -func (c *Cargo) AssignToRoute(itinerary Itinerary) { - c.Itinerary = itinerary - c.Delivery = c.Delivery.UpdateOnRouting(c.RouteSpecification, c.Itinerary) -} - -// DeriveDeliveryProgress updates all aspects of the cargo aggregate status -// based on the current route specification, itinerary and handling of the cargo. -func (c *Cargo) DeriveDeliveryProgress(history HandlingHistory) { - c.Delivery = DeriveDeliveryFrom(c.RouteSpecification, c.Itinerary, history) -} - -// New creates a new, unrouted cargo. -func New(id TrackingID, rs RouteSpecification) *Cargo { - itinerary := Itinerary{} - history := HandlingHistory{make([]HandlingEvent, 0)} - - return &Cargo{ - TrackingID: id, - Origin: rs.Origin, - RouteSpecification: rs, - Delivery: DeriveDeliveryFrom(rs, itinerary, history), - } -} - -// Repository provides access a cargo store. -type Repository interface { - Store(cargo *Cargo) error - Find(id TrackingID) (*Cargo, error) - FindAll() []*Cargo -} - -// ErrUnknown is used when a cargo could not be found. -var ErrUnknown = errors.New("unknown cargo") - -// NextTrackingID generates a new tracking ID. -// TODO: Move to infrastructure(?) -func NextTrackingID() TrackingID { - return TrackingID(strings.Split(strings.ToUpper(uuid.New()), "-")[0]) -} - -// RouteSpecification Contains information about a route: its origin, -// destination and arrival deadline. -type RouteSpecification struct { - Origin location.UNLocode - Destination location.UNLocode - ArrivalDeadline time.Time -} - -// IsSatisfiedBy checks whether provided itinerary satisfies this -// specification. -func (s RouteSpecification) IsSatisfiedBy(itinerary Itinerary) bool { - return itinerary.Legs != nil && - s.Origin == itinerary.InitialDepartureLocation() && - s.Destination == itinerary.FinalArrivalLocation() -} - -// RoutingStatus describes status of cargo routing. -type RoutingStatus int - -// Valid routing statuses. -const ( - NotRouted RoutingStatus = iota - Misrouted - Routed -) - -func (s RoutingStatus) String() string { - switch s { - case NotRouted: - return "Not routed" - case Misrouted: - return "Misrouted" - case Routed: - return "Routed" - } - return "" -} - -// TransportStatus describes status of cargo transportation. -type TransportStatus int - -// Valid transport statuses. -const ( - NotReceived TransportStatus = iota - InPort - OnboardCarrier - Claimed - Unknown -) - -func (s TransportStatus) String() string { - switch s { - case NotReceived: - return "Not received" - case InPort: - return "In port" - case OnboardCarrier: - return "Onboard carrier" - case Claimed: - return "Claimed" - case Unknown: - return "Unknown" - } - return "" -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/cargo/delivery.go b/vendor/github.com/go-kit/kit/examples/shipping/cargo/delivery.go deleted file mode 100644 index 34f079dc..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/cargo/delivery.go +++ /dev/null @@ -1,174 +0,0 @@ -package cargo - -import ( - "time" - - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/voyage" -) - -// Delivery is the actual transportation of the cargo, as opposed to the -// customer requirement (RouteSpecification) and the plan (Itinerary). -type Delivery struct { - Itinerary Itinerary - RouteSpecification RouteSpecification - RoutingStatus RoutingStatus - TransportStatus TransportStatus - NextExpectedActivity HandlingActivity - LastEvent HandlingEvent - LastKnownLocation location.UNLocode - CurrentVoyage voyage.Number - ETA time.Time - IsMisdirected bool - IsUnloadedAtDestination bool -} - -// UpdateOnRouting creates a new delivery snapshot to reflect changes in -// routing, i.e. when the route specification or the itinerary has changed but -// no additional handling of the cargo has been performed. -func (d Delivery) UpdateOnRouting(rs RouteSpecification, itinerary Itinerary) Delivery { - return newDelivery(d.LastEvent, itinerary, rs) -} - -// IsOnTrack checks if the delivery is on track. -func (d Delivery) IsOnTrack() bool { - return d.RoutingStatus == Routed && !d.IsMisdirected -} - -// DeriveDeliveryFrom creates a new delivery snapshot based on the complete -// handling history of a cargo, as well as its route specification and -// itinerary. -func DeriveDeliveryFrom(rs RouteSpecification, itinerary Itinerary, history HandlingHistory) Delivery { - lastEvent, _ := history.MostRecentlyCompletedEvent() - return newDelivery(lastEvent, itinerary, rs) -} - -// newDelivery creates a up-to-date delivery based on an handling event, -// itinerary and a route specification. -func newDelivery(lastEvent HandlingEvent, itinerary Itinerary, rs RouteSpecification) Delivery { - var ( - routingStatus = calculateRoutingStatus(itinerary, rs) - transportStatus = calculateTransportStatus(lastEvent) - lastKnownLocation = calculateLastKnownLocation(lastEvent) - isMisdirected = calculateMisdirectedStatus(lastEvent, itinerary) - isUnloadedAtDestination = calculateUnloadedAtDestination(lastEvent, rs) - currentVoyage = calculateCurrentVoyage(transportStatus, lastEvent) - ) - - d := Delivery{ - LastEvent: lastEvent, - Itinerary: itinerary, - RouteSpecification: rs, - RoutingStatus: routingStatus, - TransportStatus: transportStatus, - LastKnownLocation: lastKnownLocation, - IsMisdirected: isMisdirected, - IsUnloadedAtDestination: isUnloadedAtDestination, - CurrentVoyage: currentVoyage, - } - - d.NextExpectedActivity = calculateNextExpectedActivity(d) - d.ETA = calculateETA(d) - - return d -} - -// Below are internal functions used when creating a new delivery. - -func calculateRoutingStatus(itinerary Itinerary, rs RouteSpecification) RoutingStatus { - if itinerary.Legs == nil { - return NotRouted - } - - if rs.IsSatisfiedBy(itinerary) { - return Routed - } - - return Misrouted -} - -func calculateMisdirectedStatus(event HandlingEvent, itinerary Itinerary) bool { - if event.Activity.Type == NotHandled { - return false - } - - return !itinerary.IsExpected(event) -} - -func calculateUnloadedAtDestination(event HandlingEvent, rs RouteSpecification) bool { - if event.Activity.Type == NotHandled { - return false - } - - return event.Activity.Type == Unload && rs.Destination == event.Activity.Location -} - -func calculateTransportStatus(event HandlingEvent) TransportStatus { - switch event.Activity.Type { - case NotHandled: - return NotReceived - case Load: - return OnboardCarrier - case Unload: - return InPort - case Receive: - return InPort - case Customs: - return InPort - case Claim: - return Claimed - } - return Unknown -} - -func calculateLastKnownLocation(event HandlingEvent) location.UNLocode { - return event.Activity.Location -} - -func calculateNextExpectedActivity(d Delivery) HandlingActivity { - if !d.IsOnTrack() { - return HandlingActivity{} - } - - switch d.LastEvent.Activity.Type { - case NotHandled: - return HandlingActivity{Type: Receive, Location: d.RouteSpecification.Origin} - case Receive: - l := d.Itinerary.Legs[0] - return HandlingActivity{Type: Load, Location: l.LoadLocation, VoyageNumber: l.VoyageNumber} - case Load: - for _, l := range d.Itinerary.Legs { - if l.LoadLocation == d.LastEvent.Activity.Location { - return HandlingActivity{Type: Unload, Location: l.UnloadLocation, VoyageNumber: l.VoyageNumber} - } - } - case Unload: - for i, l := range d.Itinerary.Legs { - if l.UnloadLocation == d.LastEvent.Activity.Location { - if i < len(d.Itinerary.Legs)-1 { - return HandlingActivity{Type: Load, Location: d.Itinerary.Legs[i+1].LoadLocation, VoyageNumber: d.Itinerary.Legs[i+1].VoyageNumber} - } - - return HandlingActivity{Type: Claim, Location: l.UnloadLocation} - } - } - } - - return HandlingActivity{} -} - -func calculateCurrentVoyage(transportStatus TransportStatus, event HandlingEvent) voyage.Number { - if transportStatus == OnboardCarrier && event.Activity.Type != NotHandled { - return event.Activity.VoyageNumber - } - - return voyage.Number("") -} - -func calculateETA(d Delivery) time.Time { - if !d.IsOnTrack() { - return time.Time{} - } - - return d.Itinerary.FinalArrivalTime() -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/cargo/handling.go b/vendor/github.com/go-kit/kit/examples/shipping/cargo/handling.go deleted file mode 100644 index bec8509f..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/cargo/handling.go +++ /dev/null @@ -1,121 +0,0 @@ -package cargo - -// TODO: It would make sense to have this in its own package. Unfortunately, -// then there would be a circular dependency between the cargo and handling -// packages since cargo.Delivery would use handling.HandlingEvent and -// handling.HandlingEvent would use cargo.TrackingID. Also, -// HandlingEventFactory depends on the cargo repository. -// -// It would make sense not having the cargo package depend on handling. - -import ( - "errors" - "time" - - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/voyage" -) - -// HandlingActivity represents how and where a cargo can be handled, and can -// be used to express predictions about what is expected to happen to a cargo -// in the future. -type HandlingActivity struct { - Type HandlingEventType - Location location.UNLocode - VoyageNumber voyage.Number -} - -// HandlingEvent is used to register the event when, for instance, a cargo is -// unloaded from a carrier at a some location at a given time. -type HandlingEvent struct { - TrackingID TrackingID - Activity HandlingActivity -} - -// HandlingEventType describes type of a handling event. -type HandlingEventType int - -// Valid handling event types. -const ( - NotHandled HandlingEventType = iota - Load - Unload - Receive - Claim - Customs -) - -func (t HandlingEventType) String() string { - switch t { - case NotHandled: - return "Not Handled" - case Load: - return "Load" - case Unload: - return "Unload" - case Receive: - return "Receive" - case Claim: - return "Claim" - case Customs: - return "Customs" - } - - return "" -} - -// HandlingHistory is the handling history of a cargo. -type HandlingHistory struct { - HandlingEvents []HandlingEvent -} - -// MostRecentlyCompletedEvent returns most recently completed handling event. -func (h HandlingHistory) MostRecentlyCompletedEvent() (HandlingEvent, error) { - if len(h.HandlingEvents) == 0 { - return HandlingEvent{}, errors.New("delivery history is empty") - } - - return h.HandlingEvents[len(h.HandlingEvents)-1], nil -} - -// HandlingEventRepository provides access a handling event store. -type HandlingEventRepository interface { - Store(e HandlingEvent) - QueryHandlingHistory(TrackingID) HandlingHistory -} - -// HandlingEventFactory creates handling events. -type HandlingEventFactory struct { - CargoRepository Repository - VoyageRepository voyage.Repository - LocationRepository location.Repository -} - -// CreateHandlingEvent creates a validated handling event. -func (f *HandlingEventFactory) CreateHandlingEvent(registered time.Time, completed time.Time, id TrackingID, - voyageNumber voyage.Number, unLocode location.UNLocode, eventType HandlingEventType) (HandlingEvent, error) { - - if _, err := f.CargoRepository.Find(id); err != nil { - return HandlingEvent{}, err - } - - if _, err := f.VoyageRepository.Find(voyageNumber); err != nil { - // TODO: This is pretty ugly, but when creating a Receive event, the voyage number is not known. - if len(voyageNumber) > 0 { - return HandlingEvent{}, err - } - } - - if _, err := f.LocationRepository.Find(unLocode); err != nil { - return HandlingEvent{}, err - } - - return HandlingEvent{ - TrackingID: id, - Activity: HandlingActivity{ - Type: eventType, - Location: unLocode, - VoyageNumber: voyageNumber, - }, - }, nil -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/cargo/itinerary.go b/vendor/github.com/go-kit/kit/examples/shipping/cargo/itinerary.go deleted file mode 100644 index 6b5088ea..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/cargo/itinerary.go +++ /dev/null @@ -1,91 +0,0 @@ -package cargo - -import ( - "time" - - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/voyage" -) - -// Leg describes the transportation between two locations on a voyage. -type Leg struct { - VoyageNumber voyage.Number `json:"voyage_number"` - LoadLocation location.UNLocode `json:"from"` - UnloadLocation location.UNLocode `json:"to"` - LoadTime time.Time `json:"load_time"` - UnloadTime time.Time `json:"unload_time"` -} - -// NewLeg creates a new itinerary leg. -func NewLeg(voyageNumber voyage.Number, loadLocation, unloadLocation location.UNLocode, loadTime, unloadTime time.Time) Leg { - return Leg{ - VoyageNumber: voyageNumber, - LoadLocation: loadLocation, - UnloadLocation: unloadLocation, - LoadTime: loadTime, - UnloadTime: unloadTime, - } -} - -// Itinerary specifies steps required to transport a cargo from its origin to -// destination. -type Itinerary struct { - Legs []Leg `json:"legs"` -} - -// InitialDepartureLocation returns the start of the itinerary. -func (i Itinerary) InitialDepartureLocation() location.UNLocode { - if i.IsEmpty() { - return location.UNLocode("") - } - return i.Legs[0].LoadLocation -} - -// FinalArrivalLocation returns the end of the itinerary. -func (i Itinerary) FinalArrivalLocation() location.UNLocode { - if i.IsEmpty() { - return location.UNLocode("") - } - return i.Legs[len(i.Legs)-1].UnloadLocation -} - -// FinalArrivalTime returns the expected arrival time at final destination. -func (i Itinerary) FinalArrivalTime() time.Time { - return i.Legs[len(i.Legs)-1].UnloadTime -} - -// IsEmpty checks if the itinerary contains at least one leg. -func (i Itinerary) IsEmpty() bool { - return i.Legs == nil || len(i.Legs) == 0 -} - -// IsExpected checks if the given handling event is expected when executing -// this itinerary. -func (i Itinerary) IsExpected(event HandlingEvent) bool { - if i.IsEmpty() { - return true - } - - switch event.Activity.Type { - case Receive: - return i.InitialDepartureLocation() == event.Activity.Location - case Load: - for _, l := range i.Legs { - if l.LoadLocation == event.Activity.Location && l.VoyageNumber == event.Activity.VoyageNumber { - return true - } - } - return false - case Unload: - for _, l := range i.Legs { - if l.UnloadLocation == event.Activity.Location && l.VoyageNumber == event.Activity.VoyageNumber { - return true - } - } - return false - case Claim: - return i.FinalArrivalLocation() == event.Activity.Location - } - - return true -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/handling/endpoint.go b/vendor/github.com/go-kit/kit/examples/shipping/handling/endpoint.go deleted file mode 100644 index 555d0873..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/handling/endpoint.go +++ /dev/null @@ -1,34 +0,0 @@ -package handling - -import ( - "context" - "time" - - "github.com/go-kit/kit/endpoint" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/voyage" -) - -type registerIncidentRequest struct { - ID cargo.TrackingID - Location location.UNLocode - Voyage voyage.Number - EventType cargo.HandlingEventType - CompletionTime time.Time -} - -type registerIncidentResponse struct { - Err error `json:"error,omitempty"` -} - -func (r registerIncidentResponse) error() error { return r.Err } - -func makeRegisterIncidentEndpoint(hs Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(registerIncidentRequest) - err := hs.RegisterHandlingEvent(req.CompletionTime, req.ID, req.Voyage, req.Location, req.EventType) - return registerIncidentResponse{Err: err}, nil - } -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/handling/instrumenting.go b/vendor/github.com/go-kit/kit/examples/shipping/handling/instrumenting.go deleted file mode 100644 index fecce04e..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/handling/instrumenting.go +++ /dev/null @@ -1,37 +0,0 @@ -package handling - -import ( - "time" - - "github.com/go-kit/kit/metrics" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/voyage" -) - -type instrumentingService struct { - requestCount metrics.Counter - requestLatency metrics.Histogram - Service -} - -// NewInstrumentingService returns an instance of an instrumenting Service. -func NewInstrumentingService(counter metrics.Counter, latency metrics.Histogram, s Service) Service { - return &instrumentingService{ - requestCount: counter, - requestLatency: latency, - Service: s, - } -} - -func (s *instrumentingService) RegisterHandlingEvent(completed time.Time, id cargo.TrackingID, voyageNumber voyage.Number, - loc location.UNLocode, eventType cargo.HandlingEventType) error { - - defer func(begin time.Time) { - s.requestCount.With("method", "register_incident").Add(1) - s.requestLatency.With("method", "register_incident").Observe(time.Since(begin).Seconds()) - }(time.Now()) - - return s.Service.RegisterHandlingEvent(completed, id, voyageNumber, loc, eventType) -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/handling/logging.go b/vendor/github.com/go-kit/kit/examples/shipping/handling/logging.go deleted file mode 100644 index 84722fb4..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/handling/logging.go +++ /dev/null @@ -1,38 +0,0 @@ -package handling - -import ( - "time" - - "github.com/go-kit/kit/log" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/voyage" -) - -type loggingService struct { - logger log.Logger - Service -} - -// NewLoggingService returns a new instance of a logging Service. -func NewLoggingService(logger log.Logger, s Service) Service { - return &loggingService{logger, s} -} - -func (s *loggingService) RegisterHandlingEvent(completed time.Time, id cargo.TrackingID, voyageNumber voyage.Number, - unLocode location.UNLocode, eventType cargo.HandlingEventType) (err error) { - defer func(begin time.Time) { - s.logger.Log( - "method", "register_incident", - "tracking_id", id, - "location", unLocode, - "voyage", voyageNumber, - "event_type", eventType, - "completion_time", completed, - "took", time.Since(begin), - "err", err, - ) - }(time.Now()) - return s.Service.RegisterHandlingEvent(completed, id, voyageNumber, unLocode, eventType) -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/handling/service.go b/vendor/github.com/go-kit/kit/examples/shipping/handling/service.go deleted file mode 100644 index 83d503a2..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/handling/service.go +++ /dev/null @@ -1,76 +0,0 @@ -// Package handling provides the use-case for registering incidents. Used by -// views facing the people handling the cargo along its route. -package handling - -import ( - "errors" - "time" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/inspection" - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/voyage" -) - -// ErrInvalidArgument is returned when one or more arguments are invalid. -var ErrInvalidArgument = errors.New("invalid argument") - -// EventHandler provides a means of subscribing to registered handling events. -type EventHandler interface { - CargoWasHandled(cargo.HandlingEvent) -} - -// Service provides handling operations. -type Service interface { - // RegisterHandlingEvent registers a handling event in the system, and - // notifies interested parties that a cargo has been handled. - RegisterHandlingEvent(completed time.Time, id cargo.TrackingID, voyageNumber voyage.Number, - unLocode location.UNLocode, eventType cargo.HandlingEventType) error -} - -type service struct { - handlingEventRepository cargo.HandlingEventRepository - handlingEventFactory cargo.HandlingEventFactory - handlingEventHandler EventHandler -} - -func (s *service) RegisterHandlingEvent(completed time.Time, id cargo.TrackingID, voyageNumber voyage.Number, - loc location.UNLocode, eventType cargo.HandlingEventType) error { - if completed.IsZero() || id == "" || loc == "" || eventType == cargo.NotHandled { - return ErrInvalidArgument - } - - e, err := s.handlingEventFactory.CreateHandlingEvent(time.Now(), completed, id, voyageNumber, loc, eventType) - if err != nil { - return err - } - - s.handlingEventRepository.Store(e) - s.handlingEventHandler.CargoWasHandled(e) - - return nil -} - -// NewService creates a handling event service with necessary dependencies. -func NewService(r cargo.HandlingEventRepository, f cargo.HandlingEventFactory, h EventHandler) Service { - return &service{ - handlingEventRepository: r, - handlingEventFactory: f, - handlingEventHandler: h, - } -} - -type handlingEventHandler struct { - InspectionService inspection.Service -} - -func (h *handlingEventHandler) CargoWasHandled(event cargo.HandlingEvent) { - h.InspectionService.InspectCargo(event.TrackingID) -} - -// NewEventHandler returns a new instance of a EventHandler. -func NewEventHandler(s inspection.Service) EventHandler { - return &handlingEventHandler{ - InspectionService: s, - } -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/handling/transport.go b/vendor/github.com/go-kit/kit/examples/shipping/handling/transport.go deleted file mode 100644 index 0e21365b..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/handling/transport.go +++ /dev/null @@ -1,100 +0,0 @@ -package handling - -import ( - "context" - "encoding/json" - "net/http" - "time" - - "github.com/gorilla/mux" - - kitlog "github.com/go-kit/kit/log" - kithttp "github.com/go-kit/kit/transport/http" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/voyage" -) - -// MakeHandler returns a handler for the handling service. -func MakeHandler(hs Service, logger kitlog.Logger) http.Handler { - r := mux.NewRouter() - - opts := []kithttp.ServerOption{ - kithttp.ServerErrorLogger(logger), - kithttp.ServerErrorEncoder(encodeError), - } - - registerIncidentHandler := kithttp.NewServer( - makeRegisterIncidentEndpoint(hs), - decodeRegisterIncidentRequest, - encodeResponse, - opts..., - ) - - r.Handle("/handling/v1/incidents", registerIncidentHandler).Methods("POST") - - return r -} - -func decodeRegisterIncidentRequest(_ context.Context, r *http.Request) (interface{}, error) { - var body struct { - CompletionTime time.Time `json:"completion_time"` - TrackingID string `json:"tracking_id"` - VoyageNumber string `json:"voyage"` - Location string `json:"location"` - EventType string `json:"event_type"` - } - - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - return nil, err - } - - return registerIncidentRequest{ - CompletionTime: body.CompletionTime, - ID: cargo.TrackingID(body.TrackingID), - Voyage: voyage.Number(body.VoyageNumber), - Location: location.UNLocode(body.Location), - EventType: stringToEventType(body.EventType), - }, nil -} - -func stringToEventType(s string) cargo.HandlingEventType { - types := map[string]cargo.HandlingEventType{ - cargo.Receive.String(): cargo.Receive, - cargo.Load.String(): cargo.Load, - cargo.Unload.String(): cargo.Unload, - cargo.Customs.String(): cargo.Customs, - cargo.Claim.String(): cargo.Claim, - } - return types[s] -} - -func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { - if e, ok := response.(errorer); ok && e.error() != nil { - encodeError(ctx, e.error(), w) - return nil - } - w.Header().Set("Content-Type", "application/json; charset=utf-8") - return json.NewEncoder(w).Encode(response) -} - -type errorer interface { - error() error -} - -// encode errors from business-logic -func encodeError(_ context.Context, err error, w http.ResponseWriter) { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - switch err { - case cargo.ErrUnknown: - w.WriteHeader(http.StatusNotFound) - case ErrInvalidArgument: - w.WriteHeader(http.StatusBadRequest) - default: - w.WriteHeader(http.StatusInternalServerError) - } - json.NewEncoder(w).Encode(map[string]interface{}{ - "error": err.Error(), - }) -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/inmem/inmem.go b/vendor/github.com/go-kit/kit/examples/shipping/inmem/inmem.go deleted file mode 100644 index f941b7eb..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/inmem/inmem.go +++ /dev/null @@ -1,142 +0,0 @@ -// Package inmem provides in-memory implementations of all the domain repositories. -package inmem - -import ( - "sync" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/voyage" -) - -type cargoRepository struct { - mtx sync.RWMutex - cargos map[cargo.TrackingID]*cargo.Cargo -} - -func (r *cargoRepository) Store(c *cargo.Cargo) error { - r.mtx.Lock() - defer r.mtx.Unlock() - r.cargos[c.TrackingID] = c - return nil -} - -func (r *cargoRepository) Find(id cargo.TrackingID) (*cargo.Cargo, error) { - r.mtx.RLock() - defer r.mtx.RUnlock() - if val, ok := r.cargos[id]; ok { - return val, nil - } - return nil, cargo.ErrUnknown -} - -func (r *cargoRepository) FindAll() []*cargo.Cargo { - r.mtx.RLock() - defer r.mtx.RUnlock() - c := make([]*cargo.Cargo, 0, len(r.cargos)) - for _, val := range r.cargos { - c = append(c, val) - } - return c -} - -// NewCargoRepository returns a new instance of a in-memory cargo repository. -func NewCargoRepository() cargo.Repository { - return &cargoRepository{ - cargos: make(map[cargo.TrackingID]*cargo.Cargo), - } -} - -type locationRepository struct { - locations map[location.UNLocode]*location.Location -} - -func (r *locationRepository) Find(locode location.UNLocode) (*location.Location, error) { - if l, ok := r.locations[locode]; ok { - return l, nil - } - return nil, location.ErrUnknown -} - -func (r *locationRepository) FindAll() []*location.Location { - l := make([]*location.Location, 0, len(r.locations)) - for _, val := range r.locations { - l = append(l, val) - } - return l -} - -// NewLocationRepository returns a new instance of a in-memory location repository. -func NewLocationRepository() location.Repository { - r := &locationRepository{ - locations: make(map[location.UNLocode]*location.Location), - } - - r.locations[location.SESTO] = location.Stockholm - r.locations[location.AUMEL] = location.Melbourne - r.locations[location.CNHKG] = location.Hongkong - r.locations[location.JNTKO] = location.Tokyo - r.locations[location.NLRTM] = location.Rotterdam - r.locations[location.DEHAM] = location.Hamburg - - return r -} - -type voyageRepository struct { - voyages map[voyage.Number]*voyage.Voyage -} - -func (r *voyageRepository) Find(voyageNumber voyage.Number) (*voyage.Voyage, error) { - if v, ok := r.voyages[voyageNumber]; ok { - return v, nil - } - - return nil, voyage.ErrUnknown -} - -// NewVoyageRepository returns a new instance of a in-memory voyage repository. -func NewVoyageRepository() voyage.Repository { - r := &voyageRepository{ - voyages: make(map[voyage.Number]*voyage.Voyage), - } - - r.voyages[voyage.V100.Number] = voyage.V100 - r.voyages[voyage.V300.Number] = voyage.V300 - r.voyages[voyage.V400.Number] = voyage.V400 - - r.voyages[voyage.V0100S.Number] = voyage.V0100S - r.voyages[voyage.V0200T.Number] = voyage.V0200T - r.voyages[voyage.V0300A.Number] = voyage.V0300A - r.voyages[voyage.V0301S.Number] = voyage.V0301S - r.voyages[voyage.V0400S.Number] = voyage.V0400S - - return r -} - -type handlingEventRepository struct { - mtx sync.RWMutex - events map[cargo.TrackingID][]cargo.HandlingEvent -} - -func (r *handlingEventRepository) Store(e cargo.HandlingEvent) { - r.mtx.Lock() - defer r.mtx.Unlock() - // Make array if it's the first event with this tracking ID. - if _, ok := r.events[e.TrackingID]; !ok { - r.events[e.TrackingID] = make([]cargo.HandlingEvent, 0) - } - r.events[e.TrackingID] = append(r.events[e.TrackingID], e) -} - -func (r *handlingEventRepository) QueryHandlingHistory(id cargo.TrackingID) cargo.HandlingHistory { - r.mtx.RLock() - defer r.mtx.RUnlock() - return cargo.HandlingHistory{HandlingEvents: r.events[id]} -} - -// NewHandlingEventRepository returns a new instance of a in-memory handling event repository. -func NewHandlingEventRepository() cargo.HandlingEventRepository { - return &handlingEventRepository{ - events: make(map[cargo.TrackingID][]cargo.HandlingEvent), - } -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/inspection/inspection.go b/vendor/github.com/go-kit/kit/examples/shipping/inspection/inspection.go deleted file mode 100644 index 2ebf73d4..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/inspection/inspection.go +++ /dev/null @@ -1,53 +0,0 @@ -// Package inspection provides means to inspect cargos. -package inspection - -import ( - "github.com/go-kit/kit/examples/shipping/cargo" -) - -// EventHandler provides means of subscribing to inspection events. -type EventHandler interface { - CargoWasMisdirected(*cargo.Cargo) - CargoHasArrived(*cargo.Cargo) -} - -// Service provides cargo inspection operations. -type Service interface { - // InspectCargo inspects cargo and send relevant notifications to - // interested parties, for example if a cargo has been misdirected, or - // unloaded at the final destination. - InspectCargo(id cargo.TrackingID) -} - -type service struct { - cargos cargo.Repository - events cargo.HandlingEventRepository - handler EventHandler -} - -// TODO: Should be transactional -func (s *service) InspectCargo(id cargo.TrackingID) { - c, err := s.cargos.Find(id) - if err != nil { - return - } - - h := s.events.QueryHandlingHistory(id) - - c.DeriveDeliveryProgress(h) - - if c.Delivery.IsMisdirected { - s.handler.CargoWasMisdirected(c) - } - - if c.Delivery.IsUnloadedAtDestination { - s.handler.CargoHasArrived(c) - } - - s.cargos.Store(c) -} - -// NewService creates a inspection service with necessary dependencies. -func NewService(cargos cargo.Repository, events cargo.HandlingEventRepository, handler EventHandler) Service { - return &service{cargos, events, handler} -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/location/location.go b/vendor/github.com/go-kit/kit/examples/shipping/location/location.go deleted file mode 100644 index ee2e5d45..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/location/location.go +++ /dev/null @@ -1,29 +0,0 @@ -// Package location provides the Location aggregate. -package location - -import ( - "errors" -) - -// UNLocode is the United Nations location code that uniquely identifies a -// particular location. -// -// http://www.unece.org/cefact/locode/ -// http://www.unece.org/cefact/locode/DocColumnDescription.htm#LOCODE -type UNLocode string - -// Location is a location is our model is stops on a journey, such as cargo -// origin or destination, or carrier movement endpoints. -type Location struct { - UNLocode UNLocode - Name string -} - -// ErrUnknown is used when a location could not be found. -var ErrUnknown = errors.New("unknown location") - -// Repository provides access a location store. -type Repository interface { - Find(locode UNLocode) (*Location, error) - FindAll() []*Location -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/location/sample_locations.go b/vendor/github.com/go-kit/kit/examples/shipping/location/sample_locations.go deleted file mode 100644 index 7fd34efa..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/location/sample_locations.go +++ /dev/null @@ -1,27 +0,0 @@ -package location - -// Sample UN locodes. -var ( - SESTO UNLocode = "SESTO" - AUMEL UNLocode = "AUMEL" - CNHKG UNLocode = "CNHKG" - USNYC UNLocode = "USNYC" - USCHI UNLocode = "USCHI" - JNTKO UNLocode = "JNTKO" - DEHAM UNLocode = "DEHAM" - NLRTM UNLocode = "NLRTM" - FIHEL UNLocode = "FIHEL" -) - -// Sample locations. -var ( - Stockholm = &Location{SESTO, "Stockholm"} - Melbourne = &Location{AUMEL, "Melbourne"} - Hongkong = &Location{CNHKG, "Hongkong"} - NewYork = &Location{USNYC, "New York"} - Chicago = &Location{USCHI, "Chicago"} - Tokyo = &Location{JNTKO, "Tokyo"} - Hamburg = &Location{DEHAM, "Hamburg"} - Rotterdam = &Location{NLRTM, "Rotterdam"} - Helsinki = &Location{FIHEL, "Helsinki"} -) diff --git a/vendor/github.com/go-kit/kit/examples/shipping/main.go b/vendor/github.com/go-kit/kit/examples/shipping/main.go deleted file mode 100644 index 8337d61d..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/main.go +++ /dev/null @@ -1,200 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "net/http" - "os" - "os/signal" - "syscall" - "time" - - stdprometheus "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" - - "github.com/go-kit/kit/log" - kitprometheus "github.com/go-kit/kit/metrics/prometheus" - - "github.com/go-kit/kit/examples/shipping/booking" - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/handling" - "github.com/go-kit/kit/examples/shipping/inmem" - "github.com/go-kit/kit/examples/shipping/inspection" - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/routing" - "github.com/go-kit/kit/examples/shipping/tracking" -) - -const ( - defaultPort = "8080" - defaultRoutingServiceURL = "http://localhost:7878" -) - -func main() { - var ( - addr = envString("PORT", defaultPort) - rsurl = envString("ROUTINGSERVICE_URL", defaultRoutingServiceURL) - - httpAddr = flag.String("http.addr", ":"+addr, "HTTP listen address") - routingServiceURL = flag.String("service.routing", rsurl, "routing service URL") - - ctx = context.Background() - ) - - flag.Parse() - - var logger log.Logger - logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) - logger = log.With(logger, "ts", log.DefaultTimestampUTC) - - var ( - cargos = inmem.NewCargoRepository() - locations = inmem.NewLocationRepository() - voyages = inmem.NewVoyageRepository() - handlingEvents = inmem.NewHandlingEventRepository() - ) - - // Configure some questionable dependencies. - var ( - handlingEventFactory = cargo.HandlingEventFactory{ - CargoRepository: cargos, - VoyageRepository: voyages, - LocationRepository: locations, - } - handlingEventHandler = handling.NewEventHandler( - inspection.NewService(cargos, handlingEvents, nil), - ) - ) - - // Facilitate testing by adding some cargos. - storeTestData(cargos) - - fieldKeys := []string{"method"} - - var rs routing.Service - rs = routing.NewProxyingMiddleware(ctx, *routingServiceURL)(rs) - - var bs booking.Service - bs = booking.NewService(cargos, locations, handlingEvents, rs) - bs = booking.NewLoggingService(log.With(logger, "component", "booking"), bs) - bs = booking.NewInstrumentingService( - kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{ - Namespace: "api", - Subsystem: "booking_service", - Name: "request_count", - Help: "Number of requests received.", - }, fieldKeys), - kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ - Namespace: "api", - Subsystem: "booking_service", - Name: "request_latency_microseconds", - Help: "Total duration of requests in microseconds.", - }, fieldKeys), - bs, - ) - - var ts tracking.Service - ts = tracking.NewService(cargos, handlingEvents) - ts = tracking.NewLoggingService(log.With(logger, "component", "tracking"), ts) - ts = tracking.NewInstrumentingService( - kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{ - Namespace: "api", - Subsystem: "tracking_service", - Name: "request_count", - Help: "Number of requests received.", - }, fieldKeys), - kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ - Namespace: "api", - Subsystem: "tracking_service", - Name: "request_latency_microseconds", - Help: "Total duration of requests in microseconds.", - }, fieldKeys), - ts, - ) - - var hs handling.Service - hs = handling.NewService(handlingEvents, handlingEventFactory, handlingEventHandler) - hs = handling.NewLoggingService(log.With(logger, "component", "handling"), hs) - hs = handling.NewInstrumentingService( - kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{ - Namespace: "api", - Subsystem: "handling_service", - Name: "request_count", - Help: "Number of requests received.", - }, fieldKeys), - kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ - Namespace: "api", - Subsystem: "handling_service", - Name: "request_latency_microseconds", - Help: "Total duration of requests in microseconds.", - }, fieldKeys), - hs, - ) - - httpLogger := log.With(logger, "component", "http") - - mux := http.NewServeMux() - - mux.Handle("/booking/v1/", booking.MakeHandler(bs, httpLogger)) - mux.Handle("/tracking/v1/", tracking.MakeHandler(ts, httpLogger)) - mux.Handle("/handling/v1/", handling.MakeHandler(hs, httpLogger)) - - http.Handle("/", accessControl(mux)) - http.Handle("/metrics", promhttp.Handler()) - - errs := make(chan error, 2) - go func() { - logger.Log("transport", "http", "address", *httpAddr, "msg", "listening") - errs <- http.ListenAndServe(*httpAddr, nil) - }() - go func() { - c := make(chan os.Signal) - signal.Notify(c, syscall.SIGINT) - errs <- fmt.Errorf("%s", <-c) - }() - - logger.Log("terminated", <-errs) -} - -func accessControl(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type") - - if r.Method == "OPTIONS" { - return - } - - h.ServeHTTP(w, r) - }) -} - -func envString(env, fallback string) string { - e := os.Getenv(env) - if e == "" { - return fallback - } - return e -} - -func storeTestData(r cargo.Repository) { - test1 := cargo.New("FTL456", cargo.RouteSpecification{ - Origin: location.AUMEL, - Destination: location.SESTO, - ArrivalDeadline: time.Now().AddDate(0, 0, 7), - }) - if err := r.Store(test1); err != nil { - panic(err) - } - - test2 := cargo.New("ABC123", cargo.RouteSpecification{ - Origin: location.SESTO, - Destination: location.CNHKG, - ArrivalDeadline: time.Now().AddDate(0, 0, 14), - }) - if err := r.Store(test2); err != nil { - panic(err) - } -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/routing/proxying.go b/vendor/github.com/go-kit/kit/examples/shipping/routing/proxying.go deleted file mode 100644 index 0c9150b1..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/routing/proxying.go +++ /dev/null @@ -1,117 +0,0 @@ -package routing - -import ( - "context" - "encoding/json" - "net/http" - "net/url" - "time" - - "github.com/go-kit/kit/circuitbreaker" - "github.com/go-kit/kit/endpoint" - kithttp "github.com/go-kit/kit/transport/http" - - "github.com/go-kit/kit/examples/shipping/cargo" - "github.com/go-kit/kit/examples/shipping/location" - "github.com/go-kit/kit/examples/shipping/voyage" -) - -type proxyService struct { - context.Context - FetchRoutesEndpoint endpoint.Endpoint - Service -} - -func (s proxyService) FetchRoutesForSpecification(rs cargo.RouteSpecification) []cargo.Itinerary { - response, err := s.FetchRoutesEndpoint(s.Context, fetchRoutesRequest{ - From: string(rs.Origin), - To: string(rs.Destination), - }) - if err != nil { - return []cargo.Itinerary{} - } - - resp := response.(fetchRoutesResponse) - - var itineraries []cargo.Itinerary - for _, r := range resp.Paths { - var legs []cargo.Leg - for _, e := range r.Edges { - legs = append(legs, cargo.Leg{ - VoyageNumber: voyage.Number(e.Voyage), - LoadLocation: location.UNLocode(e.Origin), - UnloadLocation: location.UNLocode(e.Destination), - LoadTime: e.Departure, - UnloadTime: e.Arrival, - }) - } - - itineraries = append(itineraries, cargo.Itinerary{Legs: legs}) - } - - return itineraries -} - -// ServiceMiddleware defines a middleware for a routing service. -type ServiceMiddleware func(Service) Service - -// NewProxyingMiddleware returns a new instance of a proxying middleware. -func NewProxyingMiddleware(ctx context.Context, proxyURL string) ServiceMiddleware { - return func(next Service) Service { - var e endpoint.Endpoint - e = makeFetchRoutesEndpoint(ctx, proxyURL) - e = circuitbreaker.Hystrix("fetch-routes")(e) - return proxyService{ctx, e, next} - } -} - -type fetchRoutesRequest struct { - From string - To string -} - -type fetchRoutesResponse struct { - Paths []struct { - Edges []struct { - Origin string `json:"origin"` - Destination string `json:"destination"` - Voyage string `json:"voyage"` - Departure time.Time `json:"departure"` - Arrival time.Time `json:"arrival"` - } `json:"edges"` - } `json:"paths"` -} - -func makeFetchRoutesEndpoint(ctx context.Context, instance string) endpoint.Endpoint { - u, err := url.Parse(instance) - if err != nil { - panic(err) - } - if u.Path == "" { - u.Path = "/paths" - } - return kithttp.NewClient( - "GET", u, - encodeFetchRoutesRequest, - decodeFetchRoutesResponse, - ).Endpoint() -} - -func decodeFetchRoutesResponse(_ context.Context, resp *http.Response) (interface{}, error) { - var response fetchRoutesResponse - if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { - return nil, err - } - return response, nil -} - -func encodeFetchRoutesRequest(_ context.Context, r *http.Request, request interface{}) error { - req := request.(fetchRoutesRequest) - - vals := r.URL.Query() - vals.Add("from", req.From) - vals.Add("to", req.To) - r.URL.RawQuery = vals.Encode() - - return nil -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/routing/routing.go b/vendor/github.com/go-kit/kit/examples/shipping/routing/routing.go deleted file mode 100644 index 50496f2b..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/routing/routing.go +++ /dev/null @@ -1,15 +0,0 @@ -// Package routing provides the routing domain service. It does not actually -// implement the routing service but merely acts as a proxy for a separate -// bounded context. -package routing - -import ( - "github.com/go-kit/kit/examples/shipping/cargo" -) - -// Service provides access to an external routing service. -type Service interface { - // FetchRoutesForSpecification finds all possible routes that satisfy a - // given specification. - FetchRoutesForSpecification(rs cargo.RouteSpecification) []cargo.Itinerary -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/tracking/endpoint.go b/vendor/github.com/go-kit/kit/examples/shipping/tracking/endpoint.go deleted file mode 100644 index ddb13172..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/tracking/endpoint.go +++ /dev/null @@ -1,26 +0,0 @@ -package tracking - -import ( - "context" - - "github.com/go-kit/kit/endpoint" -) - -type trackCargoRequest struct { - ID string -} - -type trackCargoResponse struct { - Cargo *Cargo `json:"cargo,omitempty"` - Err error `json:"error,omitempty"` -} - -func (r trackCargoResponse) error() error { return r.Err } - -func makeTrackCargoEndpoint(ts Service) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(trackCargoRequest) - c, err := ts.Track(req.ID) - return trackCargoResponse{Cargo: &c, Err: err}, nil - } -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/tracking/instrumenting.go b/vendor/github.com/go-kit/kit/examples/shipping/tracking/instrumenting.go deleted file mode 100644 index f5dc018b..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/tracking/instrumenting.go +++ /dev/null @@ -1,31 +0,0 @@ -package tracking - -import ( - "time" - - "github.com/go-kit/kit/metrics" -) - -type instrumentingService struct { - requestCount metrics.Counter - requestLatency metrics.Histogram - Service -} - -// NewInstrumentingService returns an instance of an instrumenting Service. -func NewInstrumentingService(counter metrics.Counter, latency metrics.Histogram, s Service) Service { - return &instrumentingService{ - requestCount: counter, - requestLatency: latency, - Service: s, - } -} - -func (s *instrumentingService) Track(id string) (Cargo, error) { - defer func(begin time.Time) { - s.requestCount.With("method", "track").Add(1) - s.requestLatency.With("method", "track").Observe(time.Since(begin).Seconds()) - }(time.Now()) - - return s.Service.Track(id) -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/tracking/logging.go b/vendor/github.com/go-kit/kit/examples/shipping/tracking/logging.go deleted file mode 100644 index 584aeaa4..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/tracking/logging.go +++ /dev/null @@ -1,24 +0,0 @@ -package tracking - -import ( - "time" - - "github.com/go-kit/kit/log" -) - -type loggingService struct { - logger log.Logger - Service -} - -// NewLoggingService returns a new instance of a logging Service. -func NewLoggingService(logger log.Logger, s Service) Service { - return &loggingService{logger, s} -} - -func (s *loggingService) Track(id string) (c Cargo, err error) { - defer func(begin time.Time) { - s.logger.Log("method", "track", "tracking_id", id, "took", time.Since(begin), "err", err) - }(time.Now()) - return s.Service.Track(id) -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/tracking/service.go b/vendor/github.com/go-kit/kit/examples/shipping/tracking/service.go deleted file mode 100644 index b0e360b2..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/tracking/service.go +++ /dev/null @@ -1,163 +0,0 @@ -// Package tracking provides the use-case of tracking a cargo. Used by views -// facing the end-user. -package tracking - -import ( - "errors" - "fmt" - "strings" - "time" - - "github.com/go-kit/kit/examples/shipping/cargo" -) - -// ErrInvalidArgument is returned when one or more arguments are invalid. -var ErrInvalidArgument = errors.New("invalid argument") - -// Service is the interface that provides the basic Track method. -type Service interface { - // Track returns a cargo matching a tracking ID. - Track(id string) (Cargo, error) -} - -type service struct { - cargos cargo.Repository - handlingEvents cargo.HandlingEventRepository -} - -func (s *service) Track(id string) (Cargo, error) { - if id == "" { - return Cargo{}, ErrInvalidArgument - } - c, err := s.cargos.Find(cargo.TrackingID(id)) - if err != nil { - return Cargo{}, err - } - return assemble(c, s.handlingEvents), nil -} - -// NewService returns a new instance of the default Service. -func NewService(cargos cargo.Repository, events cargo.HandlingEventRepository) Service { - return &service{ - cargos: cargos, - handlingEvents: events, - } -} - -// Cargo is a read model for tracking views. -type Cargo struct { - TrackingID string `json:"tracking_id"` - StatusText string `json:"status_text"` - Origin string `json:"origin"` - Destination string `json:"destination"` - ETA time.Time `json:"eta"` - NextExpectedActivity string `json:"next_expected_activity"` - ArrivalDeadline time.Time `json:"arrival_deadline"` - Events []Event `json:"events"` -} - -// Leg is a read model for booking views. -type Leg struct { - VoyageNumber string `json:"voyage_number"` - From string `json:"from"` - To string `json:"to"` - LoadTime time.Time `json:"load_time"` - UnloadTime time.Time `json:"unload_time"` -} - -// Event is a read model for tracking views. -type Event struct { - Description string `json:"description"` - Expected bool `json:"expected"` -} - -func assemble(c *cargo.Cargo, events cargo.HandlingEventRepository) Cargo { - return Cargo{ - TrackingID: string(c.TrackingID), - Origin: string(c.Origin), - Destination: string(c.RouteSpecification.Destination), - ETA: c.Delivery.ETA, - NextExpectedActivity: nextExpectedActivity(c), - ArrivalDeadline: c.RouteSpecification.ArrivalDeadline, - StatusText: assembleStatusText(c), - Events: assembleEvents(c, events), - } -} - -func assembleLegs(c cargo.Cargo) []Leg { - var legs []Leg - for _, l := range c.Itinerary.Legs { - legs = append(legs, Leg{ - VoyageNumber: string(l.VoyageNumber), - From: string(l.LoadLocation), - To: string(l.UnloadLocation), - LoadTime: l.LoadTime, - UnloadTime: l.UnloadTime, - }) - } - return legs -} - -func nextExpectedActivity(c *cargo.Cargo) string { - a := c.Delivery.NextExpectedActivity - prefix := "Next expected activity is to" - - switch a.Type { - case cargo.Load: - return fmt.Sprintf("%s %s cargo onto voyage %s in %s.", prefix, strings.ToLower(a.Type.String()), a.VoyageNumber, a.Location) - case cargo.Unload: - return fmt.Sprintf("%s %s cargo off of voyage %s in %s.", prefix, strings.ToLower(a.Type.String()), a.VoyageNumber, a.Location) - case cargo.NotHandled: - return "There are currently no expected activities for this cargo." - } - - return fmt.Sprintf("%s %s cargo in %s.", prefix, strings.ToLower(a.Type.String()), a.Location) -} - -func assembleStatusText(c *cargo.Cargo) string { - switch c.Delivery.TransportStatus { - case cargo.NotReceived: - return "Not received" - case cargo.InPort: - return fmt.Sprintf("In port %s", c.Delivery.LastKnownLocation) - case cargo.OnboardCarrier: - return fmt.Sprintf("Onboard voyage %s", c.Delivery.CurrentVoyage) - case cargo.Claimed: - return "Claimed" - default: - return "Unknown" - } -} - -func assembleEvents(c *cargo.Cargo, handlingEvents cargo.HandlingEventRepository) []Event { - h := handlingEvents.QueryHandlingHistory(c.TrackingID) - - var events []Event - for _, e := range h.HandlingEvents { - var description string - - switch e.Activity.Type { - case cargo.NotHandled: - description = "Cargo has not yet been received." - case cargo.Receive: - description = fmt.Sprintf("Received in %s, at %s", e.Activity.Location, time.Now().Format(time.RFC3339)) - case cargo.Load: - description = fmt.Sprintf("Loaded onto voyage %s in %s, at %s.", e.Activity.VoyageNumber, e.Activity.Location, time.Now().Format(time.RFC3339)) - case cargo.Unload: - description = fmt.Sprintf("Unloaded off voyage %s in %s, at %s.", e.Activity.VoyageNumber, e.Activity.Location, time.Now().Format(time.RFC3339)) - case cargo.Claim: - description = fmt.Sprintf("Claimed in %s, at %s.", e.Activity.Location, time.Now().Format(time.RFC3339)) - case cargo.Customs: - description = fmt.Sprintf("Cleared customs in %s, at %s.", e.Activity.Location, time.Now().Format(time.RFC3339)) - default: - description = "[Unknown status]" - } - - events = append(events, Event{ - Description: description, - Expected: c.Itinerary.IsExpected(e), - }) - } - - return events -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/tracking/transport.go b/vendor/github.com/go-kit/kit/examples/shipping/tracking/transport.go deleted file mode 100644 index 32db9716..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/tracking/transport.go +++ /dev/null @@ -1,74 +0,0 @@ -package tracking - -import ( - "context" - "encoding/json" - "errors" - "net/http" - - "github.com/gorilla/mux" - - kitlog "github.com/go-kit/kit/log" - kithttp "github.com/go-kit/kit/transport/http" - - "github.com/go-kit/kit/examples/shipping/cargo" -) - -// MakeHandler returns a handler for the tracking service. -func MakeHandler(ts Service, logger kitlog.Logger) http.Handler { - r := mux.NewRouter() - - opts := []kithttp.ServerOption{ - kithttp.ServerErrorLogger(logger), - kithttp.ServerErrorEncoder(encodeError), - } - - trackCargoHandler := kithttp.NewServer( - makeTrackCargoEndpoint(ts), - decodeTrackCargoRequest, - encodeResponse, - opts..., - ) - - r.Handle("/tracking/v1/cargos/{id}", trackCargoHandler).Methods("GET") - - return r -} - -func decodeTrackCargoRequest(_ context.Context, r *http.Request) (interface{}, error) { - vars := mux.Vars(r) - id, ok := vars["id"] - if !ok { - return nil, errors.New("bad route") - } - return trackCargoRequest{ID: id}, nil -} - -func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { - if e, ok := response.(errorer); ok && e.error() != nil { - encodeError(ctx, e.error(), w) - return nil - } - w.Header().Set("Content-Type", "application/json; charset=utf-8") - return json.NewEncoder(w).Encode(response) -} - -type errorer interface { - error() error -} - -// encode errors from business-logic -func encodeError(_ context.Context, err error, w http.ResponseWriter) { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - switch err { - case cargo.ErrUnknown: - w.WriteHeader(http.StatusNotFound) - case ErrInvalidArgument: - w.WriteHeader(http.StatusBadRequest) - default: - w.WriteHeader(http.StatusInternalServerError) - } - json.NewEncoder(w).Encode(map[string]interface{}{ - "error": err.Error(), - }) -} diff --git a/vendor/github.com/go-kit/kit/examples/shipping/voyage/sample_voyages.go b/vendor/github.com/go-kit/kit/examples/shipping/voyage/sample_voyages.go deleted file mode 100644 index 751f5885..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/voyage/sample_voyages.go +++ /dev/null @@ -1,40 +0,0 @@ -package voyage - -import "github.com/go-kit/kit/examples/shipping/location" - -// A set of sample voyages. -var ( - V100 = New("V100", Schedule{ - []CarrierMovement{ - {DepartureLocation: location.CNHKG, ArrivalLocation: location.JNTKO}, - {DepartureLocation: location.JNTKO, ArrivalLocation: location.USNYC}, - }, - }) - - V300 = New("V300", Schedule{ - []CarrierMovement{ - {DepartureLocation: location.JNTKO, ArrivalLocation: location.NLRTM}, - {DepartureLocation: location.NLRTM, ArrivalLocation: location.DEHAM}, - {DepartureLocation: location.DEHAM, ArrivalLocation: location.AUMEL}, - {DepartureLocation: location.AUMEL, ArrivalLocation: location.JNTKO}, - }, - }) - - V400 = New("V400", Schedule{ - []CarrierMovement{ - {DepartureLocation: location.DEHAM, ArrivalLocation: location.SESTO}, - {DepartureLocation: location.SESTO, ArrivalLocation: location.FIHEL}, - {DepartureLocation: location.FIHEL, ArrivalLocation: location.DEHAM}, - }, - }) -) - -// These voyages are hard-coded into the current pathfinder. Make sure -// they exist. -var ( - V0100S = New("0100S", Schedule{[]CarrierMovement{}}) - V0200T = New("0200T", Schedule{[]CarrierMovement{}}) - V0300A = New("0300A", Schedule{[]CarrierMovement{}}) - V0301S = New("0301S", Schedule{[]CarrierMovement{}}) - V0400S = New("0400S", Schedule{[]CarrierMovement{}}) -) diff --git a/vendor/github.com/go-kit/kit/examples/shipping/voyage/voyage.go b/vendor/github.com/go-kit/kit/examples/shipping/voyage/voyage.go deleted file mode 100644 index 37366af4..00000000 --- a/vendor/github.com/go-kit/kit/examples/shipping/voyage/voyage.go +++ /dev/null @@ -1,44 +0,0 @@ -// Package voyage provides the Voyage aggregate. -package voyage - -import ( - "errors" - "time" - - "github.com/go-kit/kit/examples/shipping/location" -) - -// Number uniquely identifies a particular Voyage. -type Number string - -// Voyage is a uniquely identifiable series of carrier movements. -type Voyage struct { - Number Number - Schedule Schedule -} - -// New creates a voyage with a voyage number and a provided schedule. -func New(n Number, s Schedule) *Voyage { - return &Voyage{Number: n, Schedule: s} -} - -// Schedule describes a voyage schedule. -type Schedule struct { - CarrierMovements []CarrierMovement -} - -// CarrierMovement is a vessel voyage from one location to another. -type CarrierMovement struct { - DepartureLocation location.UNLocode - ArrivalLocation location.UNLocode - DepartureTime time.Time - ArrivalTime time.Time -} - -// ErrUnknown is used when a voyage could not be found. -var ErrUnknown = errors.New("unknown voyage") - -// Repository provides access a voyage store. -type Repository interface { - Find(Number) (*Voyage, error) -} diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc1/main.go b/vendor/github.com/go-kit/kit/examples/stringsvc1/main.go deleted file mode 100644 index 03fc7939..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc1/main.go +++ /dev/null @@ -1,111 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "errors" - "log" - "net/http" - "strings" - - "github.com/go-kit/kit/endpoint" - httptransport "github.com/go-kit/kit/transport/http" -) - -// StringService provides operations on strings. -type StringService interface { - Uppercase(string) (string, error) - Count(string) int -} - -type stringService struct{} - -func (stringService) Uppercase(s string) (string, error) { - if s == "" { - return "", ErrEmpty - } - return strings.ToUpper(s), nil -} - -func (stringService) Count(s string) int { - return len(s) -} - -func main() { - svc := stringService{} - - uppercaseHandler := httptransport.NewServer( - makeUppercaseEndpoint(svc), - decodeUppercaseRequest, - encodeResponse, - ) - - countHandler := httptransport.NewServer( - makeCountEndpoint(svc), - decodeCountRequest, - encodeResponse, - ) - - http.Handle("/uppercase", uppercaseHandler) - http.Handle("/count", countHandler) - log.Fatal(http.ListenAndServe(":8080", nil)) -} - -func makeUppercaseEndpoint(svc StringService) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(uppercaseRequest) - v, err := svc.Uppercase(req.S) - if err != nil { - return uppercaseResponse{v, err.Error()}, nil - } - return uppercaseResponse{v, ""}, nil - } -} - -func makeCountEndpoint(svc StringService) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(countRequest) - v := svc.Count(req.S) - return countResponse{v}, nil - } -} - -func decodeUppercaseRequest(_ context.Context, r *http.Request) (interface{}, error) { - var request uppercaseRequest - if err := json.NewDecoder(r.Body).Decode(&request); err != nil { - return nil, err - } - return request, nil -} - -func decodeCountRequest(_ context.Context, r *http.Request) (interface{}, error) { - var request countRequest - if err := json.NewDecoder(r.Body).Decode(&request); err != nil { - return nil, err - } - return request, nil -} - -func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error { - return json.NewEncoder(w).Encode(response) -} - -type uppercaseRequest struct { - S string `json:"s"` -} - -type uppercaseResponse struct { - V string `json:"v"` - Err string `json:"err,omitempty"` // errors don't define JSON marshaling -} - -type countRequest struct { - S string `json:"s"` -} - -type countResponse struct { - V int `json:"v"` -} - -// ErrEmpty is returned when an input string is empty. -var ErrEmpty = errors.New("empty string") diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc2/instrumenting.go b/vendor/github.com/go-kit/kit/examples/stringsvc2/instrumenting.go deleted file mode 100644 index 675617d9..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc2/instrumenting.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/go-kit/kit/metrics" -) - -type instrumentingMiddleware struct { - requestCount metrics.Counter - requestLatency metrics.Histogram - countResult metrics.Histogram - next StringService -} - -func (mw instrumentingMiddleware) Uppercase(s string) (output string, err error) { - defer func(begin time.Time) { - lvs := []string{"method", "uppercase", "error", fmt.Sprint(err != nil)} - mw.requestCount.With(lvs...).Add(1) - mw.requestLatency.With(lvs...).Observe(time.Since(begin).Seconds()) - }(time.Now()) - - output, err = mw.next.Uppercase(s) - return -} - -func (mw instrumentingMiddleware) Count(s string) (n int) { - defer func(begin time.Time) { - lvs := []string{"method", "count", "error", "false"} - mw.requestCount.With(lvs...).Add(1) - mw.requestLatency.With(lvs...).Observe(time.Since(begin).Seconds()) - mw.countResult.Observe(float64(n)) - }(time.Now()) - - n = mw.next.Count(s) - return -} diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc2/logging.go b/vendor/github.com/go-kit/kit/examples/stringsvc2/logging.go deleted file mode 100644 index b958f3b6..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc2/logging.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "time" - - "github.com/go-kit/kit/log" -) - -type loggingMiddleware struct { - logger log.Logger - next StringService -} - -func (mw loggingMiddleware) Uppercase(s string) (output string, err error) { - defer func(begin time.Time) { - _ = mw.logger.Log( - "method", "uppercase", - "input", s, - "output", output, - "err", err, - "took", time.Since(begin), - ) - }(time.Now()) - - output, err = mw.next.Uppercase(s) - return -} - -func (mw loggingMiddleware) Count(s string) (n int) { - defer func(begin time.Time) { - _ = mw.logger.Log( - "method", "count", - "input", s, - "n", n, - "took", time.Since(begin), - ) - }(time.Now()) - - n = mw.next.Count(s) - return -} diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc2/main.go b/vendor/github.com/go-kit/kit/examples/stringsvc2/main.go deleted file mode 100644 index 60544f27..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc2/main.go +++ /dev/null @@ -1,60 +0,0 @@ -package main - -import ( - "net/http" - "os" - - stdprometheus "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" - - "github.com/go-kit/kit/log" - kitprometheus "github.com/go-kit/kit/metrics/prometheus" - httptransport "github.com/go-kit/kit/transport/http" -) - -func main() { - logger := log.NewLogfmtLogger(os.Stderr) - - fieldKeys := []string{"method", "error"} - requestCount := kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{ - Namespace: "my_group", - Subsystem: "string_service", - Name: "request_count", - Help: "Number of requests received.", - }, fieldKeys) - requestLatency := kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ - Namespace: "my_group", - Subsystem: "string_service", - Name: "request_latency_microseconds", - Help: "Total duration of requests in microseconds.", - }, fieldKeys) - countResult := kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ - Namespace: "my_group", - Subsystem: "string_service", - Name: "count_result", - Help: "The result of each count method.", - }, []string{}) // no fields here - - var svc StringService - svc = stringService{} - svc = loggingMiddleware{logger, svc} - svc = instrumentingMiddleware{requestCount, requestLatency, countResult, svc} - - uppercaseHandler := httptransport.NewServer( - makeUppercaseEndpoint(svc), - decodeUppercaseRequest, - encodeResponse, - ) - - countHandler := httptransport.NewServer( - makeCountEndpoint(svc), - decodeCountRequest, - encodeResponse, - ) - - http.Handle("/uppercase", uppercaseHandler) - http.Handle("/count", countHandler) - http.Handle("/metrics", promhttp.Handler()) - logger.Log("msg", "HTTP", "addr", ":8080") - logger.Log("err", http.ListenAndServe(":8080", nil)) -} diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc2/service.go b/vendor/github.com/go-kit/kit/examples/stringsvc2/service.go deleted file mode 100644 index 1da2f3eb..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc2/service.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "errors" - "strings" -) - -// StringService provides operations on strings. -type StringService interface { - Uppercase(string) (string, error) - Count(string) int -} - -type stringService struct{} - -func (stringService) Uppercase(s string) (string, error) { - if s == "" { - return "", ErrEmpty - } - return strings.ToUpper(s), nil -} - -func (stringService) Count(s string) int { - return len(s) -} - -// ErrEmpty is returned when an input string is empty. -var ErrEmpty = errors.New("empty string") diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc2/transport.go b/vendor/github.com/go-kit/kit/examples/stringsvc2/transport.go deleted file mode 100644 index 297b3ffe..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc2/transport.go +++ /dev/null @@ -1,65 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "net/http" - - "github.com/go-kit/kit/endpoint" -) - -func makeUppercaseEndpoint(svc StringService) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(uppercaseRequest) - v, err := svc.Uppercase(req.S) - if err != nil { - return uppercaseResponse{v, err.Error()}, nil - } - return uppercaseResponse{v, ""}, nil - } -} - -func makeCountEndpoint(svc StringService) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(countRequest) - v := svc.Count(req.S) - return countResponse{v}, nil - } -} - -func decodeUppercaseRequest(_ context.Context, r *http.Request) (interface{}, error) { - var request uppercaseRequest - if err := json.NewDecoder(r.Body).Decode(&request); err != nil { - return nil, err - } - return request, nil -} - -func decodeCountRequest(_ context.Context, r *http.Request) (interface{}, error) { - var request countRequest - if err := json.NewDecoder(r.Body).Decode(&request); err != nil { - return nil, err - } - return request, nil -} - -func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error { - return json.NewEncoder(w).Encode(response) -} - -type uppercaseRequest struct { - S string `json:"s"` -} - -type uppercaseResponse struct { - V string `json:"v"` - Err string `json:"err,omitempty"` -} - -type countRequest struct { - S string `json:"s"` -} - -type countResponse struct { - V int `json:"v"` -} diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc3/instrumenting.go b/vendor/github.com/go-kit/kit/examples/stringsvc3/instrumenting.go deleted file mode 100644 index b21c016c..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc3/instrumenting.go +++ /dev/null @@ -1,48 +0,0 @@ -package main - -import ( - "fmt" - "time" - - "github.com/go-kit/kit/metrics" -) - -func instrumentingMiddleware( - requestCount metrics.Counter, - requestLatency metrics.Histogram, - countResult metrics.Histogram, -) ServiceMiddleware { - return func(next StringService) StringService { - return instrmw{requestCount, requestLatency, countResult, next} - } -} - -type instrmw struct { - requestCount metrics.Counter - requestLatency metrics.Histogram - countResult metrics.Histogram - StringService -} - -func (mw instrmw) Uppercase(s string) (output string, err error) { - defer func(begin time.Time) { - lvs := []string{"method", "uppercase", "error", fmt.Sprint(err != nil)} - mw.requestCount.With(lvs...).Add(1) - mw.requestLatency.With(lvs...).Observe(time.Since(begin).Seconds()) - }(time.Now()) - - output, err = mw.StringService.Uppercase(s) - return -} - -func (mw instrmw) Count(s string) (n int) { - defer func(begin time.Time) { - lvs := []string{"method", "count", "error", "false"} - mw.requestCount.With(lvs...).Add(1) - mw.requestLatency.With(lvs...).Observe(time.Since(begin).Seconds()) - mw.countResult.Observe(float64(n)) - }(time.Now()) - - n = mw.StringService.Count(s) - return -} diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc3/logging.go b/vendor/github.com/go-kit/kit/examples/stringsvc3/logging.go deleted file mode 100644 index 72a2709d..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc3/logging.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "time" - - "github.com/go-kit/kit/log" -) - -func loggingMiddleware(logger log.Logger) ServiceMiddleware { - return func(next StringService) StringService { - return logmw{logger, next} - } -} - -type logmw struct { - logger log.Logger - StringService -} - -func (mw logmw) Uppercase(s string) (output string, err error) { - defer func(begin time.Time) { - _ = mw.logger.Log( - "method", "uppercase", - "input", s, - "output", output, - "err", err, - "took", time.Since(begin), - ) - }(time.Now()) - - output, err = mw.StringService.Uppercase(s) - return -} - -func (mw logmw) Count(s string) (n int) { - defer func(begin time.Time) { - _ = mw.logger.Log( - "method", "count", - "input", s, - "n", n, - "took", time.Since(begin), - ) - }(time.Now()) - - n = mw.StringService.Count(s) - return -} diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc3/main.go b/vendor/github.com/go-kit/kit/examples/stringsvc3/main.go deleted file mode 100644 index 5cdb43b1..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc3/main.go +++ /dev/null @@ -1,70 +0,0 @@ -package main - -import ( - "context" - "flag" - "net/http" - "os" - - stdprometheus "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" - - "github.com/go-kit/kit/log" - kitprometheus "github.com/go-kit/kit/metrics/prometheus" - httptransport "github.com/go-kit/kit/transport/http" -) - -func main() { - var ( - listen = flag.String("listen", ":8080", "HTTP listen address") - proxy = flag.String("proxy", "", "Optional comma-separated list of URLs to proxy uppercase requests") - ) - flag.Parse() - - var logger log.Logger - logger = log.NewLogfmtLogger(os.Stderr) - logger = log.With(logger, "listen", *listen, "caller", log.DefaultCaller) - - fieldKeys := []string{"method", "error"} - requestCount := kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{ - Namespace: "my_group", - Subsystem: "string_service", - Name: "request_count", - Help: "Number of requests received.", - }, fieldKeys) - requestLatency := kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ - Namespace: "my_group", - Subsystem: "string_service", - Name: "request_latency_microseconds", - Help: "Total duration of requests in microseconds.", - }, fieldKeys) - countResult := kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ - Namespace: "my_group", - Subsystem: "string_service", - Name: "count_result", - Help: "The result of each count method.", - }, []string{}) - - var svc StringService - svc = stringService{} - svc = proxyingMiddleware(context.Background(), *proxy, logger)(svc) - svc = loggingMiddleware(logger)(svc) - svc = instrumentingMiddleware(requestCount, requestLatency, countResult)(svc) - - uppercaseHandler := httptransport.NewServer( - makeUppercaseEndpoint(svc), - decodeUppercaseRequest, - encodeResponse, - ) - countHandler := httptransport.NewServer( - makeCountEndpoint(svc), - decodeCountRequest, - encodeResponse, - ) - - http.Handle("/uppercase", uppercaseHandler) - http.Handle("/count", countHandler) - http.Handle("/metrics", promhttp.Handler()) - logger.Log("msg", "HTTP", "addr", *listen) - logger.Log("err", http.ListenAndServe(*listen, nil)) -} diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc3/proxying.go b/vendor/github.com/go-kit/kit/examples/stringsvc3/proxying.go deleted file mode 100644 index 8b1013f3..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc3/proxying.go +++ /dev/null @@ -1,116 +0,0 @@ -package main - -import ( - "context" - "errors" - "fmt" - "net/url" - "strings" - "time" - - jujuratelimit "github.com/juju/ratelimit" - "github.com/sony/gobreaker" - - "github.com/go-kit/kit/circuitbreaker" - "github.com/go-kit/kit/endpoint" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/ratelimit" - "github.com/go-kit/kit/sd" - "github.com/go-kit/kit/sd/lb" - httptransport "github.com/go-kit/kit/transport/http" -) - -func proxyingMiddleware(ctx context.Context, instances string, logger log.Logger) ServiceMiddleware { - // If instances is empty, don't proxy. - if instances == "" { - logger.Log("proxy_to", "none") - return func(next StringService) StringService { return next } - } - - // Set some parameters for our client. - var ( - qps = 100 // beyond which we will return an error - maxAttempts = 3 // per request, before giving up - maxTime = 250 * time.Millisecond // wallclock time, before giving up - ) - - // Otherwise, construct an endpoint for each instance in the list, and add - // it to a fixed set of endpoints. In a real service, rather than doing this - // by hand, you'd probably use package sd's support for your service - // discovery system. - var ( - instanceList = split(instances) - endpointer sd.FixedEndpointer - ) - logger.Log("proxy_to", fmt.Sprint(instanceList)) - for _, instance := range instanceList { - var e endpoint.Endpoint - e = makeUppercaseProxy(ctx, instance) - e = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{}))(e) - e = ratelimit.NewTokenBucketLimiter(jujuratelimit.NewBucketWithRate(float64(qps), int64(qps)))(e) - endpointer = append(endpointer, e) - } - - // Now, build a single, retrying, load-balancing endpoint out of all of - // those individual endpoints. - balancer := lb.NewRoundRobin(endpointer) - retry := lb.Retry(maxAttempts, maxTime, balancer) - - // And finally, return the ServiceMiddleware, implemented by proxymw. - return func(next StringService) StringService { - return proxymw{ctx, next, retry} - } -} - -// proxymw implements StringService, forwarding Uppercase requests to the -// provided endpoint, and serving all other (i.e. Count) requests via the -// next StringService. -type proxymw struct { - ctx context.Context - next StringService // Serve most requests via this service... - uppercase endpoint.Endpoint // ...except Uppercase, which gets served by this endpoint -} - -func (mw proxymw) Count(s string) int { - return mw.next.Count(s) -} - -func (mw proxymw) Uppercase(s string) (string, error) { - response, err := mw.uppercase(mw.ctx, uppercaseRequest{S: s}) - if err != nil { - return "", err - } - - resp := response.(uppercaseResponse) - if resp.Err != "" { - return resp.V, errors.New(resp.Err) - } - return resp.V, nil -} - -func makeUppercaseProxy(ctx context.Context, instance string) endpoint.Endpoint { - if !strings.HasPrefix(instance, "http") { - instance = "http://" + instance - } - u, err := url.Parse(instance) - if err != nil { - panic(err) - } - if u.Path == "" { - u.Path = "/uppercase" - } - return httptransport.NewClient( - "GET", - u, - encodeRequest, - decodeUppercaseResponse, - ).Endpoint() -} - -func split(s string) []string { - a := strings.Split(s, ",") - for i := range a { - a[i] = strings.TrimSpace(a[i]) - } - return a -} diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc3/service.go b/vendor/github.com/go-kit/kit/examples/stringsvc3/service.go deleted file mode 100644 index 7e1773a9..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc3/service.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "errors" - "strings" -) - -// StringService provides operations on strings. -type StringService interface { - Uppercase(string) (string, error) - Count(string) int -} - -type stringService struct{} - -func (stringService) Uppercase(s string) (string, error) { - if s == "" { - return "", ErrEmpty - } - return strings.ToUpper(s), nil -} - -func (stringService) Count(s string) int { - return len(s) -} - -// ErrEmpty is returned when an input string is empty. -var ErrEmpty = errors.New("empty string") - -// ServiceMiddleware is a chainable behavior modifier for StringService. -type ServiceMiddleware func(StringService) StringService diff --git a/vendor/github.com/go-kit/kit/examples/stringsvc3/transport.go b/vendor/github.com/go-kit/kit/examples/stringsvc3/transport.go deleted file mode 100644 index c17a055c..00000000 --- a/vendor/github.com/go-kit/kit/examples/stringsvc3/transport.go +++ /dev/null @@ -1,84 +0,0 @@ -package main - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - "net/http" - - "github.com/go-kit/kit/endpoint" -) - -func makeUppercaseEndpoint(svc StringService) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(uppercaseRequest) - v, err := svc.Uppercase(req.S) - if err != nil { - return uppercaseResponse{v, err.Error()}, nil - } - return uppercaseResponse{v, ""}, nil - } -} - -func makeCountEndpoint(svc StringService) endpoint.Endpoint { - return func(ctx context.Context, request interface{}) (interface{}, error) { - req := request.(countRequest) - v := svc.Count(req.S) - return countResponse{v}, nil - } -} - -func decodeUppercaseRequest(_ context.Context, r *http.Request) (interface{}, error) { - var request uppercaseRequest - if err := json.NewDecoder(r.Body).Decode(&request); err != nil { - return nil, err - } - return request, nil -} - -func decodeCountRequest(_ context.Context, r *http.Request) (interface{}, error) { - var request countRequest - if err := json.NewDecoder(r.Body).Decode(&request); err != nil { - return nil, err - } - return request, nil -} - -func decodeUppercaseResponse(_ context.Context, r *http.Response) (interface{}, error) { - var response uppercaseResponse - if err := json.NewDecoder(r.Body).Decode(&response); err != nil { - return nil, err - } - return response, nil -} - -func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error { - return json.NewEncoder(w).Encode(response) -} - -func encodeRequest(_ context.Context, r *http.Request, request interface{}) error { - var buf bytes.Buffer - if err := json.NewEncoder(&buf).Encode(request); err != nil { - return err - } - r.Body = ioutil.NopCloser(&buf) - return nil -} - -type uppercaseRequest struct { - S string `json:"s"` -} - -type uppercaseResponse struct { - V string `json:"v"` - Err string `json:"err,omitempty"` -} - -type countRequest struct { - S string `json:"s"` -} - -type countResponse struct { - V int `json:"v"` -} diff --git a/vendor/github.com/go-kit/kit/lint b/vendor/github.com/go-kit/kit/lint deleted file mode 100755 index 12e30727..00000000 --- a/vendor/github.com/go-kit/kit/lint +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash - -set -o errexit -set -o nounset -set -o pipefail - -if [ ! $(command -v gometalinter) ] -then - go get github.com/alecthomas/gometalinter - gometalinter --update --install -fi - -time gometalinter \ - --exclude='error return value not checked.*(Close|Log|Print).*\(errcheck\)$' \ - --exclude='.*_test\.go:.*error return value not checked.*\(errcheck\)$' \ - --exclude='/thrift/' \ - --exclude='/pb/' \ - --exclude='no args in Log call \(vet\)' \ - --disable=dupl \ - --disable=aligncheck \ - --disable=gotype \ - --cyclo-over=20 \ - --tests \ - --concurrency=2 \ - --deadline=300s \ - ./... diff --git a/vendor/github.com/go-kit/kit/log/README.md b/vendor/github.com/go-kit/kit/log/README.md deleted file mode 100644 index 7222f800..00000000 --- a/vendor/github.com/go-kit/kit/log/README.md +++ /dev/null @@ -1,147 +0,0 @@ -# package log - -`package log` provides a minimal interface for structured logging in services. -It may be wrapped to encode conventions, enforce type-safety, provide leveled -logging, and so on. It can be used for both typical application log events, -and log-structured data streams. - -## Structured logging - -Structured logging is, basically, conceding to the reality that logs are -_data_, and warrant some level of schematic rigor. Using a stricter, -key/value-oriented message format for our logs, containing contextual and -semantic information, makes it much easier to get insight into the -operational activity of the systems we build. Consequently, `package log` is -of the strong belief that "[the benefits of structured logging outweigh the -minimal effort involved](https://www.thoughtworks.com/radar/techniques/structured-logging)". - -Migrating from unstructured to structured logging is probably a lot easier -than you'd expect. - -```go -// Unstructured -log.Printf("HTTP server listening on %s", addr) - -// Structured -logger.Log("transport", "HTTP", "addr", addr, "msg", "listening") -``` - -## Usage - -### Typical application logging - -```go -w := log.NewSyncWriter(os.Stderr) -logger := log.NewLogfmtLogger(w) -logger.Log("question", "what is the meaning of life?", "answer", 42) - -// Output: -// question="what is the meaning of life?" answer=42 -``` - -### Contextual Loggers - -```go -func main() { - var logger log.Logger - logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) - logger = log.With(logger, "instance_id", 123) - - logger.Log("msg", "starting") - NewWorker(log.With(logger, "component", "worker")).Run() - NewSlacker(log.With(logger, "component", "slacker")).Run() -} - -// Output: -// instance_id=123 msg=starting -// instance_id=123 component=worker msg=running -// instance_id=123 component=slacker msg=running -``` - -### Interact with stdlib logger - -Redirect stdlib logger to Go kit logger. - -```go -import ( - "os" - stdlog "log" - kitlog "github.com/go-kit/kit/log" -) - -func main() { - logger := kitlog.NewJSONLogger(kitlog.NewSyncWriter(os.Stdout)) - stdlog.SetOutput(kitlog.NewStdlibAdapter(logger)) - stdlog.Print("I sure like pie") -} - -// Output: -// {"msg":"I sure like pie","ts":"2016/01/01 12:34:56"} -``` - -Or, if, for legacy reasons, you need to pipe all of your logging through the -stdlib log package, you can redirect Go kit logger to the stdlib logger. - -```go -logger := kitlog.NewLogfmtLogger(kitlog.StdlibWriter{}) -logger.Log("legacy", true, "msg", "at least it's something") - -// Output: -// 2016/01/01 12:34:56 legacy=true msg="at least it's something" -``` - -### Timestamps and callers - -```go -var logger log.Logger -logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) -logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) - -logger.Log("msg", "hello") - -// Output: -// ts=2016-01-01T12:34:56Z caller=main.go:15 msg=hello -``` - -## Supported output formats - -- [Logfmt](https://brandur.org/logfmt) ([see also](https://blog.codeship.com/logfmt-a-log-format-thats-easy-to-read-and-write)) -- JSON - -## Enhancements - -`package log` is centered on the one-method Logger interface. - -```go -type Logger interface { - Log(keyvals ...interface{}) error -} -``` - -This interface, and its supporting code like is the product of much iteration -and evaluation. For more details on the evolution of the Logger interface, -see [The Hunt for a Logger Interface](http://go-talks.appspot.com/github.com/ChrisHines/talks/structured-logging/structured-logging.slide#1), -a talk by [Chris Hines](https://github.com/ChrisHines). -Also, please see -[#63](https://github.com/go-kit/kit/issues/63), -[#76](https://github.com/go-kit/kit/pull/76), -[#131](https://github.com/go-kit/kit/issues/131), -[#157](https://github.com/go-kit/kit/pull/157), -[#164](https://github.com/go-kit/kit/issues/164), and -[#252](https://github.com/go-kit/kit/pull/252) -to review historical conversations about package log and the Logger interface. - -Value-add packages and suggestions, -like improvements to [the leveled logger](https://godoc.org/github.com/go-kit/kit/log/level), -are of course welcome. Good proposals should - -- Be composable with [contextual loggers](https://godoc.org/github.com/go-kit/kit/log#With), -- Not break the behavior of [log.Caller](https://godoc.org/github.com/go-kit/kit/log#Caller) in any wrapped contextual loggers, and -- Be friendly to packages that accept only an unadorned log.Logger. - -## Benchmarks & comparisons - -There are a few Go logging benchmarks and comparisons that include Go kit's package log. - -- [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench) includes kit/log -- [uber-common/zap](https://github.com/uber-common/zap), a zero-alloc logging library, includes a comparison with kit/log diff --git a/vendor/github.com/go-kit/kit/log/benchmark_test.go b/vendor/github.com/go-kit/kit/log/benchmark_test.go deleted file mode 100644 index 126bfa5a..00000000 --- a/vendor/github.com/go-kit/kit/log/benchmark_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package log_test - -import ( - "testing" - - "github.com/go-kit/kit/log" -) - -func benchmarkRunner(b *testing.B, logger log.Logger, f func(log.Logger)) { - lc := log.With(logger, "common_key", "common_value") - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - f(lc) - } -} - -var ( - baseMessage = func(logger log.Logger) { logger.Log("foo_key", "foo_value") } - withMessage = func(logger log.Logger) { log.With(logger, "a", "b").Log("c", "d") } -) diff --git a/vendor/github.com/go-kit/kit/log/concurrency_test.go b/vendor/github.com/go-kit/kit/log/concurrency_test.go deleted file mode 100644 index 95a749e7..00000000 --- a/vendor/github.com/go-kit/kit/log/concurrency_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package log_test - -import ( - "math" - "testing" - - "github.com/go-kit/kit/log" -) - -// These test are designed to be run with the race detector. - -func testConcurrency(t *testing.T, logger log.Logger, total int) { - n := int(math.Sqrt(float64(total))) - share := total / n - - errC := make(chan error, n) - - for i := 0; i < n; i++ { - go func() { - errC <- spam(logger, share) - }() - } - - for i := 0; i < n; i++ { - err := <-errC - if err != nil { - t.Fatalf("concurrent logging error: %v", err) - } - } -} - -func spam(logger log.Logger, count int) error { - for i := 0; i < count; i++ { - err := logger.Log("key", i) - if err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/go-kit/kit/log/deprecated_levels/levels.go b/vendor/github.com/go-kit/kit/log/deprecated_levels/levels.go deleted file mode 100644 index a0342127..00000000 --- a/vendor/github.com/go-kit/kit/log/deprecated_levels/levels.go +++ /dev/null @@ -1,127 +0,0 @@ -package levels - -import "github.com/go-kit/kit/log" - -// Levels provides a leveled logging wrapper around a logger. It has five -// levels: debug, info, warning (warn), error, and critical (crit). If you -// want a different set of levels, you can create your own levels type very -// easily, and you can elide the configuration. -type Levels struct { - logger log.Logger - levelKey string - - // We have a choice between storing level values in string fields or - // making a separate context for each level. When using string fields the - // Log method must combine the base context, the level data, and the - // logged keyvals; but the With method only requires updating one context. - // If we instead keep a separate context for each level the Log method - // must only append the new keyvals; but the With method would have to - // update all five contexts. - - // Roughly speaking, storing multiple contexts breaks even if the ratio of - // Log/With calls is more than the number of levels. We have chosen to - // make the With method cheap and the Log method a bit more costly because - // we do not expect most applications to Log more than five times for each - // call to With. - - debugValue string - infoValue string - warnValue string - errorValue string - critValue string -} - -// New creates a new leveled logger, wrapping the passed logger. -func New(logger log.Logger, options ...Option) Levels { - l := Levels{ - logger: logger, - levelKey: "level", - - debugValue: "debug", - infoValue: "info", - warnValue: "warn", - errorValue: "error", - critValue: "crit", - } - for _, option := range options { - option(&l) - } - return l -} - -// With returns a new leveled logger that includes keyvals in all log events. -func (l Levels) With(keyvals ...interface{}) Levels { - return Levels{ - logger: log.With(l.logger, keyvals...), - levelKey: l.levelKey, - debugValue: l.debugValue, - infoValue: l.infoValue, - warnValue: l.warnValue, - errorValue: l.errorValue, - critValue: l.critValue, - } -} - -// Debug returns a debug level logger. -func (l Levels) Debug() log.Logger { - return log.WithPrefix(l.logger, l.levelKey, l.debugValue) -} - -// Info returns an info level logger. -func (l Levels) Info() log.Logger { - return log.WithPrefix(l.logger, l.levelKey, l.infoValue) -} - -// Warn returns a warning level logger. -func (l Levels) Warn() log.Logger { - return log.WithPrefix(l.logger, l.levelKey, l.warnValue) -} - -// Error returns an error level logger. -func (l Levels) Error() log.Logger { - return log.WithPrefix(l.logger, l.levelKey, l.errorValue) -} - -// Crit returns a critical level logger. -func (l Levels) Crit() log.Logger { - return log.WithPrefix(l.logger, l.levelKey, l.critValue) -} - -// Option sets a parameter for leveled loggers. -type Option func(*Levels) - -// Key sets the key for the field used to indicate log level. By default, -// the key is "level". -func Key(key string) Option { - return func(l *Levels) { l.levelKey = key } -} - -// DebugValue sets the value for the field used to indicate the debug log -// level. By default, the value is "debug". -func DebugValue(value string) Option { - return func(l *Levels) { l.debugValue = value } -} - -// InfoValue sets the value for the field used to indicate the info log level. -// By default, the value is "info". -func InfoValue(value string) Option { - return func(l *Levels) { l.infoValue = value } -} - -// WarnValue sets the value for the field used to indicate the warning log -// level. By default, the value is "warn". -func WarnValue(value string) Option { - return func(l *Levels) { l.warnValue = value } -} - -// ErrorValue sets the value for the field used to indicate the error log -// level. By default, the value is "error". -func ErrorValue(value string) Option { - return func(l *Levels) { l.errorValue = value } -} - -// CritValue sets the value for the field used to indicate the critical log -// level. By default, the value is "crit". -func CritValue(value string) Option { - return func(l *Levels) { l.critValue = value } -} diff --git a/vendor/github.com/go-kit/kit/log/deprecated_levels/levels_test.go b/vendor/github.com/go-kit/kit/log/deprecated_levels/levels_test.go deleted file mode 100644 index 8d4a7f55..00000000 --- a/vendor/github.com/go-kit/kit/log/deprecated_levels/levels_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package levels_test - -import ( - "bytes" - "os" - "testing" - - "github.com/go-kit/kit/log" - levels "github.com/go-kit/kit/log/deprecated_levels" -) - -func TestDefaultLevels(t *testing.T) { - buf := bytes.Buffer{} - logger := levels.New(log.NewLogfmtLogger(&buf)) - - logger.Debug().Log("msg", "résumé") // of course you'd want to do this - if want, have := "level=debug msg=résumé\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } - - buf.Reset() - logger.Info().Log("msg", "Åhus") - if want, have := "level=info msg=Åhus\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } - - buf.Reset() - logger.Error().Log("msg", "© violation") - if want, have := "level=error msg=\"© violation\"\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } - - buf.Reset() - logger.Crit().Log("msg", " ") - if want, have := "level=crit msg=\"\\t\"\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } -} - -func TestModifiedLevels(t *testing.T) { - buf := bytes.Buffer{} - logger := levels.New( - log.NewJSONLogger(&buf), - levels.Key("l"), - levels.DebugValue("dbg"), - levels.InfoValue("nfo"), - levels.WarnValue("wrn"), - levels.ErrorValue("err"), - levels.CritValue("crt"), - ) - logger.With("easter_island", "176°").Debug().Log("msg", "moai") - if want, have := `{"easter_island":"176°","l":"dbg","msg":"moai"}`+"\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } -} - -func ExampleLevels() { - logger := levels.New(log.NewLogfmtLogger(os.Stdout)) - logger.Debug().Log("msg", "hello") - logger.With("context", "foo").Warn().Log("err", "error") - - // Output: - // level=debug msg=hello - // level=warn context=foo err=error -} diff --git a/vendor/github.com/go-kit/kit/log/doc.go b/vendor/github.com/go-kit/kit/log/doc.go deleted file mode 100644 index 918c0af4..00000000 --- a/vendor/github.com/go-kit/kit/log/doc.go +++ /dev/null @@ -1,116 +0,0 @@ -// Package log provides a structured logger. -// -// Structured logging produces logs easily consumed later by humans or -// machines. Humans might be interested in debugging errors, or tracing -// specific requests. Machines might be interested in counting interesting -// events, or aggregating information for off-line processing. In both cases, -// it is important that the log messages are structured and actionable. -// Package log is designed to encourage both of these best practices. -// -// Basic Usage -// -// The fundamental interface is Logger. Loggers create log events from -// key/value data. The Logger interface has a single method, Log, which -// accepts a sequence of alternating key/value pairs, which this package names -// keyvals. -// -// type Logger interface { -// Log(keyvals ...interface{}) error -// } -// -// Here is an example of a function using a Logger to create log events. -// -// func RunTask(task Task, logger log.Logger) string { -// logger.Log("taskID", task.ID, "event", "starting task") -// ... -// logger.Log("taskID", task.ID, "event", "task complete") -// } -// -// The keys in the above example are "taskID" and "event". The values are -// task.ID, "starting task", and "task complete". Every key is followed -// immediately by its value. -// -// Keys are usually plain strings. Values may be any type that has a sensible -// encoding in the chosen log format. With structured logging it is a good -// idea to log simple values without formatting them. This practice allows -// the chosen logger to encode values in the most appropriate way. -// -// Contextual Loggers -// -// A contextual logger stores keyvals that it includes in all log events. -// Building appropriate contextual loggers reduces repetition and aids -// consistency in the resulting log output. With and WithPrefix add context to -// a logger. We can use With to improve the RunTask example. -// -// func RunTask(task Task, logger log.Logger) string { -// logger = log.With(logger, "taskID", task.ID) -// logger.Log("event", "starting task") -// ... -// taskHelper(task.Cmd, logger) -// ... -// logger.Log("event", "task complete") -// } -// -// The improved version emits the same log events as the original for the -// first and last calls to Log. Passing the contextual logger to taskHelper -// enables each log event created by taskHelper to include the task.ID even -// though taskHelper does not have access to that value. Using contextual -// loggers this way simplifies producing log output that enables tracing the -// life cycle of individual tasks. (See the Contextual example for the full -// code of the above snippet.) -// -// Dynamic Contextual Values -// -// A Valuer function stored in a contextual logger generates a new value each -// time an event is logged. The Valuer example demonstrates how this feature -// works. -// -// Valuers provide the basis for consistently logging timestamps and source -// code location. The log package defines several valuers for that purpose. -// See Timestamp, DefaultTimestamp, DefaultTimestampUTC, Caller, and -// DefaultCaller. A common logger initialization sequence that ensures all log -// entries contain a timestamp and source location looks like this: -// -// logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) -// logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) -// -// Concurrent Safety -// -// Applications with multiple goroutines want each log event written to the -// same logger to remain separate from other log events. Package log provides -// two simple solutions for concurrent safe logging. -// -// NewSyncWriter wraps an io.Writer and serializes each call to its Write -// method. Using a SyncWriter has the benefit that the smallest practical -// portion of the logging logic is performed within a mutex, but it requires -// the formatting Logger to make only one call to Write per log event. -// -// NewSyncLogger wraps any Logger and serializes each call to its Log method. -// Using a SyncLogger has the benefit that it guarantees each log event is -// handled atomically within the wrapped logger, but it typically serializes -// both the formatting and output logic. Use a SyncLogger if the formatting -// logger may perform multiple writes per log event. -// -// Error Handling -// -// This package relies on the practice of wrapping or decorating loggers with -// other loggers to provide composable pieces of functionality. It also means -// that Logger.Log must return an error because some -// implementations—especially those that output log data to an io.Writer—may -// encounter errors that cannot be handled locally. This in turn means that -// Loggers that wrap other loggers should return errors from the wrapped -// logger up the stack. -// -// Fortunately, the decorator pattern also provides a way to avoid the -// necessity to check for errors every time an application calls Logger.Log. -// An application required to panic whenever its Logger encounters -// an error could initialize its logger as follows. -// -// fmtlogger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) -// logger := log.LoggerFunc(func(keyvals ...interface{}) error { -// if err := fmtlogger.Log(keyvals...); err != nil { -// panic(err) -// } -// return nil -// }) -package log diff --git a/vendor/github.com/go-kit/kit/log/example_test.go b/vendor/github.com/go-kit/kit/log/example_test.go deleted file mode 100644 index 97667748..00000000 --- a/vendor/github.com/go-kit/kit/log/example_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package log_test - -import ( - "math/rand" - "os" - "sync" - "time" - - "github.com/go-kit/kit/log" -) - -func Example_basic() { - logger := log.NewLogfmtLogger(os.Stdout) - - type Task struct { - ID int - } - - RunTask := func(task Task, logger log.Logger) { - logger.Log("taskID", task.ID, "event", "starting task") - - logger.Log("taskID", task.ID, "event", "task complete") - } - - RunTask(Task{ID: 1}, logger) - - // Output: - // taskID=1 event="starting task" - // taskID=1 event="task complete" -} - -func Example_contextual() { - logger := log.NewLogfmtLogger(os.Stdout) - - type Task struct { - ID int - Cmd string - } - - taskHelper := func(cmd string, logger log.Logger) { - // execute(cmd) - logger.Log("cmd", cmd, "dur", 42*time.Millisecond) - } - - RunTask := func(task Task, logger log.Logger) { - logger = log.With(logger, "taskID", task.ID) - logger.Log("event", "starting task") - - taskHelper(task.Cmd, logger) - - logger.Log("event", "task complete") - } - - RunTask(Task{ID: 1, Cmd: "echo Hello, world!"}, logger) - - // Output: - // taskID=1 event="starting task" - // taskID=1 cmd="echo Hello, world!" dur=42ms - // taskID=1 event="task complete" -} - -func Example_valuer() { - logger := log.NewLogfmtLogger(os.Stdout) - - count := 0 - counter := func() interface{} { - count++ - return count - } - - logger = log.With(logger, "count", log.Valuer(counter)) - - logger.Log("call", "first") - logger.Log("call", "second") - - // Output: - // count=1 call=first - // count=2 call=second -} - -func Example_debugInfo() { - logger := log.NewLogfmtLogger(os.Stdout) - - // make time predictable for this test - baseTime := time.Date(2015, time.February, 3, 10, 0, 0, 0, time.UTC) - mockTime := func() time.Time { - baseTime = baseTime.Add(time.Second) - return baseTime - } - - logger = log.With(logger, "time", log.Timestamp(mockTime), "caller", log.DefaultCaller) - - logger.Log("call", "first") - logger.Log("call", "second") - - // ... - - logger.Log("call", "third") - - // Output: - // time=2015-02-03T10:00:01Z caller=example_test.go:93 call=first - // time=2015-02-03T10:00:02Z caller=example_test.go:94 call=second - // time=2015-02-03T10:00:03Z caller=example_test.go:98 call=third -} - -func Example_syncWriter() { - w := log.NewSyncWriter(os.Stdout) - logger := log.NewLogfmtLogger(w) - - type Task struct { - ID int - } - - var wg sync.WaitGroup - - RunTask := func(task Task, logger log.Logger) { - logger.Log("taskID", task.ID, "event", "starting task") - - time.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond) - - logger.Log("taskID", task.ID, "event", "task complete") - wg.Done() - } - - wg.Add(2) - - go RunTask(Task{ID: 1}, logger) - go RunTask(Task{ID: 2}, logger) - - wg.Wait() - - // Unordered output: - // taskID=1 event="starting task" - // taskID=2 event="starting task" - // taskID=1 event="task complete" - // taskID=2 event="task complete" -} diff --git a/vendor/github.com/go-kit/kit/log/json_logger.go b/vendor/github.com/go-kit/kit/log/json_logger.go deleted file mode 100644 index 66094b4d..00000000 --- a/vendor/github.com/go-kit/kit/log/json_logger.go +++ /dev/null @@ -1,89 +0,0 @@ -package log - -import ( - "encoding" - "encoding/json" - "fmt" - "io" - "reflect" -) - -type jsonLogger struct { - io.Writer -} - -// NewJSONLogger returns a Logger that encodes keyvals to the Writer as a -// single JSON object. Each log event produces no more than one call to -// w.Write. The passed Writer must be safe for concurrent use by multiple -// goroutines if the returned Logger will be used concurrently. -func NewJSONLogger(w io.Writer) Logger { - return &jsonLogger{w} -} - -func (l *jsonLogger) Log(keyvals ...interface{}) error { - n := (len(keyvals) + 1) / 2 // +1 to handle case when len is odd - m := make(map[string]interface{}, n) - for i := 0; i < len(keyvals); i += 2 { - k := keyvals[i] - var v interface{} = ErrMissingValue - if i+1 < len(keyvals) { - v = keyvals[i+1] - } - merge(m, k, v) - } - return json.NewEncoder(l.Writer).Encode(m) -} - -func merge(dst map[string]interface{}, k, v interface{}) { - var key string - switch x := k.(type) { - case string: - key = x - case fmt.Stringer: - key = safeString(x) - default: - key = fmt.Sprint(x) - } - - // We want json.Marshaler and encoding.TextMarshaller to take priority over - // err.Error() and v.String(). But json.Marshall (called later) does that by - // default so we force a no-op if it's one of those 2 case. - switch x := v.(type) { - case json.Marshaler: - case encoding.TextMarshaler: - case error: - v = safeError(x) - case fmt.Stringer: - v = safeString(x) - } - - dst[key] = v -} - -func safeString(str fmt.Stringer) (s string) { - defer func() { - if panicVal := recover(); panicVal != nil { - if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() { - s = "NULL" - } else { - panic(panicVal) - } - } - }() - s = str.String() - return -} - -func safeError(err error) (s interface{}) { - defer func() { - if panicVal := recover(); panicVal != nil { - if v := reflect.ValueOf(err); v.Kind() == reflect.Ptr && v.IsNil() { - s = nil - } else { - panic(panicVal) - } - } - }() - s = err.Error() - return -} diff --git a/vendor/github.com/go-kit/kit/log/json_logger_test.go b/vendor/github.com/go-kit/kit/log/json_logger_test.go deleted file mode 100644 index e3e30909..00000000 --- a/vendor/github.com/go-kit/kit/log/json_logger_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package log_test - -import ( - "bytes" - "errors" - "io/ioutil" - "testing" - - "github.com/go-kit/kit/log" -) - -func TestJSONLoggerCaller(t *testing.T) { - t.Parallel() - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - logger = log.With(logger, "caller", log.DefaultCaller) - - if err := logger.Log(); err != nil { - t.Fatal(err) - } - if want, have := `{"caller":"json_logger_test.go:18"}`+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } -} - -func TestJSONLogger(t *testing.T) { - t.Parallel() - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - if err := logger.Log("err", errors.New("err"), "m", map[string]int{"0": 0}, "a", []int{1, 2, 3}); err != nil { - t.Fatal(err) - } - if want, have := `{"a":[1,2,3],"err":"err","m":{"0":0}}`+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } -} - -func TestJSONLoggerMissingValue(t *testing.T) { - t.Parallel() - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - if err := logger.Log("k"); err != nil { - t.Fatal(err) - } - if want, have := `{"k":"(MISSING)"}`+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } -} - -func TestJSONLoggerNilStringerKey(t *testing.T) { - t.Parallel() - - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - if err := logger.Log((*stringer)(nil), "v"); err != nil { - t.Fatal(err) - } - if want, have := `{"NULL":"v"}`+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } -} - -func TestJSONLoggerNilErrorValue(t *testing.T) { - t.Parallel() - - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - if err := logger.Log("err", (*stringError)(nil)); err != nil { - t.Fatal(err) - } - if want, have := `{"err":null}`+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } -} - -// aller implements json.Marshaler, encoding.TextMarshaler, and fmt.Stringer. -type aller struct{} - -func (aller) MarshalJSON() ([]byte, error) { - return []byte("\"json\""), nil -} - -func (aller) MarshalText() ([]byte, error) { - return []byte("text"), nil -} - -func (aller) String() string { - return "string" -} - -func (aller) Error() string { - return "error" -} - -// textstringer implements encoding.TextMarshaler and fmt.Stringer. -type textstringer struct{} - -func (textstringer) MarshalText() ([]byte, error) { - return []byte("text"), nil -} - -func (textstringer) String() string { - return "string" -} - -func TestJSONLoggerStringValue(t *testing.T) { - t.Parallel() - tests := []struct { - v interface{} - expected string - }{ - { - v: aller{}, - expected: `{"v":"json"}`, - }, - { - v: textstringer{}, - expected: `{"v":"text"}`, - }, - { - v: stringer("string"), - expected: `{"v":"string"}`, - }, - } - - for _, test := range tests { - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - if err := logger.Log("v", test.v); err != nil { - t.Fatal(err) - } - - if want, have := test.expected+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } - } -} - -type stringer string - -func (s stringer) String() string { - return string(s) -} - -type stringError string - -func (s stringError) Error() string { - return string(s) -} - -func BenchmarkJSONLoggerSimple(b *testing.B) { - benchmarkRunner(b, log.NewJSONLogger(ioutil.Discard), baseMessage) -} - -func BenchmarkJSONLoggerContextual(b *testing.B) { - benchmarkRunner(b, log.NewJSONLogger(ioutil.Discard), withMessage) -} - -func TestJSONLoggerConcurrency(t *testing.T) { - t.Parallel() - testConcurrency(t, log.NewJSONLogger(ioutil.Discard), 10000) -} diff --git a/vendor/github.com/go-kit/kit/log/level/benchmark_test.go b/vendor/github.com/go-kit/kit/log/level/benchmark_test.go deleted file mode 100644 index 4fca6f08..00000000 --- a/vendor/github.com/go-kit/kit/log/level/benchmark_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package level_test - -import ( - "io/ioutil" - "testing" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" -) - -func Benchmark(b *testing.B) { - contexts := []struct { - name string - context func(log.Logger) log.Logger - }{ - {"NoContext", func(l log.Logger) log.Logger { - return l - }}, - {"TimeContext", func(l log.Logger) log.Logger { - return log.With(l, "time", log.DefaultTimestampUTC) - }}, - {"CallerContext", func(l log.Logger) log.Logger { - return log.With(l, "caller", log.DefaultCaller) - }}, - {"TimeCallerReqIDContext", func(l log.Logger) log.Logger { - return log.With(l, "time", log.DefaultTimestampUTC, "caller", log.DefaultCaller, "reqID", 29) - }}, - } - - loggers := []struct { - name string - logger log.Logger - }{ - {"Nop", log.NewNopLogger()}, - {"Logfmt", log.NewLogfmtLogger(ioutil.Discard)}, - {"JSON", log.NewJSONLogger(ioutil.Discard)}, - } - - filters := []struct { - name string - filter func(log.Logger) log.Logger - }{ - {"Baseline", func(l log.Logger) log.Logger { - return l - }}, - {"DisallowedLevel", func(l log.Logger) log.Logger { - return level.NewFilter(l, level.AllowInfo()) - }}, - {"AllowedLevel", func(l log.Logger) log.Logger { - return level.NewFilter(l, level.AllowAll()) - }}, - } - - for _, c := range contexts { - b.Run(c.name, func(b *testing.B) { - for _, f := range filters { - b.Run(f.name, func(b *testing.B) { - for _, l := range loggers { - b.Run(l.name, func(b *testing.B) { - logger := c.context(f.filter(l.logger)) - b.ResetTimer() - b.ReportAllocs() - for i := 0; i < b.N; i++ { - level.Debug(logger).Log("foo", "bar") - } - }) - } - }) - } - }) - } -} diff --git a/vendor/github.com/go-kit/kit/log/level/doc.go b/vendor/github.com/go-kit/kit/log/level/doc.go deleted file mode 100644 index 5e9df7fa..00000000 --- a/vendor/github.com/go-kit/kit/log/level/doc.go +++ /dev/null @@ -1,22 +0,0 @@ -// Package level implements leveled logging on top of package log. To use the -// level package, create a logger as per normal in your func main, and wrap it -// with level.NewFilter. -// -// var logger log.Logger -// logger = log.NewLogfmtLogger(os.Stderr) -// logger = level.NewFilter(logger, level.AllowInfoAndAbove()) // <-- -// logger = log.With(logger, "ts", log.DefaultTimestampUTC) -// -// Then, at the callsites, use one of the level.Debug, Info, Warn, or Error -// helper methods to emit leveled log events. -// -// logger.Log("foo", "bar") // as normal, no level -// level.Debug(logger).Log("request_id", reqID, "trace_data", trace.Get()) -// if value > 100 { -// level.Error(logger).Log("value", value) -// } -// -// NewFilter allows precise control over what happens when a log event is -// emitted without a level key, or if a squelched level is used. Check the -// Option functions for details. -package level diff --git a/vendor/github.com/go-kit/kit/log/level/example_test.go b/vendor/github.com/go-kit/kit/log/level/example_test.go deleted file mode 100644 index fed52e51..00000000 --- a/vendor/github.com/go-kit/kit/log/level/example_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package level_test - -import ( - "errors" - "os" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" -) - -func Example_basic() { - // setup logger with level filter - logger := log.NewLogfmtLogger(os.Stdout) - logger = level.NewFilter(logger, level.AllowInfo()) - logger = log.With(logger, "caller", log.DefaultCaller) - - // use level helpers to log at different levels - level.Error(logger).Log("err", errors.New("bad data")) - level.Info(logger).Log("event", "data saved") - level.Debug(logger).Log("next item", 17) // filtered - - // Output: - // level=error caller=example_test.go:18 err="bad data" - // level=info caller=example_test.go:19 event="data saved" -} diff --git a/vendor/github.com/go-kit/kit/log/level/level.go b/vendor/github.com/go-kit/kit/log/level/level.go deleted file mode 100644 index 6833b0dc..00000000 --- a/vendor/github.com/go-kit/kit/log/level/level.go +++ /dev/null @@ -1,205 +0,0 @@ -package level - -import "github.com/go-kit/kit/log" - -// Error returns a logger that includes a Key/ErrorValue pair. -func Error(logger log.Logger) log.Logger { - return log.WithPrefix(logger, Key(), ErrorValue()) -} - -// Warn returns a logger that includes a Key/WarnValue pair. -func Warn(logger log.Logger) log.Logger { - return log.WithPrefix(logger, Key(), WarnValue()) -} - -// Info returns a logger that includes a Key/InfoValue pair. -func Info(logger log.Logger) log.Logger { - return log.WithPrefix(logger, Key(), InfoValue()) -} - -// Debug returns a logger that includes a Key/DebugValue pair. -func Debug(logger log.Logger) log.Logger { - return log.WithPrefix(logger, Key(), DebugValue()) -} - -// NewFilter wraps next and implements level filtering. See the commentary on -// the Option functions for a detailed description of how to configure levels. -// If no options are provided, all leveled log events created with Debug, -// Info, Warn or Error helper methods are squelched and non-leveled log -// events are passed to next unmodified. -func NewFilter(next log.Logger, options ...Option) log.Logger { - l := &logger{ - next: next, - } - for _, option := range options { - option(l) - } - return l -} - -type logger struct { - next log.Logger - allowed level - squelchNoLevel bool - errNotAllowed error - errNoLevel error -} - -func (l *logger) Log(keyvals ...interface{}) error { - var hasLevel, levelAllowed bool - for i := 1; i < len(keyvals); i += 2 { - if v, ok := keyvals[i].(*levelValue); ok { - hasLevel = true - levelAllowed = l.allowed&v.level != 0 - break - } - } - if !hasLevel && l.squelchNoLevel { - return l.errNoLevel - } - if hasLevel && !levelAllowed { - return l.errNotAllowed - } - return l.next.Log(keyvals...) -} - -// Option sets a parameter for the leveled logger. -type Option func(*logger) - -// AllowAll is an alias for AllowDebug. -func AllowAll() Option { - return AllowDebug() -} - -// AllowDebug allows error, warn, info and debug level log events to pass. -func AllowDebug() Option { - return allowed(levelError | levelWarn | levelInfo | levelDebug) -} - -// AllowInfo allows error, warn and info level log events to pass. -func AllowInfo() Option { - return allowed(levelError | levelWarn | levelInfo) -} - -// AllowWarn allows error and warn level log events to pass. -func AllowWarn() Option { - return allowed(levelError | levelWarn) -} - -// AllowError allows only error level log events to pass. -func AllowError() Option { - return allowed(levelError) -} - -// AllowNone allows no leveled log events to pass. -func AllowNone() Option { - return allowed(0) -} - -func allowed(allowed level) Option { - return func(l *logger) { l.allowed = allowed } -} - -// ErrNotAllowed sets the error to return from Log when it squelches a log -// event disallowed by the configured Allow[Level] option. By default, -// ErrNotAllowed is nil; in this case the log event is squelched with no -// error. -func ErrNotAllowed(err error) Option { - return func(l *logger) { l.errNotAllowed = err } -} - -// SquelchNoLevel instructs Log to squelch log events with no level, so that -// they don't proceed through to the wrapped logger. If SquelchNoLevel is set -// to true and a log event is squelched in this way, the error value -// configured with ErrNoLevel is returned to the caller. -func SquelchNoLevel(squelch bool) Option { - return func(l *logger) { l.squelchNoLevel = squelch } -} - -// ErrNoLevel sets the error to return from Log when it squelches a log event -// with no level. By default, ErrNoLevel is nil; in this case the log event is -// squelched with no error. -func ErrNoLevel(err error) Option { - return func(l *logger) { l.errNoLevel = err } -} - -// NewInjector wraps next and returns a logger that adds a Key/level pair to -// the beginning of log events that don't already contain a level. In effect, -// this gives a default level to logs without a level. -func NewInjector(next log.Logger, level Value) log.Logger { - return &injector{ - next: next, - level: level, - } -} - -type injector struct { - next log.Logger - level interface{} -} - -func (l *injector) Log(keyvals ...interface{}) error { - for i := 1; i < len(keyvals); i += 2 { - if _, ok := keyvals[i].(*levelValue); ok { - return l.next.Log(keyvals...) - } - } - kvs := make([]interface{}, len(keyvals)+2) - kvs[0], kvs[1] = key, l.level - copy(kvs[2:], keyvals) - return l.next.Log(kvs...) -} - -// Value is the interface that each of the canonical level values implement. -// It contains unexported methods that prevent types from other packages from -// implementing it and guaranteeing that NewFilter can distinguish the levels -// defined in this package from all other values. -type Value interface { - String() string - levelVal() -} - -// Key returns the unique key added to log events by the loggers in this -// package. -func Key() interface{} { return key } - -// ErrorValue returns the unique value added to log events by Error. -func ErrorValue() Value { return errorValue } - -// WarnValue returns the unique value added to log events by Warn. -func WarnValue() Value { return warnValue } - -// InfoValue returns the unique value added to log events by Info. -func InfoValue() Value { return infoValue } - -// DebugValue returns the unique value added to log events by Warn. -func DebugValue() Value { return debugValue } - -var ( - // key is of type interfae{} so that it allocates once during package - // initialization and avoids allocating every type the value is added to a - // []interface{} later. - key interface{} = "level" - - errorValue = &levelValue{level: levelError, name: "error"} - warnValue = &levelValue{level: levelWarn, name: "warn"} - infoValue = &levelValue{level: levelInfo, name: "info"} - debugValue = &levelValue{level: levelDebug, name: "debug"} -) - -type level byte - -const ( - levelDebug level = 1 << iota - levelInfo - levelWarn - levelError -) - -type levelValue struct { - name string - level -} - -func (v *levelValue) String() string { return v.name } -func (v *levelValue) levelVal() {} diff --git a/vendor/github.com/go-kit/kit/log/level/level_test.go b/vendor/github.com/go-kit/kit/log/level/level_test.go deleted file mode 100644 index e362effc..00000000 --- a/vendor/github.com/go-kit/kit/log/level/level_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package level_test - -import ( - "bytes" - "errors" - "io" - "strings" - "testing" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" -) - -func TestVariousLevels(t *testing.T) { - testCases := []struct { - name string - allowed level.Option - want string - }{ - { - "AllowAll", - level.AllowAll(), - strings.Join([]string{ - `{"level":"debug","this is":"debug log"}`, - `{"level":"info","this is":"info log"}`, - `{"level":"warn","this is":"warn log"}`, - `{"level":"error","this is":"error log"}`, - }, "\n"), - }, - { - "AllowDebug", - level.AllowDebug(), - strings.Join([]string{ - `{"level":"debug","this is":"debug log"}`, - `{"level":"info","this is":"info log"}`, - `{"level":"warn","this is":"warn log"}`, - `{"level":"error","this is":"error log"}`, - }, "\n"), - }, - { - "AllowInfo", - level.AllowInfo(), - strings.Join([]string{ - `{"level":"info","this is":"info log"}`, - `{"level":"warn","this is":"warn log"}`, - `{"level":"error","this is":"error log"}`, - }, "\n"), - }, - { - "AllowWarn", - level.AllowWarn(), - strings.Join([]string{ - `{"level":"warn","this is":"warn log"}`, - `{"level":"error","this is":"error log"}`, - }, "\n"), - }, - { - "AllowError", - level.AllowError(), - strings.Join([]string{ - `{"level":"error","this is":"error log"}`, - }, "\n"), - }, - { - "AllowNone", - level.AllowNone(), - ``, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - var buf bytes.Buffer - logger := level.NewFilter(log.NewJSONLogger(&buf), tc.allowed) - - level.Debug(logger).Log("this is", "debug log") - level.Info(logger).Log("this is", "info log") - level.Warn(logger).Log("this is", "warn log") - level.Error(logger).Log("this is", "error log") - - if want, have := tc.want, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant:\n%s\nhave:\n%s", want, have) - } - }) - } -} - -func TestErrNotAllowed(t *testing.T) { - myError := errors.New("squelched!") - opts := []level.Option{ - level.AllowWarn(), - level.ErrNotAllowed(myError), - } - logger := level.NewFilter(log.NewNopLogger(), opts...) - - if want, have := myError, level.Info(logger).Log("foo", "bar"); want != have { - t.Errorf("want %#+v, have %#+v", want, have) - } - - if want, have := error(nil), level.Warn(logger).Log("foo", "bar"); want != have { - t.Errorf("want %#+v, have %#+v", want, have) - } -} - -func TestErrNoLevel(t *testing.T) { - myError := errors.New("no level specified") - - var buf bytes.Buffer - opts := []level.Option{ - level.SquelchNoLevel(true), - level.ErrNoLevel(myError), - } - logger := level.NewFilter(log.NewJSONLogger(&buf), opts...) - - if want, have := myError, logger.Log("foo", "bar"); want != have { - t.Errorf("want %v, have %v", want, have) - } - if want, have := ``, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant '%s'\nhave '%s'", want, have) - } -} - -func TestAllowNoLevel(t *testing.T) { - var buf bytes.Buffer - opts := []level.Option{ - level.SquelchNoLevel(false), - level.ErrNoLevel(errors.New("I should never be returned!")), - } - logger := level.NewFilter(log.NewJSONLogger(&buf), opts...) - - if want, have := error(nil), logger.Log("foo", "bar"); want != have { - t.Errorf("want %v, have %v", want, have) - } - if want, have := `{"foo":"bar"}`, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant '%s'\nhave '%s'", want, have) - } -} - -func TestLevelContext(t *testing.T) { - var buf bytes.Buffer - - // Wrapping the level logger with a context allows users to use - // log.DefaultCaller as per normal. - var logger log.Logger - logger = log.NewLogfmtLogger(&buf) - logger = level.NewFilter(logger, level.AllowAll()) - logger = log.With(logger, "caller", log.DefaultCaller) - - level.Info(logger).Log("foo", "bar") - if want, have := `level=info caller=level_test.go:149 foo=bar`, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant '%s'\nhave '%s'", want, have) - } -} - -func TestContextLevel(t *testing.T) { - var buf bytes.Buffer - - // Wrapping a context with the level logger still works, but requires users - // to specify a higher callstack depth value. - var logger log.Logger - logger = log.NewLogfmtLogger(&buf) - logger = log.With(logger, "caller", log.Caller(5)) - logger = level.NewFilter(logger, level.AllowAll()) - - level.Info(logger).Log("foo", "bar") - if want, have := `caller=level_test.go:165 level=info foo=bar`, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant '%s'\nhave '%s'", want, have) - } -} - -func TestLevelFormatting(t *testing.T) { - testCases := []struct { - name string - format func(io.Writer) log.Logger - output string - }{ - { - name: "logfmt", - format: log.NewLogfmtLogger, - output: `level=info foo=bar`, - }, - { - name: "JSON", - format: log.NewJSONLogger, - output: `{"foo":"bar","level":"info"}`, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - var buf bytes.Buffer - - logger := tc.format(&buf) - level.Info(logger).Log("foo", "bar") - if want, have := tc.output, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant: '%s'\nhave '%s'", want, have) - } - }) - } -} - -func TestInjector(t *testing.T) { - var ( - output []interface{} - logger log.Logger - ) - - logger = log.LoggerFunc(func(keyvals ...interface{}) error { - output = keyvals - return nil - }) - logger = level.NewInjector(logger, level.InfoValue()) - - logger.Log("foo", "bar") - if got, want := len(output), 4; got != want { - t.Errorf("missing level not injected: got len==%d, want len==%d", got, want) - } - if got, want := output[0], level.Key(); got != want { - t.Errorf("wrong level key: got %#v, want %#v", got, want) - } - if got, want := output[1], level.InfoValue(); got != want { - t.Errorf("wrong level value: got %#v, want %#v", got, want) - } - - level.Error(logger).Log("foo", "bar") - if got, want := len(output), 4; got != want { - t.Errorf("leveled record modified: got len==%d, want len==%d", got, want) - } - if got, want := output[0], level.Key(); got != want { - t.Errorf("wrong level key: got %#v, want %#v", got, want) - } - if got, want := output[1], level.ErrorValue(); got != want { - t.Errorf("wrong level value: got %#v, want %#v", got, want) - } -} diff --git a/vendor/github.com/go-kit/kit/log/log.go b/vendor/github.com/go-kit/kit/log/log.go deleted file mode 100644 index 66a9e2fd..00000000 --- a/vendor/github.com/go-kit/kit/log/log.go +++ /dev/null @@ -1,135 +0,0 @@ -package log - -import "errors" - -// Logger is the fundamental interface for all log operations. Log creates a -// log event from keyvals, a variadic sequence of alternating keys and values. -// Implementations must be safe for concurrent use by multiple goroutines. In -// particular, any implementation of Logger that appends to keyvals or -// modifies or retains any of its elements must make a copy first. -type Logger interface { - Log(keyvals ...interface{}) error -} - -// ErrMissingValue is appended to keyvals slices with odd length to substitute -// the missing value. -var ErrMissingValue = errors.New("(MISSING)") - -// With returns a new contextual logger with keyvals prepended to those passed -// to calls to Log. If logger is also a contextual logger created by With or -// WithPrefix, keyvals is appended to the existing context. -// -// The returned Logger replaces all value elements (odd indexes) containing a -// Valuer with their generated value for each call to its Log method. -func With(logger Logger, keyvals ...interface{}) Logger { - if len(keyvals) == 0 { - return logger - } - l := newContext(logger) - kvs := append(l.keyvals, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - return &context{ - logger: l.logger, - // Limiting the capacity of the stored keyvals ensures that a new - // backing array is created if the slice must grow in Log or With. - // Using the extra capacity without copying risks a data race that - // would violate the Logger interface contract. - keyvals: kvs[:len(kvs):len(kvs)], - hasValuer: l.hasValuer || containsValuer(keyvals), - } -} - -// WithPrefix returns a new contextual logger with keyvals prepended to those -// passed to calls to Log. If logger is also a contextual logger created by -// With or WithPrefix, keyvals is prepended to the existing context. -// -// The returned Logger replaces all value elements (odd indexes) containing a -// Valuer with their generated value for each call to its Log method. -func WithPrefix(logger Logger, keyvals ...interface{}) Logger { - if len(keyvals) == 0 { - return logger - } - l := newContext(logger) - // Limiting the capacity of the stored keyvals ensures that a new - // backing array is created if the slice must grow in Log or With. - // Using the extra capacity without copying risks a data race that - // would violate the Logger interface contract. - n := len(l.keyvals) + len(keyvals) - if len(keyvals)%2 != 0 { - n++ - } - kvs := make([]interface{}, 0, n) - kvs = append(kvs, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - kvs = append(kvs, l.keyvals...) - return &context{ - logger: l.logger, - keyvals: kvs, - hasValuer: l.hasValuer || containsValuer(keyvals), - } -} - -// context is the Logger implementation returned by With and WithPrefix. It -// wraps a Logger and holds keyvals that it includes in all log events. Its -// Log method calls bindValues to generate values for each Valuer in the -// context keyvals. -// -// A context must always have the same number of stack frames between calls to -// its Log method and the eventual binding of Valuers to their value. This -// requirement comes from the functional requirement to allow a context to -// resolve application call site information for a Caller stored in the -// context. To do this we must be able to predict the number of logging -// functions on the stack when bindValues is called. -// -// Two implementation details provide the needed stack depth consistency. -// -// 1. newContext avoids introducing an additional layer when asked to -// wrap another context. -// 2. With and WithPrefix avoid introducing an additional layer by -// returning a newly constructed context with a merged keyvals rather -// than simply wrapping the existing context. -type context struct { - logger Logger - keyvals []interface{} - hasValuer bool -} - -func newContext(logger Logger) *context { - if c, ok := logger.(*context); ok { - return c - } - return &context{logger: logger} -} - -// Log replaces all value elements (odd indexes) containing a Valuer in the -// stored context with their generated value, appends keyvals, and passes the -// result to the wrapped Logger. -func (l *context) Log(keyvals ...interface{}) error { - kvs := append(l.keyvals, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - if l.hasValuer { - // If no keyvals were appended above then we must copy l.keyvals so - // that future log events will reevaluate the stored Valuers. - if len(keyvals) == 0 { - kvs = append([]interface{}{}, l.keyvals...) - } - bindValues(kvs[:len(l.keyvals)]) - } - return l.logger.Log(kvs...) -} - -// LoggerFunc is an adapter to allow use of ordinary functions as Loggers. If -// f is a function with the appropriate signature, LoggerFunc(f) is a Logger -// object that calls f. -type LoggerFunc func(...interface{}) error - -// Log implements Logger by calling f(keyvals...). -func (f LoggerFunc) Log(keyvals ...interface{}) error { - return f(keyvals...) -} diff --git a/vendor/github.com/go-kit/kit/log/log_test.go b/vendor/github.com/go-kit/kit/log/log_test.go deleted file mode 100644 index 1bf29727..00000000 --- a/vendor/github.com/go-kit/kit/log/log_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package log_test - -import ( - "bytes" - "fmt" - "sync" - "testing" - - "github.com/go-kit/kit/log" - "github.com/go-stack/stack" -) - -func TestContext(t *testing.T) { - t.Parallel() - buf := &bytes.Buffer{} - logger := log.NewLogfmtLogger(buf) - - kvs := []interface{}{"a", 123} - lc := log.With(logger, kvs...) - kvs[1] = 0 // With should copy its key values - - lc = log.With(lc, "b", "c") // With should stack - if err := lc.Log("msg", "message"); err != nil { - t.Fatal(err) - } - if want, have := "a=123 b=c msg=message\n", buf.String(); want != have { - t.Errorf("\nwant: %shave: %s", want, have) - } - - buf.Reset() - lc = log.WithPrefix(lc, "p", "first") - if err := lc.Log("msg", "message"); err != nil { - t.Fatal(err) - } - if want, have := "p=first a=123 b=c msg=message\n", buf.String(); want != have { - t.Errorf("\nwant: %shave: %s", want, have) - } -} - -func TestContextMissingValue(t *testing.T) { - t.Parallel() - var output []interface{} - logger := log.Logger(log.LoggerFunc(func(keyvals ...interface{}) error { - output = keyvals - return nil - })) - - log.WithPrefix(log.With(logger, "k1"), "k0").Log("k2") - if want, have := 6, len(output); want != have { - t.Errorf("want len(output) == %v, have %v", want, have) - } - for i := 1; i < 6; i += 2 { - if want, have := log.ErrMissingValue, output[i]; want != have { - t.Errorf("want output[%d] == %#v, have %#v", i, want, have) - } - } -} - -// Test that context.Log has a consistent function stack depth when binding -// Valuers, regardless of how many times With has been called. -func TestContextStackDepth(t *testing.T) { - t.Parallel() - fn := fmt.Sprintf("%n", stack.Caller(0)) - - var output []interface{} - - logger := log.Logger(log.LoggerFunc(func(keyvals ...interface{}) error { - output = keyvals - return nil - })) - - stackValuer := log.Valuer(func() interface{} { - for i, c := range stack.Trace() { - if fmt.Sprintf("%n", c) == fn { - return i - } - } - t.Fatal("Test function not found in stack trace.") - return nil - }) - - logger = log.With(logger, "stack", stackValuer) - - // Call through interface to get baseline. - logger.Log("k", "v") - want := output[1].(int) - - for len(output) < 10 { - logger.Log("k", "v") - if have := output[1]; have != want { - t.Errorf("%d Withs: have %v, want %v", len(output)/2-1, have, want) - } - - wrapped := log.With(logger) - wrapped.Log("k", "v") - if have := output[1]; have != want { - t.Errorf("%d Withs: have %v, want %v", len(output)/2-1, have, want) - } - - logger = log.With(logger, "k", "v") - } -} - -// Test that With returns a Logger safe for concurrent use. This test -// validates that the stored logging context does not get corrupted when -// multiple clients concurrently log additional keyvals. -// -// This test must be run with go test -cpu 2 (or more) to achieve its goal. -func TestWithConcurrent(t *testing.T) { - // Create some buckets to count how many events each goroutine logs. - const goroutines = 8 - counts := [goroutines]int{} - - // This logger extracts a goroutine id from the last value field and - // increments the referenced bucket. - logger := log.LoggerFunc(func(kv ...interface{}) error { - goroutine := kv[len(kv)-1].(int) - counts[goroutine]++ - return nil - }) - - // With must be careful about handling slices that can grow without - // copying the underlying array, so give it a challenge. - l := log.With(logger, make([]interface{}, 0, 2)...) - - // Start logging concurrently. Each goroutine logs its id so the logger - // can bucket the event counts. - var wg sync.WaitGroup - wg.Add(goroutines) - const n = 10000 - for i := 0; i < goroutines; i++ { - go func(idx int) { - defer wg.Done() - for j := 0; j < n; j++ { - l.Log("goroutineIdx", idx) - } - }(i) - } - wg.Wait() - - for bucket, have := range counts { - if want := n; want != have { - t.Errorf("bucket %d: want %d, have %d", bucket, want, have) // note Errorf - } - } -} - -func BenchmarkDiscard(b *testing.B) { - logger := log.NewNopLogger() - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - logger.Log("k", "v") - } -} - -func BenchmarkOneWith(b *testing.B) { - logger := log.NewNopLogger() - lc := log.With(logger, "k", "v") - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - lc.Log("k", "v") - } -} - -func BenchmarkTwoWith(b *testing.B) { - logger := log.NewNopLogger() - lc := log.With(logger, "k", "v") - for i := 1; i < 2; i++ { - lc = log.With(lc, "k", "v") - } - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - lc.Log("k", "v") - } -} - -func BenchmarkTenWith(b *testing.B) { - logger := log.NewNopLogger() - lc := log.With(logger, "k", "v") - for i := 1; i < 10; i++ { - lc = log.With(lc, "k", "v") - } - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - lc.Log("k", "v") - } -} diff --git a/vendor/github.com/go-kit/kit/log/logfmt_logger.go b/vendor/github.com/go-kit/kit/log/logfmt_logger.go deleted file mode 100644 index a0030529..00000000 --- a/vendor/github.com/go-kit/kit/log/logfmt_logger.go +++ /dev/null @@ -1,62 +0,0 @@ -package log - -import ( - "bytes" - "io" - "sync" - - "github.com/go-logfmt/logfmt" -) - -type logfmtEncoder struct { - *logfmt.Encoder - buf bytes.Buffer -} - -func (l *logfmtEncoder) Reset() { - l.Encoder.Reset() - l.buf.Reset() -} - -var logfmtEncoderPool = sync.Pool{ - New: func() interface{} { - var enc logfmtEncoder - enc.Encoder = logfmt.NewEncoder(&enc.buf) - return &enc - }, -} - -type logfmtLogger struct { - w io.Writer -} - -// NewLogfmtLogger returns a logger that encodes keyvals to the Writer in -// logfmt format. Each log event produces no more than one call to w.Write. -// The passed Writer must be safe for concurrent use by multiple goroutines if -// the returned Logger will be used concurrently. -func NewLogfmtLogger(w io.Writer) Logger { - return &logfmtLogger{w} -} - -func (l logfmtLogger) Log(keyvals ...interface{}) error { - enc := logfmtEncoderPool.Get().(*logfmtEncoder) - enc.Reset() - defer logfmtEncoderPool.Put(enc) - - if err := enc.EncodeKeyvals(keyvals...); err != nil { - return err - } - - // Add newline to the end of the buffer - if err := enc.EndRecord(); err != nil { - return err - } - - // The Logger interface requires implementations to be safe for concurrent - // use by multiple goroutines. For this implementation that means making - // only one call to l.w.Write() for each call to Log. - if _, err := l.w.Write(enc.buf.Bytes()); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-kit/kit/log/logfmt_logger_test.go b/vendor/github.com/go-kit/kit/log/logfmt_logger_test.go deleted file mode 100644 index 91bbca15..00000000 --- a/vendor/github.com/go-kit/kit/log/logfmt_logger_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package log_test - -import ( - "bytes" - "errors" - "io/ioutil" - "testing" - - "github.com/go-kit/kit/log" - "github.com/go-logfmt/logfmt" -) - -func TestLogfmtLogger(t *testing.T) { - t.Parallel() - buf := &bytes.Buffer{} - logger := log.NewLogfmtLogger(buf) - - if err := logger.Log("hello", "world"); err != nil { - t.Fatal(err) - } - if want, have := "hello=world\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } - - buf.Reset() - if err := logger.Log("a", 1, "err", errors.New("error")); err != nil { - t.Fatal(err) - } - if want, have := "a=1 err=error\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } - - buf.Reset() - if err := logger.Log("std_map", map[int]int{1: 2}, "my_map", mymap{0: 0}); err != nil { - t.Fatal(err) - } - if want, have := "std_map=\""+logfmt.ErrUnsupportedValueType.Error()+"\" my_map=special_behavior\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } -} - -func BenchmarkLogfmtLoggerSimple(b *testing.B) { - benchmarkRunner(b, log.NewLogfmtLogger(ioutil.Discard), baseMessage) -} - -func BenchmarkLogfmtLoggerContextual(b *testing.B) { - benchmarkRunner(b, log.NewLogfmtLogger(ioutil.Discard), withMessage) -} - -func TestLogfmtLoggerConcurrency(t *testing.T) { - t.Parallel() - testConcurrency(t, log.NewLogfmtLogger(ioutil.Discard), 10000) -} - -type mymap map[int]int - -func (m mymap) String() string { return "special_behavior" } diff --git a/vendor/github.com/go-kit/kit/log/nop_logger.go b/vendor/github.com/go-kit/kit/log/nop_logger.go deleted file mode 100644 index 1047d626..00000000 --- a/vendor/github.com/go-kit/kit/log/nop_logger.go +++ /dev/null @@ -1,8 +0,0 @@ -package log - -type nopLogger struct{} - -// NewNopLogger returns a logger that doesn't do anything. -func NewNopLogger() Logger { return nopLogger{} } - -func (nopLogger) Log(...interface{}) error { return nil } diff --git a/vendor/github.com/go-kit/kit/log/nop_logger_test.go b/vendor/github.com/go-kit/kit/log/nop_logger_test.go deleted file mode 100644 index 908ddd81..00000000 --- a/vendor/github.com/go-kit/kit/log/nop_logger_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package log_test - -import ( - "testing" - - "github.com/go-kit/kit/log" -) - -func TestNopLogger(t *testing.T) { - t.Parallel() - logger := log.NewNopLogger() - if err := logger.Log("abc", 123); err != nil { - t.Error(err) - } - if err := log.With(logger, "def", "ghi").Log(); err != nil { - t.Error(err) - } -} - -func BenchmarkNopLoggerSimple(b *testing.B) { - benchmarkRunner(b, log.NewNopLogger(), baseMessage) -} - -func BenchmarkNopLoggerContextual(b *testing.B) { - benchmarkRunner(b, log.NewNopLogger(), withMessage) -} diff --git a/vendor/github.com/go-kit/kit/log/stdlib.go b/vendor/github.com/go-kit/kit/log/stdlib.go deleted file mode 100644 index ff96b5de..00000000 --- a/vendor/github.com/go-kit/kit/log/stdlib.go +++ /dev/null @@ -1,116 +0,0 @@ -package log - -import ( - "io" - "log" - "regexp" - "strings" -) - -// StdlibWriter implements io.Writer by invoking the stdlib log.Print. It's -// designed to be passed to a Go kit logger as the writer, for cases where -// it's necessary to redirect all Go kit log output to the stdlib logger. -// -// If you have any choice in the matter, you shouldn't use this. Prefer to -// redirect the stdlib log to the Go kit logger via NewStdlibAdapter. -type StdlibWriter struct{} - -// Write implements io.Writer. -func (w StdlibWriter) Write(p []byte) (int, error) { - log.Print(strings.TrimSpace(string(p))) - return len(p), nil -} - -// StdlibAdapter wraps a Logger and allows it to be passed to the stdlib -// logger's SetOutput. It will extract date/timestamps, filenames, and -// messages, and place them under relevant keys. -type StdlibAdapter struct { - Logger - timestampKey string - fileKey string - messageKey string -} - -// StdlibAdapterOption sets a parameter for the StdlibAdapter. -type StdlibAdapterOption func(*StdlibAdapter) - -// TimestampKey sets the key for the timestamp field. By default, it's "ts". -func TimestampKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.timestampKey = key } -} - -// FileKey sets the key for the file and line field. By default, it's "caller". -func FileKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.fileKey = key } -} - -// MessageKey sets the key for the actual log message. By default, it's "msg". -func MessageKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.messageKey = key } -} - -// NewStdlibAdapter returns a new StdlibAdapter wrapper around the passed -// logger. It's designed to be passed to log.SetOutput. -func NewStdlibAdapter(logger Logger, options ...StdlibAdapterOption) io.Writer { - a := StdlibAdapter{ - Logger: logger, - timestampKey: "ts", - fileKey: "caller", - messageKey: "msg", - } - for _, option := range options { - option(&a) - } - return a -} - -func (a StdlibAdapter) Write(p []byte) (int, error) { - result := subexps(p) - keyvals := []interface{}{} - var timestamp string - if date, ok := result["date"]; ok && date != "" { - timestamp = date - } - if time, ok := result["time"]; ok && time != "" { - if timestamp != "" { - timestamp += " " - } - timestamp += time - } - if timestamp != "" { - keyvals = append(keyvals, a.timestampKey, timestamp) - } - if file, ok := result["file"]; ok && file != "" { - keyvals = append(keyvals, a.fileKey, file) - } - if msg, ok := result["msg"]; ok { - keyvals = append(keyvals, a.messageKey, msg) - } - if err := a.Logger.Log(keyvals...); err != nil { - return 0, err - } - return len(p), nil -} - -const ( - logRegexpDate = `(?P[0-9]{4}/[0-9]{2}/[0-9]{2})?[ ]?` - logRegexpTime = `(?P