├── Futures-Go-demo ├── .idea │ ├── Futures-Go-demo.iml │ ├── misc.xml │ ├── modules.xml │ └── workspace.xml ├── Gopkg.lock ├── Gopkg.toml ├── LICENSE ├── README.md ├── _vendor-20190121094707 │ ├── github.com │ │ ├── dgrijalva │ │ │ └── jwt-go │ │ │ │ ├── .gitignore │ │ │ │ ├── .travis.yml │ │ │ │ ├── LICENSE │ │ │ │ ├── MIGRATION_GUIDE.md │ │ │ │ ├── README.md │ │ │ │ ├── VERSION_HISTORY.md │ │ │ │ ├── claims.go │ │ │ │ ├── doc.go │ │ │ │ ├── ecdsa.go │ │ │ │ ├── ecdsa_utils.go │ │ │ │ ├── errors.go │ │ │ │ ├── hmac.go │ │ │ │ ├── map_claims.go │ │ │ │ ├── none.go │ │ │ │ ├── parser.go │ │ │ │ ├── rsa.go │ │ │ │ ├── rsa_pss.go │ │ │ │ ├── rsa_utils.go │ │ │ │ ├── signing_method.go │ │ │ │ └── token.go │ │ ├── gorilla │ │ │ └── websocket │ │ │ │ ├── .gitignore │ │ │ │ ├── .travis.yml │ │ │ │ ├── AUTHORS │ │ │ │ ├── LICENSE │ │ │ │ ├── README.md │ │ │ │ ├── client.go │ │ │ │ ├── client_clone.go │ │ │ │ ├── client_clone_legacy.go │ │ │ │ ├── compression.go │ │ │ │ ├── conn.go │ │ │ │ ├── conn_write.go │ │ │ │ ├── conn_write_legacy.go │ │ │ │ ├── doc.go │ │ │ │ ├── json.go │ │ │ │ ├── mask.go │ │ │ │ ├── mask_safe.go │ │ │ │ ├── prepared.go │ │ │ │ ├── proxy.go │ │ │ │ ├── server.go │ │ │ │ ├── trace.go │ │ │ │ ├── trace_17.go │ │ │ │ ├── util.go │ │ │ │ └── x_net_proxy.go │ │ └── spf13 │ │ │ └── cast │ │ │ ├── .gitignore │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── Makefile │ │ │ ├── README.md │ │ │ ├── cast.go │ │ │ ├── caste.go │ │ │ ├── go.mod │ │ │ └── go.sum │ └── golang.org │ │ └── x │ │ └── net │ │ ├── AUTHORS │ │ ├── CONTRIBUTORS │ │ ├── LICENSE │ │ ├── PATENTS │ │ └── websocket │ │ ├── client.go │ │ ├── dial.go │ │ ├── hybi.go │ │ ├── server.go │ │ └── websocket.go ├── config │ └── config.go ├── glide.yaml ├── main │ ├── ipmain │ ├── main.go │ ├── mainip │ └── wsmain ├── services │ ├── Market.go │ └── Market_test.go ├── untils │ ├── CryptoUtil.go │ └── Untils.go ├── vendor │ ├── github.com │ │ ├── dgrijalva │ │ │ └── jwt-go │ │ │ │ ├── .gitignore │ │ │ │ ├── .travis.yml │ │ │ │ ├── LICENSE │ │ │ │ ├── MIGRATION_GUIDE.md │ │ │ │ ├── README.md │ │ │ │ ├── VERSION_HISTORY.md │ │ │ │ ├── claims.go │ │ │ │ ├── doc.go │ │ │ │ ├── ecdsa.go │ │ │ │ ├── ecdsa_utils.go │ │ │ │ ├── errors.go │ │ │ │ ├── hmac.go │ │ │ │ ├── map_claims.go │ │ │ │ ├── none.go │ │ │ │ ├── parser.go │ │ │ │ ├── rsa.go │ │ │ │ ├── rsa_pss.go │ │ │ │ ├── rsa_utils.go │ │ │ │ ├── signing_method.go │ │ │ │ └── token.go │ │ ├── gorilla │ │ │ └── websocket │ │ │ │ ├── .gitignore │ │ │ │ ├── .travis.yml │ │ │ │ ├── AUTHORS │ │ │ │ ├── LICENSE │ │ │ │ ├── README.md │ │ │ │ ├── client.go │ │ │ │ ├── client_clone.go │ │ │ │ ├── client_clone_legacy.go │ │ │ │ ├── compression.go │ │ │ │ ├── conn.go │ │ │ │ ├── conn_write.go │ │ │ │ ├── conn_write_legacy.go │ │ │ │ ├── doc.go │ │ │ │ ├── json.go │ │ │ │ ├── mask.go │ │ │ │ ├── mask_safe.go │ │ │ │ ├── prepared.go │ │ │ │ ├── proxy.go │ │ │ │ ├── server.go │ │ │ │ ├── trace.go │ │ │ │ ├── trace_17.go │ │ │ │ ├── util.go │ │ │ │ └── x_net_proxy.go │ │ └── spf13 │ │ │ └── cast │ │ │ ├── .gitignore │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── Makefile │ │ │ ├── README.md │ │ │ ├── cast.go │ │ │ ├── caste.go │ │ │ ├── go.mod │ │ │ └── go.sum │ └── golang.org │ │ └── x │ │ └── net │ │ ├── AUTHORS │ │ ├── CONTRIBUTORS │ │ ├── LICENSE │ │ ├── PATENTS │ │ └── websocket │ │ ├── client.go │ │ ├── dial.go │ │ ├── hybi.go │ │ ├── server.go │ │ └── websocket.go └── websocket │ ├── ws.go │ ├── ws_new.go │ └── ws_order.go ├── LICENSE └── README.md /Futures-Go-demo/.idea/Futures-Go-demo.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Futures-Go-demo/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /Futures-Go-demo/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Futures-Go-demo/Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | name = "github.com/dgrijalva/jwt-go" 6 | packages = ["."] 7 | revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" 8 | version = "v3.2.0" 9 | 10 | [[projects]] 11 | name = "github.com/gorilla/websocket" 12 | packages = ["."] 13 | revision = "66b9c49e59c6c48f0ffce28c2d8b8a5678502c6d" 14 | version = "v1.4.0" 15 | 16 | [[projects]] 17 | name = "github.com/spf13/cast" 18 | packages = ["."] 19 | revision = "8c9545af88b134710ab1cd196795e7f2388358d7" 20 | version = "v1.3.0" 21 | 22 | [[projects]] 23 | branch = "master" 24 | name = "golang.org/x/net" 25 | packages = ["websocket"] 26 | revision = "ed066c81e75eba56dd9bd2139ade88125b855585" 27 | 28 | [solve-meta] 29 | analyzer-name = "dep" 30 | analyzer-version = 1 31 | inputs-digest = "321c01bd23c7524ac151248aa50eae968611566a9645a3c406e63e009dabd5a1" 32 | solver-name = "gps-cdcl" 33 | solver-version = 1 34 | -------------------------------------------------------------------------------- /Futures-Go-demo/Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | # 22 | # [prune] 23 | # non-go = false 24 | # go-tests = true 25 | # unused-packages = true 26 | 27 | 28 | [[constraint]] 29 | name = "github.com/dgrijalva/jwt-go" 30 | version = "3.2.0" 31 | 32 | [[constraint]] 33 | name = "github.com/gorilla/websocket" 34 | version = "1.4.0" 35 | 36 | [[constraint]] 37 | name = "github.com/spf13/cast" 38 | version = "1.3.0" 39 | 40 | [[constraint]] 41 | branch = "master" 42 | name = "golang.org/x/net" 43 | 44 | [prune] 45 | go-tests = true 46 | unused-packages = true 47 | -------------------------------------------------------------------------------- /Futures-Go-demo/README.md: -------------------------------------------------------------------------------- 1 | # HBDM - Go Language 2 | 包含 WebSocket 行情,交易 API ; 3 | WebSocket 订单推送 API ; 4 | REST 行情,交易 API 5 | 6 | ## 依赖管理 7 | 支持Dep和Glide管理依赖 8 | 9 | ## 实例代码 10 | ### 配置文件 11 | 修改 [配置文件](./config/config.go)中*todo*的部分,替换成自己的Key和自己要连接的服务地址 12 | ### 测试用例 13 | 可以参考[接口测试](./services/Market_test.go) 14 | ### 运行 15 | go run main/main.go 16 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | bin 3 | 4 | 5 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | script: 4 | - go vet ./... 5 | - go test -v ./... 6 | 7 | go: 8 | - 1.3 9 | - 1.4 10 | - 1.5 11 | - 1.6 12 | - 1.7 13 | - tip 14 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Dave Grijalva 2 | 3 | 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: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | 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. 8 | 9 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md: -------------------------------------------------------------------------------- 1 | ## Migration Guide from v2 -> v3 2 | 3 | Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code. 4 | 5 | ### `Token.Claims` is now an interface type 6 | 7 | The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`. 8 | 9 | `MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property. 10 | 11 | The old example for parsing a token looked like this.. 12 | 13 | ```go 14 | if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { 15 | fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) 16 | } 17 | ``` 18 | 19 | is now directly mapped to... 20 | 21 | ```go 22 | if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { 23 | claims := token.Claims.(jwt.MapClaims) 24 | fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) 25 | } 26 | ``` 27 | 28 | `StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type. 29 | 30 | ```go 31 | type MyCustomClaims struct { 32 | User string 33 | *StandardClaims 34 | } 35 | 36 | if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil { 37 | claims := token.Claims.(*MyCustomClaims) 38 | fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt) 39 | } 40 | ``` 41 | 42 | ### `ParseFromRequest` has been moved 43 | 44 | To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`. 45 | 46 | `Extractors` do the work of picking the token string out of a request. The interface is simple and composable. 47 | 48 | This simple parsing example: 49 | 50 | ```go 51 | if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil { 52 | fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) 53 | } 54 | ``` 55 | 56 | is directly mapped to: 57 | 58 | ```go 59 | if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil { 60 | claims := token.Claims.(jwt.MapClaims) 61 | fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) 62 | } 63 | ``` 64 | 65 | There are several concrete `Extractor` types provided for your convenience: 66 | 67 | * `HeaderExtractor` will search a list of headers until one contains content. 68 | * `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content. 69 | * `MultiExtractor` will try a list of `Extractors` in order until one returns content. 70 | * `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token. 71 | * `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument 72 | * `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header 73 | 74 | 75 | ### RSA signing methods no longer accept `[]byte` keys 76 | 77 | Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse. 78 | 79 | To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types. 80 | 81 | ```go 82 | func keyLookupFunc(*Token) (interface{}, error) { 83 | // Don't forget to validate the alg is what you expect: 84 | if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { 85 | return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) 86 | } 87 | 88 | // Look up key 89 | key, err := lookupPublicKey(token.Header["kid"]) 90 | if err != nil { 91 | return nil, err 92 | } 93 | 94 | // Unpack key from PEM encoded PKCS8 95 | return jwt.ParseRSAPublicKeyFromPEM(key) 96 | } 97 | ``` 98 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/claims.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/subtle" 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | // For a type to be a Claims object, it must just have a Valid method that determines 10 | // if the token is invalid for any supported reason 11 | type Claims interface { 12 | Valid() error 13 | } 14 | 15 | // Structured version of Claims Section, as referenced at 16 | // https://tools.ietf.org/html/rfc7519#section-4.1 17 | // See examples for how to use this with your own claim types 18 | type StandardClaims struct { 19 | Audience string `json:"aud,omitempty"` 20 | ExpiresAt int64 `json:"exp,omitempty"` 21 | Id string `json:"jti,omitempty"` 22 | IssuedAt int64 `json:"iat,omitempty"` 23 | Issuer string `json:"iss,omitempty"` 24 | NotBefore int64 `json:"nbf,omitempty"` 25 | Subject string `json:"sub,omitempty"` 26 | } 27 | 28 | // Validates time based claims "exp, iat, nbf". 29 | // There is no accounting for clock skew. 30 | // As well, if any of the above claims are not in the token, it will still 31 | // be considered a valid claim. 32 | func (c StandardClaims) Valid() error { 33 | vErr := new(ValidationError) 34 | now := TimeFunc().Unix() 35 | 36 | // The claims below are optional, by default, so if they are set to the 37 | // default value in Go, let's not fail the verification for them. 38 | if c.VerifyExpiresAt(now, false) == false { 39 | delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) 40 | vErr.Inner = fmt.Errorf("token is expired by %v", delta) 41 | vErr.Errors |= ValidationErrorExpired 42 | } 43 | 44 | if c.VerifyIssuedAt(now, false) == false { 45 | vErr.Inner = fmt.Errorf("Token used before issued") 46 | vErr.Errors |= ValidationErrorIssuedAt 47 | } 48 | 49 | if c.VerifyNotBefore(now, false) == false { 50 | vErr.Inner = fmt.Errorf("token is not valid yet") 51 | vErr.Errors |= ValidationErrorNotValidYet 52 | } 53 | 54 | if vErr.valid() { 55 | return nil 56 | } 57 | 58 | return vErr 59 | } 60 | 61 | // Compares the aud claim against cmp. 62 | // If required is false, this method will return true if the value matches or is unset 63 | func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { 64 | return verifyAud(c.Audience, cmp, req) 65 | } 66 | 67 | // Compares the exp claim against cmp. 68 | // If required is false, this method will return true if the value matches or is unset 69 | func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { 70 | return verifyExp(c.ExpiresAt, cmp, req) 71 | } 72 | 73 | // Compares the iat claim against cmp. 74 | // If required is false, this method will return true if the value matches or is unset 75 | func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { 76 | return verifyIat(c.IssuedAt, cmp, req) 77 | } 78 | 79 | // Compares the iss claim against cmp. 80 | // If required is false, this method will return true if the value matches or is unset 81 | func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { 82 | return verifyIss(c.Issuer, cmp, req) 83 | } 84 | 85 | // Compares the nbf claim against cmp. 86 | // If required is false, this method will return true if the value matches or is unset 87 | func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { 88 | return verifyNbf(c.NotBefore, cmp, req) 89 | } 90 | 91 | // ----- helpers 92 | 93 | func verifyAud(aud string, cmp string, required bool) bool { 94 | if aud == "" { 95 | return !required 96 | } 97 | if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 { 98 | return true 99 | } else { 100 | return false 101 | } 102 | } 103 | 104 | func verifyExp(exp int64, now int64, required bool) bool { 105 | if exp == 0 { 106 | return !required 107 | } 108 | return now <= exp 109 | } 110 | 111 | func verifyIat(iat int64, now int64, required bool) bool { 112 | if iat == 0 { 113 | return !required 114 | } 115 | return now >= iat 116 | } 117 | 118 | func verifyIss(iss string, cmp string, required bool) bool { 119 | if iss == "" { 120 | return !required 121 | } 122 | if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { 123 | return true 124 | } else { 125 | return false 126 | } 127 | } 128 | 129 | func verifyNbf(nbf int64, now int64, required bool) bool { 130 | if nbf == 0 { 131 | return !required 132 | } 133 | return now >= nbf 134 | } 135 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/doc.go: -------------------------------------------------------------------------------- 1 | // Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html 2 | // 3 | // See README.md for more info. 4 | package jwt 5 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/ecdsa.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/ecdsa" 6 | "crypto/rand" 7 | "errors" 8 | "math/big" 9 | ) 10 | 11 | var ( 12 | // Sadly this is missing from crypto/ecdsa compared to crypto/rsa 13 | ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") 14 | ) 15 | 16 | // Implements the ECDSA family of signing methods signing methods 17 | // Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification 18 | type SigningMethodECDSA struct { 19 | Name string 20 | Hash crypto.Hash 21 | KeySize int 22 | CurveBits int 23 | } 24 | 25 | // Specific instances for EC256 and company 26 | var ( 27 | SigningMethodES256 *SigningMethodECDSA 28 | SigningMethodES384 *SigningMethodECDSA 29 | SigningMethodES512 *SigningMethodECDSA 30 | ) 31 | 32 | func init() { 33 | // ES256 34 | SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} 35 | RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { 36 | return SigningMethodES256 37 | }) 38 | 39 | // ES384 40 | SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} 41 | RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { 42 | return SigningMethodES384 43 | }) 44 | 45 | // ES512 46 | SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} 47 | RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { 48 | return SigningMethodES512 49 | }) 50 | } 51 | 52 | func (m *SigningMethodECDSA) Alg() string { 53 | return m.Name 54 | } 55 | 56 | // Implements the Verify method from SigningMethod 57 | // For this verify method, key must be an ecdsa.PublicKey struct 58 | func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { 59 | var err error 60 | 61 | // Decode the signature 62 | var sig []byte 63 | if sig, err = DecodeSegment(signature); err != nil { 64 | return err 65 | } 66 | 67 | // Get the key 68 | var ecdsaKey *ecdsa.PublicKey 69 | switch k := key.(type) { 70 | case *ecdsa.PublicKey: 71 | ecdsaKey = k 72 | default: 73 | return ErrInvalidKeyType 74 | } 75 | 76 | if len(sig) != 2*m.KeySize { 77 | return ErrECDSAVerification 78 | } 79 | 80 | r := big.NewInt(0).SetBytes(sig[:m.KeySize]) 81 | s := big.NewInt(0).SetBytes(sig[m.KeySize:]) 82 | 83 | // Create hasher 84 | if !m.Hash.Available() { 85 | return ErrHashUnavailable 86 | } 87 | hasher := m.Hash.New() 88 | hasher.Write([]byte(signingString)) 89 | 90 | // Verify the signature 91 | if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { 92 | return nil 93 | } else { 94 | return ErrECDSAVerification 95 | } 96 | } 97 | 98 | // Implements the Sign method from SigningMethod 99 | // For this signing method, key must be an ecdsa.PrivateKey struct 100 | func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { 101 | // Get the key 102 | var ecdsaKey *ecdsa.PrivateKey 103 | switch k := key.(type) { 104 | case *ecdsa.PrivateKey: 105 | ecdsaKey = k 106 | default: 107 | return "", ErrInvalidKeyType 108 | } 109 | 110 | // Create the hasher 111 | if !m.Hash.Available() { 112 | return "", ErrHashUnavailable 113 | } 114 | 115 | hasher := m.Hash.New() 116 | hasher.Write([]byte(signingString)) 117 | 118 | // Sign the string and return r, s 119 | if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { 120 | curveBits := ecdsaKey.Curve.Params().BitSize 121 | 122 | if m.CurveBits != curveBits { 123 | return "", ErrInvalidKey 124 | } 125 | 126 | keyBytes := curveBits / 8 127 | if curveBits%8 > 0 { 128 | keyBytes += 1 129 | } 130 | 131 | // We serialize the outpus (r and s) into big-endian byte arrays and pad 132 | // them with zeros on the left to make sure the sizes work out. Both arrays 133 | // must be keyBytes long, and the output must be 2*keyBytes long. 134 | rBytes := r.Bytes() 135 | rBytesPadded := make([]byte, keyBytes) 136 | copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) 137 | 138 | sBytes := s.Bytes() 139 | sBytesPadded := make([]byte, keyBytes) 140 | copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) 141 | 142 | out := append(rBytesPadded, sBytesPadded...) 143 | 144 | return EncodeSegment(out), nil 145 | } else { 146 | return "", err 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/ecdsa_utils.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/ecdsa" 5 | "crypto/x509" 6 | "encoding/pem" 7 | "errors" 8 | ) 9 | 10 | var ( 11 | ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") 12 | ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") 13 | ) 14 | 15 | // Parse PEM encoded Elliptic Curve Private Key Structure 16 | func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { 17 | var err error 18 | 19 | // Parse PEM block 20 | var block *pem.Block 21 | if block, _ = pem.Decode(key); block == nil { 22 | return nil, ErrKeyMustBePEMEncoded 23 | } 24 | 25 | // Parse the key 26 | var parsedKey interface{} 27 | if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { 28 | return nil, err 29 | } 30 | 31 | var pkey *ecdsa.PrivateKey 32 | var ok bool 33 | if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { 34 | return nil, ErrNotECPrivateKey 35 | } 36 | 37 | return pkey, nil 38 | } 39 | 40 | // Parse PEM encoded PKCS1 or PKCS8 public key 41 | func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { 42 | var err error 43 | 44 | // Parse PEM block 45 | var block *pem.Block 46 | if block, _ = pem.Decode(key); block == nil { 47 | return nil, ErrKeyMustBePEMEncoded 48 | } 49 | 50 | // Parse the key 51 | var parsedKey interface{} 52 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 53 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil { 54 | parsedKey = cert.PublicKey 55 | } else { 56 | return nil, err 57 | } 58 | } 59 | 60 | var pkey *ecdsa.PublicKey 61 | var ok bool 62 | if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { 63 | return nil, ErrNotECPublicKey 64 | } 65 | 66 | return pkey, nil 67 | } 68 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/errors.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | // Error constants 8 | var ( 9 | ErrInvalidKey = errors.New("key is invalid") 10 | ErrInvalidKeyType = errors.New("key is of invalid type") 11 | ErrHashUnavailable = errors.New("the requested hash function is unavailable") 12 | ) 13 | 14 | // The errors that might occur when parsing and validating a token 15 | const ( 16 | ValidationErrorMalformed uint32 = 1 << iota // Token is malformed 17 | ValidationErrorUnverifiable // Token could not be verified because of signing problems 18 | ValidationErrorSignatureInvalid // Signature validation failed 19 | 20 | // Standard Claim validation errors 21 | ValidationErrorAudience // AUD validation failed 22 | ValidationErrorExpired // EXP validation failed 23 | ValidationErrorIssuedAt // IAT validation failed 24 | ValidationErrorIssuer // ISS validation failed 25 | ValidationErrorNotValidYet // NBF validation failed 26 | ValidationErrorId // JTI validation failed 27 | ValidationErrorClaimsInvalid // Generic claims validation error 28 | ) 29 | 30 | // Helper for constructing a ValidationError with a string error message 31 | func NewValidationError(errorText string, errorFlags uint32) *ValidationError { 32 | return &ValidationError{ 33 | text: errorText, 34 | Errors: errorFlags, 35 | } 36 | } 37 | 38 | // The error from Parse if token is not valid 39 | type ValidationError struct { 40 | Inner error // stores the error returned by external dependencies, i.e.: KeyFunc 41 | Errors uint32 // bitfield. see ValidationError... constants 42 | text string // errors that do not have a valid error just have text 43 | } 44 | 45 | // Validation error is an error type 46 | func (e ValidationError) Error() string { 47 | if e.Inner != nil { 48 | return e.Inner.Error() 49 | } else if e.text != "" { 50 | return e.text 51 | } else { 52 | return "token is invalid" 53 | } 54 | } 55 | 56 | // No errors 57 | func (e *ValidationError) valid() bool { 58 | return e.Errors == 0 59 | } 60 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/hmac.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/hmac" 6 | "errors" 7 | ) 8 | 9 | // Implements the HMAC-SHA family of signing methods signing methods 10 | // Expects key type of []byte for both signing and validation 11 | type SigningMethodHMAC struct { 12 | Name string 13 | Hash crypto.Hash 14 | } 15 | 16 | // Specific instances for HS256 and company 17 | var ( 18 | SigningMethodHS256 *SigningMethodHMAC 19 | SigningMethodHS384 *SigningMethodHMAC 20 | SigningMethodHS512 *SigningMethodHMAC 21 | ErrSignatureInvalid = errors.New("signature is invalid") 22 | ) 23 | 24 | func init() { 25 | // HS256 26 | SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} 27 | RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { 28 | return SigningMethodHS256 29 | }) 30 | 31 | // HS384 32 | SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} 33 | RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { 34 | return SigningMethodHS384 35 | }) 36 | 37 | // HS512 38 | SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} 39 | RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { 40 | return SigningMethodHS512 41 | }) 42 | } 43 | 44 | func (m *SigningMethodHMAC) Alg() string { 45 | return m.Name 46 | } 47 | 48 | // Verify the signature of HSXXX tokens. Returns nil if the signature is valid. 49 | func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { 50 | // Verify the key is the right type 51 | keyBytes, ok := key.([]byte) 52 | if !ok { 53 | return ErrInvalidKeyType 54 | } 55 | 56 | // Decode signature, for comparison 57 | sig, err := DecodeSegment(signature) 58 | if err != nil { 59 | return err 60 | } 61 | 62 | // Can we use the specified hashing method? 63 | if !m.Hash.Available() { 64 | return ErrHashUnavailable 65 | } 66 | 67 | // This signing method is symmetric, so we validate the signature 68 | // by reproducing the signature from the signing string and key, then 69 | // comparing that against the provided signature. 70 | hasher := hmac.New(m.Hash.New, keyBytes) 71 | hasher.Write([]byte(signingString)) 72 | if !hmac.Equal(sig, hasher.Sum(nil)) { 73 | return ErrSignatureInvalid 74 | } 75 | 76 | // No validation errors. Signature is good. 77 | return nil 78 | } 79 | 80 | // Implements the Sign method from SigningMethod for this signing method. 81 | // Key must be []byte 82 | func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { 83 | if keyBytes, ok := key.([]byte); ok { 84 | if !m.Hash.Available() { 85 | return "", ErrHashUnavailable 86 | } 87 | 88 | hasher := hmac.New(m.Hash.New, keyBytes) 89 | hasher.Write([]byte(signingString)) 90 | 91 | return EncodeSegment(hasher.Sum(nil)), nil 92 | } 93 | 94 | return "", ErrInvalidKeyType 95 | } 96 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/map_claims.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | // "fmt" 7 | ) 8 | 9 | // Claims type that uses the map[string]interface{} for JSON decoding 10 | // This is the default claims type if you don't supply one 11 | type MapClaims map[string]interface{} 12 | 13 | // Compares the aud claim against cmp. 14 | // If required is false, this method will return true if the value matches or is unset 15 | func (m MapClaims) VerifyAudience(cmp string, req bool) bool { 16 | aud, _ := m["aud"].(string) 17 | return verifyAud(aud, cmp, req) 18 | } 19 | 20 | // Compares the exp claim against cmp. 21 | // If required is false, this method will return true if the value matches or is unset 22 | func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { 23 | switch exp := m["exp"].(type) { 24 | case float64: 25 | return verifyExp(int64(exp), cmp, req) 26 | case json.Number: 27 | v, _ := exp.Int64() 28 | return verifyExp(v, cmp, req) 29 | } 30 | return req == false 31 | } 32 | 33 | // Compares the iat claim against cmp. 34 | // If required is false, this method will return true if the value matches or is unset 35 | func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { 36 | switch iat := m["iat"].(type) { 37 | case float64: 38 | return verifyIat(int64(iat), cmp, req) 39 | case json.Number: 40 | v, _ := iat.Int64() 41 | return verifyIat(v, cmp, req) 42 | } 43 | return req == false 44 | } 45 | 46 | // Compares the iss claim against cmp. 47 | // If required is false, this method will return true if the value matches or is unset 48 | func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { 49 | iss, _ := m["iss"].(string) 50 | return verifyIss(iss, cmp, req) 51 | } 52 | 53 | // Compares the nbf claim against cmp. 54 | // If required is false, this method will return true if the value matches or is unset 55 | func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { 56 | switch nbf := m["nbf"].(type) { 57 | case float64: 58 | return verifyNbf(int64(nbf), cmp, req) 59 | case json.Number: 60 | v, _ := nbf.Int64() 61 | return verifyNbf(v, cmp, req) 62 | } 63 | return req == false 64 | } 65 | 66 | // Validates time based claims "exp, iat, nbf". 67 | // There is no accounting for clock skew. 68 | // As well, if any of the above claims are not in the token, it will still 69 | // be considered a valid claim. 70 | func (m MapClaims) Valid() error { 71 | vErr := new(ValidationError) 72 | now := TimeFunc().Unix() 73 | 74 | if m.VerifyExpiresAt(now, false) == false { 75 | vErr.Inner = errors.New("Token is expired") 76 | vErr.Errors |= ValidationErrorExpired 77 | } 78 | 79 | if m.VerifyIssuedAt(now, false) == false { 80 | vErr.Inner = errors.New("Token used before issued") 81 | vErr.Errors |= ValidationErrorIssuedAt 82 | } 83 | 84 | if m.VerifyNotBefore(now, false) == false { 85 | vErr.Inner = errors.New("Token is not valid yet") 86 | vErr.Errors |= ValidationErrorNotValidYet 87 | } 88 | 89 | if vErr.valid() { 90 | return nil 91 | } 92 | 93 | return vErr 94 | } 95 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/none.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | // Implements the none signing method. This is required by the spec 4 | // but you probably should never use it. 5 | var SigningMethodNone *signingMethodNone 6 | 7 | const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" 8 | 9 | var NoneSignatureTypeDisallowedError error 10 | 11 | type signingMethodNone struct{} 12 | type unsafeNoneMagicConstant string 13 | 14 | func init() { 15 | SigningMethodNone = &signingMethodNone{} 16 | NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) 17 | 18 | RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { 19 | return SigningMethodNone 20 | }) 21 | } 22 | 23 | func (m *signingMethodNone) Alg() string { 24 | return "none" 25 | } 26 | 27 | // Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key 28 | func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { 29 | // Key must be UnsafeAllowNoneSignatureType to prevent accidentally 30 | // accepting 'none' signing method 31 | if _, ok := key.(unsafeNoneMagicConstant); !ok { 32 | return NoneSignatureTypeDisallowedError 33 | } 34 | // If signing method is none, signature must be an empty string 35 | if signature != "" { 36 | return NewValidationError( 37 | "'none' signing method with non-empty signature", 38 | ValidationErrorSignatureInvalid, 39 | ) 40 | } 41 | 42 | // Accept 'none' signing method. 43 | return nil 44 | } 45 | 46 | // Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key 47 | func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { 48 | if _, ok := key.(unsafeNoneMagicConstant); ok { 49 | return "", nil 50 | } 51 | return "", NoneSignatureTypeDisallowedError 52 | } 53 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/parser.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "strings" 8 | ) 9 | 10 | type Parser struct { 11 | ValidMethods []string // If populated, only these methods will be considered valid 12 | UseJSONNumber bool // Use JSON Number format in JSON decoder 13 | SkipClaimsValidation bool // Skip claims validation during token parsing 14 | } 15 | 16 | // Parse, validate, and return a token. 17 | // keyFunc will receive the parsed token and should return the key for validating. 18 | // If everything is kosher, err will be nil 19 | func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { 20 | return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) 21 | } 22 | 23 | func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { 24 | token, parts, err := p.ParseUnverified(tokenString, claims) 25 | if err != nil { 26 | return token, err 27 | } 28 | 29 | // Verify signing method is in the required set 30 | if p.ValidMethods != nil { 31 | var signingMethodValid = false 32 | var alg = token.Method.Alg() 33 | for _, m := range p.ValidMethods { 34 | if m == alg { 35 | signingMethodValid = true 36 | break 37 | } 38 | } 39 | if !signingMethodValid { 40 | // signing method is not in the listed set 41 | return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) 42 | } 43 | } 44 | 45 | // Lookup key 46 | var key interface{} 47 | if keyFunc == nil { 48 | // keyFunc was not provided. short circuiting validation 49 | return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) 50 | } 51 | if key, err = keyFunc(token); err != nil { 52 | // keyFunc returned an error 53 | if ve, ok := err.(*ValidationError); ok { 54 | return token, ve 55 | } 56 | return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} 57 | } 58 | 59 | vErr := &ValidationError{} 60 | 61 | // Validate Claims 62 | if !p.SkipClaimsValidation { 63 | if err := token.Claims.Valid(); err != nil { 64 | 65 | // If the Claims Valid returned an error, check if it is a validation error, 66 | // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set 67 | if e, ok := err.(*ValidationError); !ok { 68 | vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} 69 | } else { 70 | vErr = e 71 | } 72 | } 73 | } 74 | 75 | // Perform validation 76 | token.Signature = parts[2] 77 | if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { 78 | vErr.Inner = err 79 | vErr.Errors |= ValidationErrorSignatureInvalid 80 | } 81 | 82 | if vErr.valid() { 83 | token.Valid = true 84 | return token, nil 85 | } 86 | 87 | return token, vErr 88 | } 89 | 90 | // WARNING: Don't use this method unless you know what you're doing 91 | // 92 | // This method parses the token but doesn't validate the signature. It's only 93 | // ever useful in cases where you know the signature is valid (because it has 94 | // been checked previously in the stack) and you want to extract values from 95 | // it. 96 | func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { 97 | parts = strings.Split(tokenString, ".") 98 | if len(parts) != 3 { 99 | return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) 100 | } 101 | 102 | token = &Token{Raw: tokenString} 103 | 104 | // parse Header 105 | var headerBytes []byte 106 | if headerBytes, err = DecodeSegment(parts[0]); err != nil { 107 | if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { 108 | return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) 109 | } 110 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 111 | } 112 | if err = json.Unmarshal(headerBytes, &token.Header); err != nil { 113 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 114 | } 115 | 116 | // parse Claims 117 | var claimBytes []byte 118 | token.Claims = claims 119 | 120 | if claimBytes, err = DecodeSegment(parts[1]); err != nil { 121 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 122 | } 123 | dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) 124 | if p.UseJSONNumber { 125 | dec.UseNumber() 126 | } 127 | // JSON Decode. Special case for map type to avoid weird pointer behavior 128 | if c, ok := token.Claims.(MapClaims); ok { 129 | err = dec.Decode(&c) 130 | } else { 131 | err = dec.Decode(&claims) 132 | } 133 | // Handle decode error 134 | if err != nil { 135 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 136 | } 137 | 138 | // Lookup signature method 139 | if method, ok := token.Header["alg"].(string); ok { 140 | if token.Method = GetSigningMethod(method); token.Method == nil { 141 | return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) 142 | } 143 | } else { 144 | return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) 145 | } 146 | 147 | return token, parts, nil 148 | } 149 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/rsa.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | ) 8 | 9 | // Implements the RSA family of signing methods signing methods 10 | // Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation 11 | type SigningMethodRSA struct { 12 | Name string 13 | Hash crypto.Hash 14 | } 15 | 16 | // Specific instances for RS256 and company 17 | var ( 18 | SigningMethodRS256 *SigningMethodRSA 19 | SigningMethodRS384 *SigningMethodRSA 20 | SigningMethodRS512 *SigningMethodRSA 21 | ) 22 | 23 | func init() { 24 | // RS256 25 | SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} 26 | RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { 27 | return SigningMethodRS256 28 | }) 29 | 30 | // RS384 31 | SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} 32 | RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { 33 | return SigningMethodRS384 34 | }) 35 | 36 | // RS512 37 | SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} 38 | RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { 39 | return SigningMethodRS512 40 | }) 41 | } 42 | 43 | func (m *SigningMethodRSA) Alg() string { 44 | return m.Name 45 | } 46 | 47 | // Implements the Verify method from SigningMethod 48 | // For this signing method, must be an *rsa.PublicKey structure. 49 | func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { 50 | var err error 51 | 52 | // Decode the signature 53 | var sig []byte 54 | if sig, err = DecodeSegment(signature); err != nil { 55 | return err 56 | } 57 | 58 | var rsaKey *rsa.PublicKey 59 | var ok bool 60 | 61 | if rsaKey, ok = key.(*rsa.PublicKey); !ok { 62 | return ErrInvalidKeyType 63 | } 64 | 65 | // Create hasher 66 | if !m.Hash.Available() { 67 | return ErrHashUnavailable 68 | } 69 | hasher := m.Hash.New() 70 | hasher.Write([]byte(signingString)) 71 | 72 | // Verify the signature 73 | return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) 74 | } 75 | 76 | // Implements the Sign method from SigningMethod 77 | // For this signing method, must be an *rsa.PrivateKey structure. 78 | func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { 79 | var rsaKey *rsa.PrivateKey 80 | var ok bool 81 | 82 | // Validate type of key 83 | if rsaKey, ok = key.(*rsa.PrivateKey); !ok { 84 | return "", ErrInvalidKey 85 | } 86 | 87 | // Create the hasher 88 | if !m.Hash.Available() { 89 | return "", ErrHashUnavailable 90 | } 91 | 92 | hasher := m.Hash.New() 93 | hasher.Write([]byte(signingString)) 94 | 95 | // Sign the string and return the encoded bytes 96 | if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { 97 | return EncodeSegment(sigBytes), nil 98 | } else { 99 | return "", err 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/rsa_pss.go: -------------------------------------------------------------------------------- 1 | // +build go1.4 2 | 3 | package jwt 4 | 5 | import ( 6 | "crypto" 7 | "crypto/rand" 8 | "crypto/rsa" 9 | ) 10 | 11 | // Implements the RSAPSS family of signing methods signing methods 12 | type SigningMethodRSAPSS struct { 13 | *SigningMethodRSA 14 | Options *rsa.PSSOptions 15 | } 16 | 17 | // Specific instances for RS/PS and company 18 | var ( 19 | SigningMethodPS256 *SigningMethodRSAPSS 20 | SigningMethodPS384 *SigningMethodRSAPSS 21 | SigningMethodPS512 *SigningMethodRSAPSS 22 | ) 23 | 24 | func init() { 25 | // PS256 26 | SigningMethodPS256 = &SigningMethodRSAPSS{ 27 | &SigningMethodRSA{ 28 | Name: "PS256", 29 | Hash: crypto.SHA256, 30 | }, 31 | &rsa.PSSOptions{ 32 | SaltLength: rsa.PSSSaltLengthAuto, 33 | Hash: crypto.SHA256, 34 | }, 35 | } 36 | RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { 37 | return SigningMethodPS256 38 | }) 39 | 40 | // PS384 41 | SigningMethodPS384 = &SigningMethodRSAPSS{ 42 | &SigningMethodRSA{ 43 | Name: "PS384", 44 | Hash: crypto.SHA384, 45 | }, 46 | &rsa.PSSOptions{ 47 | SaltLength: rsa.PSSSaltLengthAuto, 48 | Hash: crypto.SHA384, 49 | }, 50 | } 51 | RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { 52 | return SigningMethodPS384 53 | }) 54 | 55 | // PS512 56 | SigningMethodPS512 = &SigningMethodRSAPSS{ 57 | &SigningMethodRSA{ 58 | Name: "PS512", 59 | Hash: crypto.SHA512, 60 | }, 61 | &rsa.PSSOptions{ 62 | SaltLength: rsa.PSSSaltLengthAuto, 63 | Hash: crypto.SHA512, 64 | }, 65 | } 66 | RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { 67 | return SigningMethodPS512 68 | }) 69 | } 70 | 71 | // Implements the Verify method from SigningMethod 72 | // For this verify method, key must be an rsa.PublicKey struct 73 | func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { 74 | var err error 75 | 76 | // Decode the signature 77 | var sig []byte 78 | if sig, err = DecodeSegment(signature); err != nil { 79 | return err 80 | } 81 | 82 | var rsaKey *rsa.PublicKey 83 | switch k := key.(type) { 84 | case *rsa.PublicKey: 85 | rsaKey = k 86 | default: 87 | return ErrInvalidKey 88 | } 89 | 90 | // Create hasher 91 | if !m.Hash.Available() { 92 | return ErrHashUnavailable 93 | } 94 | hasher := m.Hash.New() 95 | hasher.Write([]byte(signingString)) 96 | 97 | return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options) 98 | } 99 | 100 | // Implements the Sign method from SigningMethod 101 | // For this signing method, key must be an rsa.PrivateKey struct 102 | func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { 103 | var rsaKey *rsa.PrivateKey 104 | 105 | switch k := key.(type) { 106 | case *rsa.PrivateKey: 107 | rsaKey = k 108 | default: 109 | return "", ErrInvalidKeyType 110 | } 111 | 112 | // Create the hasher 113 | if !m.Hash.Available() { 114 | return "", ErrHashUnavailable 115 | } 116 | 117 | hasher := m.Hash.New() 118 | hasher.Write([]byte(signingString)) 119 | 120 | // Sign the string and return the encoded bytes 121 | if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { 122 | return EncodeSegment(sigBytes), nil 123 | } else { 124 | return "", err 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/rsa_utils.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/rsa" 5 | "crypto/x509" 6 | "encoding/pem" 7 | "errors" 8 | ) 9 | 10 | var ( 11 | ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") 12 | ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") 13 | ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") 14 | ) 15 | 16 | // Parse PEM encoded PKCS1 or PKCS8 private key 17 | func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { 18 | var err error 19 | 20 | // Parse PEM block 21 | var block *pem.Block 22 | if block, _ = pem.Decode(key); block == nil { 23 | return nil, ErrKeyMustBePEMEncoded 24 | } 25 | 26 | var parsedKey interface{} 27 | if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { 28 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { 29 | return nil, err 30 | } 31 | } 32 | 33 | var pkey *rsa.PrivateKey 34 | var ok bool 35 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { 36 | return nil, ErrNotRSAPrivateKey 37 | } 38 | 39 | return pkey, nil 40 | } 41 | 42 | // Parse PEM encoded PKCS1 or PKCS8 private key protected with password 43 | func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { 44 | var err error 45 | 46 | // Parse PEM block 47 | var block *pem.Block 48 | if block, _ = pem.Decode(key); block == nil { 49 | return nil, ErrKeyMustBePEMEncoded 50 | } 51 | 52 | var parsedKey interface{} 53 | 54 | var blockDecrypted []byte 55 | if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { 56 | return nil, err 57 | } 58 | 59 | if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { 60 | if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { 61 | return nil, err 62 | } 63 | } 64 | 65 | var pkey *rsa.PrivateKey 66 | var ok bool 67 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { 68 | return nil, ErrNotRSAPrivateKey 69 | } 70 | 71 | return pkey, nil 72 | } 73 | 74 | // Parse PEM encoded PKCS1 or PKCS8 public key 75 | func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { 76 | var err error 77 | 78 | // Parse PEM block 79 | var block *pem.Block 80 | if block, _ = pem.Decode(key); block == nil { 81 | return nil, ErrKeyMustBePEMEncoded 82 | } 83 | 84 | // Parse the key 85 | var parsedKey interface{} 86 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 87 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil { 88 | parsedKey = cert.PublicKey 89 | } else { 90 | return nil, err 91 | } 92 | } 93 | 94 | var pkey *rsa.PublicKey 95 | var ok bool 96 | if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { 97 | return nil, ErrNotRSAPublicKey 98 | } 99 | 100 | return pkey, nil 101 | } 102 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/signing_method.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "sync" 5 | ) 6 | 7 | var signingMethods = map[string]func() SigningMethod{} 8 | var signingMethodLock = new(sync.RWMutex) 9 | 10 | // Implement SigningMethod to add new methods for signing or verifying tokens. 11 | type SigningMethod interface { 12 | Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid 13 | Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error 14 | Alg() string // returns the alg identifier for this method (example: 'HS256') 15 | } 16 | 17 | // Register the "alg" name and a factory function for signing method. 18 | // This is typically done during init() in the method's implementation 19 | func RegisterSigningMethod(alg string, f func() SigningMethod) { 20 | signingMethodLock.Lock() 21 | defer signingMethodLock.Unlock() 22 | 23 | signingMethods[alg] = f 24 | } 25 | 26 | // Get a signing method from an "alg" string 27 | func GetSigningMethod(alg string) (method SigningMethod) { 28 | signingMethodLock.RLock() 29 | defer signingMethodLock.RUnlock() 30 | 31 | if methodF, ok := signingMethods[alg]; ok { 32 | method = methodF() 33 | } 34 | return 35 | } 36 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/dgrijalva/jwt-go/token.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "encoding/base64" 5 | "encoding/json" 6 | "strings" 7 | "time" 8 | ) 9 | 10 | // TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). 11 | // You can override it to use another time value. This is useful for testing or if your 12 | // server uses a different time zone than your tokens. 13 | var TimeFunc = time.Now 14 | 15 | // Parse methods use this callback function to supply 16 | // the key for verification. The function receives the parsed, 17 | // but unverified Token. This allows you to use properties in the 18 | // Header of the token (such as `kid`) to identify which key to use. 19 | type Keyfunc func(*Token) (interface{}, error) 20 | 21 | // A JWT Token. Different fields will be used depending on whether you're 22 | // creating or parsing/verifying a token. 23 | type Token struct { 24 | Raw string // The raw token. Populated when you Parse a token 25 | Method SigningMethod // The signing method used or to be used 26 | Header map[string]interface{} // The first segment of the token 27 | Claims Claims // The second segment of the token 28 | Signature string // The third segment of the token. Populated when you Parse a token 29 | Valid bool // Is the token valid? Populated when you Parse/Verify a token 30 | } 31 | 32 | // Create a new Token. Takes a signing method 33 | func New(method SigningMethod) *Token { 34 | return NewWithClaims(method, MapClaims{}) 35 | } 36 | 37 | func NewWithClaims(method SigningMethod, claims Claims) *Token { 38 | return &Token{ 39 | Header: map[string]interface{}{ 40 | "typ": "JWT", 41 | "alg": method.Alg(), 42 | }, 43 | Claims: claims, 44 | Method: method, 45 | } 46 | } 47 | 48 | // Get the complete, signed token 49 | func (t *Token) SignedString(key interface{}) (string, error) { 50 | var sig, sstr string 51 | var err error 52 | if sstr, err = t.SigningString(); err != nil { 53 | return "", err 54 | } 55 | if sig, err = t.Method.Sign(sstr, key); err != nil { 56 | return "", err 57 | } 58 | return strings.Join([]string{sstr, sig}, "."), nil 59 | } 60 | 61 | // Generate the signing string. This is the 62 | // most expensive part of the whole deal. Unless you 63 | // need this for something special, just go straight for 64 | // the SignedString. 65 | func (t *Token) SigningString() (string, error) { 66 | var err error 67 | parts := make([]string, 2) 68 | for i, _ := range parts { 69 | var jsonValue []byte 70 | if i == 0 { 71 | if jsonValue, err = json.Marshal(t.Header); err != nil { 72 | return "", err 73 | } 74 | } else { 75 | if jsonValue, err = json.Marshal(t.Claims); err != nil { 76 | return "", err 77 | } 78 | } 79 | 80 | parts[i] = EncodeSegment(jsonValue) 81 | } 82 | return strings.Join(parts, "."), nil 83 | } 84 | 85 | // Parse, validate, and return a token. 86 | // keyFunc will receive the parsed token and should return the key for validating. 87 | // If everything is kosher, err will be nil 88 | func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { 89 | return new(Parser).Parse(tokenString, keyFunc) 90 | } 91 | 92 | func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { 93 | return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) 94 | } 95 | 96 | // Encode JWT specific base64url encoding with padding stripped 97 | func EncodeSegment(seg []byte) string { 98 | return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") 99 | } 100 | 101 | // Decode JWT specific base64url encoding with padding stripped 102 | func DecodeSegment(seg string) ([]byte, error) { 103 | if l := len(seg) % 4; l > 0 { 104 | seg += strings.Repeat("=", 4-l) 105 | } 106 | 107 | return base64.URLEncoding.DecodeString(seg) 108 | } 109 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | 24 | .idea/ 25 | *.iml 26 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | sudo: false 3 | 4 | matrix: 5 | include: 6 | - go: 1.7.x 7 | - go: 1.8.x 8 | - go: 1.9.x 9 | - go: 1.10.x 10 | - go: 1.11.x 11 | - go: tip 12 | allow_failures: 13 | - go: tip 14 | 15 | script: 16 | - go get -t -v ./... 17 | - diff -u <(echo -n) <(gofmt -d .) 18 | - go vet $(go list ./... | grep -v /vendor/) 19 | - go test -v -race ./... 20 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the official list of Gorilla WebSocket authors for copyright 2 | # purposes. 3 | # 4 | # Please keep the list sorted. 5 | 6 | Gary Burd 7 | Google LLC (https://opensource.google.com/) 8 | Joachim Bauch 9 | 10 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are met: 5 | 6 | Redistributions of source code must retain the above copyright notice, this 7 | list of conditions and the following disclaimer. 8 | 9 | Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 17 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 18 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 19 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 20 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 21 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 22 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/README.md: -------------------------------------------------------------------------------- 1 | # Gorilla WebSocket 2 | 3 | Gorilla WebSocket is a [Go](http://golang.org/) implementation of the 4 | [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. 5 | 6 | [![Build Status](https://travis-ci.org/gorilla/websocket.svg?branch=master)](https://travis-ci.org/gorilla/websocket) 7 | [![GoDoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket) 8 | 9 | ### Documentation 10 | 11 | * [API Reference](http://godoc.org/github.com/gorilla/websocket) 12 | * [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat) 13 | * [Command example](https://github.com/gorilla/websocket/tree/master/examples/command) 14 | * [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo) 15 | * [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch) 16 | 17 | ### Status 18 | 19 | The Gorilla WebSocket package provides a complete and tested implementation of 20 | the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. The 21 | package API is stable. 22 | 23 | ### Installation 24 | 25 | go get github.com/gorilla/websocket 26 | 27 | ### Protocol Compliance 28 | 29 | The Gorilla WebSocket package passes the server tests in the [Autobahn Test 30 | Suite](http://autobahn.ws/testsuite) using the application in the [examples/autobahn 31 | subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn). 32 | 33 | ### Gorilla WebSocket compared with other packages 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 |
github.com/gorillagolang.org/x/net
RFC 6455 Features
Passes Autobahn Test SuiteYesNo
Receive fragmented messageYesNo, see note 1
Send close messageYesNo
Send pings and receive pongsYesNo
Get the type of a received data messageYesYes, see note 2
Other Features
Compression ExtensionsExperimentalNo
Read message using io.ReaderYesNo, see note 3
Write message using io.WriteCloserYesNo, see note 3
53 | 54 | Notes: 55 | 56 | 1. Large messages are fragmented in [Chrome's new WebSocket implementation](http://www.ietf.org/mail-archive/web/hybi/current/msg10503.html). 57 | 2. The application can get the type of a received data message by implementing 58 | a [Codec marshal](http://godoc.org/golang.org/x/net/websocket#Codec.Marshal) 59 | function. 60 | 3. The go.net io.Reader and io.Writer operate across WebSocket frame boundaries. 61 | Read returns when the input buffer is full or a frame boundary is 62 | encountered. Each call to Write sends a single frame message. The Gorilla 63 | io.Reader and io.WriteCloser operate on a single WebSocket message. 64 | 65 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/client_clone.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.8 6 | 7 | package websocket 8 | 9 | import "crypto/tls" 10 | 11 | func cloneTLSConfig(cfg *tls.Config) *tls.Config { 12 | if cfg == nil { 13 | return &tls.Config{} 14 | } 15 | return cfg.Clone() 16 | } 17 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/client_clone_legacy.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !go1.8 6 | 7 | package websocket 8 | 9 | import "crypto/tls" 10 | 11 | // cloneTLSConfig clones all public fields except the fields 12 | // SessionTicketsDisabled and SessionTicketKey. This avoids copying the 13 | // sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a 14 | // config in active use. 15 | func cloneTLSConfig(cfg *tls.Config) *tls.Config { 16 | if cfg == nil { 17 | return &tls.Config{} 18 | } 19 | return &tls.Config{ 20 | Rand: cfg.Rand, 21 | Time: cfg.Time, 22 | Certificates: cfg.Certificates, 23 | NameToCertificate: cfg.NameToCertificate, 24 | GetCertificate: cfg.GetCertificate, 25 | RootCAs: cfg.RootCAs, 26 | NextProtos: cfg.NextProtos, 27 | ServerName: cfg.ServerName, 28 | ClientAuth: cfg.ClientAuth, 29 | ClientCAs: cfg.ClientCAs, 30 | InsecureSkipVerify: cfg.InsecureSkipVerify, 31 | CipherSuites: cfg.CipherSuites, 32 | PreferServerCipherSuites: cfg.PreferServerCipherSuites, 33 | ClientSessionCache: cfg.ClientSessionCache, 34 | MinVersion: cfg.MinVersion, 35 | MaxVersion: cfg.MaxVersion, 36 | CurvePreferences: cfg.CurvePreferences, 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/compression.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "compress/flate" 9 | "errors" 10 | "io" 11 | "strings" 12 | "sync" 13 | ) 14 | 15 | const ( 16 | minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6 17 | maxCompressionLevel = flate.BestCompression 18 | defaultCompressionLevel = 1 19 | ) 20 | 21 | var ( 22 | flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool 23 | flateReaderPool = sync.Pool{New: func() interface{} { 24 | return flate.NewReader(nil) 25 | }} 26 | ) 27 | 28 | func decompressNoContextTakeover(r io.Reader) io.ReadCloser { 29 | const tail = 30 | // Add four bytes as specified in RFC 31 | "\x00\x00\xff\xff" + 32 | // Add final block to squelch unexpected EOF error from flate reader. 33 | "\x01\x00\x00\xff\xff" 34 | 35 | fr, _ := flateReaderPool.Get().(io.ReadCloser) 36 | fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil) 37 | return &flateReadWrapper{fr} 38 | } 39 | 40 | func isValidCompressionLevel(level int) bool { 41 | return minCompressionLevel <= level && level <= maxCompressionLevel 42 | } 43 | 44 | func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser { 45 | p := &flateWriterPools[level-minCompressionLevel] 46 | tw := &truncWriter{w: w} 47 | fw, _ := p.Get().(*flate.Writer) 48 | if fw == nil { 49 | fw, _ = flate.NewWriter(tw, level) 50 | } else { 51 | fw.Reset(tw) 52 | } 53 | return &flateWriteWrapper{fw: fw, tw: tw, p: p} 54 | } 55 | 56 | // truncWriter is an io.Writer that writes all but the last four bytes of the 57 | // stream to another io.Writer. 58 | type truncWriter struct { 59 | w io.WriteCloser 60 | n int 61 | p [4]byte 62 | } 63 | 64 | func (w *truncWriter) Write(p []byte) (int, error) { 65 | n := 0 66 | 67 | // fill buffer first for simplicity. 68 | if w.n < len(w.p) { 69 | n = copy(w.p[w.n:], p) 70 | p = p[n:] 71 | w.n += n 72 | if len(p) == 0 { 73 | return n, nil 74 | } 75 | } 76 | 77 | m := len(p) 78 | if m > len(w.p) { 79 | m = len(w.p) 80 | } 81 | 82 | if nn, err := w.w.Write(w.p[:m]); err != nil { 83 | return n + nn, err 84 | } 85 | 86 | copy(w.p[:], w.p[m:]) 87 | copy(w.p[len(w.p)-m:], p[len(p)-m:]) 88 | nn, err := w.w.Write(p[:len(p)-m]) 89 | return n + nn, err 90 | } 91 | 92 | type flateWriteWrapper struct { 93 | fw *flate.Writer 94 | tw *truncWriter 95 | p *sync.Pool 96 | } 97 | 98 | func (w *flateWriteWrapper) Write(p []byte) (int, error) { 99 | if w.fw == nil { 100 | return 0, errWriteClosed 101 | } 102 | return w.fw.Write(p) 103 | } 104 | 105 | func (w *flateWriteWrapper) Close() error { 106 | if w.fw == nil { 107 | return errWriteClosed 108 | } 109 | err1 := w.fw.Flush() 110 | w.p.Put(w.fw) 111 | w.fw = nil 112 | if w.tw.p != [4]byte{0, 0, 0xff, 0xff} { 113 | return errors.New("websocket: internal error, unexpected bytes at end of flate stream") 114 | } 115 | err2 := w.tw.w.Close() 116 | if err1 != nil { 117 | return err1 118 | } 119 | return err2 120 | } 121 | 122 | type flateReadWrapper struct { 123 | fr io.ReadCloser 124 | } 125 | 126 | func (r *flateReadWrapper) Read(p []byte) (int, error) { 127 | if r.fr == nil { 128 | return 0, io.ErrClosedPipe 129 | } 130 | n, err := r.fr.Read(p) 131 | if err == io.EOF { 132 | // Preemptively place the reader back in the pool. This helps with 133 | // scenarios where the application does not call NextReader() soon after 134 | // this final read. 135 | r.Close() 136 | } 137 | return n, err 138 | } 139 | 140 | func (r *flateReadWrapper) Close() error { 141 | if r.fr == nil { 142 | return io.ErrClosedPipe 143 | } 144 | err := r.fr.Close() 145 | flateReaderPool.Put(r.fr) 146 | r.fr = nil 147 | return err 148 | } 149 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/conn_write.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.8 6 | 7 | package websocket 8 | 9 | import "net" 10 | 11 | func (c *Conn) writeBufs(bufs ...[]byte) error { 12 | b := net.Buffers(bufs) 13 | _, err := b.WriteTo(c.conn) 14 | return err 15 | } 16 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/conn_write_legacy.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !go1.8 6 | 7 | package websocket 8 | 9 | func (c *Conn) writeBufs(bufs ...[]byte) error { 10 | for _, buf := range bufs { 11 | if len(buf) > 0 { 12 | if _, err := c.conn.Write(buf); err != nil { 13 | return err 14 | } 15 | } 16 | } 17 | return nil 18 | } 19 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/json.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "encoding/json" 9 | "io" 10 | ) 11 | 12 | // WriteJSON writes the JSON encoding of v as a message. 13 | // 14 | // Deprecated: Use c.WriteJSON instead. 15 | func WriteJSON(c *Conn, v interface{}) error { 16 | return c.WriteJSON(v) 17 | } 18 | 19 | // WriteJSON writes the JSON encoding of v as a message. 20 | // 21 | // See the documentation for encoding/json Marshal for details about the 22 | // conversion of Go values to JSON. 23 | func (c *Conn) WriteJSON(v interface{}) error { 24 | w, err := c.NextWriter(TextMessage) 25 | if err != nil { 26 | return err 27 | } 28 | err1 := json.NewEncoder(w).Encode(v) 29 | err2 := w.Close() 30 | if err1 != nil { 31 | return err1 32 | } 33 | return err2 34 | } 35 | 36 | // ReadJSON reads the next JSON-encoded message from the connection and stores 37 | // it in the value pointed to by v. 38 | // 39 | // Deprecated: Use c.ReadJSON instead. 40 | func ReadJSON(c *Conn, v interface{}) error { 41 | return c.ReadJSON(v) 42 | } 43 | 44 | // ReadJSON reads the next JSON-encoded message from the connection and stores 45 | // it in the value pointed to by v. 46 | // 47 | // See the documentation for the encoding/json Unmarshal function for details 48 | // about the conversion of JSON to a Go value. 49 | func (c *Conn) ReadJSON(v interface{}) error { 50 | _, r, err := c.NextReader() 51 | if err != nil { 52 | return err 53 | } 54 | err = json.NewDecoder(r).Decode(v) 55 | if err == io.EOF { 56 | // One value is expected in the message. 57 | err = io.ErrUnexpectedEOF 58 | } 59 | return err 60 | } 61 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/mask.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of 2 | // this source code is governed by a BSD-style license that can be found in the 3 | // LICENSE file. 4 | 5 | // +build !appengine 6 | 7 | package websocket 8 | 9 | import "unsafe" 10 | 11 | const wordSize = int(unsafe.Sizeof(uintptr(0))) 12 | 13 | func maskBytes(key [4]byte, pos int, b []byte) int { 14 | // Mask one byte at a time for small buffers. 15 | if len(b) < 2*wordSize { 16 | for i := range b { 17 | b[i] ^= key[pos&3] 18 | pos++ 19 | } 20 | return pos & 3 21 | } 22 | 23 | // Mask one byte at a time to word boundary. 24 | if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 { 25 | n = wordSize - n 26 | for i := range b[:n] { 27 | b[i] ^= key[pos&3] 28 | pos++ 29 | } 30 | b = b[n:] 31 | } 32 | 33 | // Create aligned word size key. 34 | var k [wordSize]byte 35 | for i := range k { 36 | k[i] = key[(pos+i)&3] 37 | } 38 | kw := *(*uintptr)(unsafe.Pointer(&k)) 39 | 40 | // Mask one word at a time. 41 | n := (len(b) / wordSize) * wordSize 42 | for i := 0; i < n; i += wordSize { 43 | *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw 44 | } 45 | 46 | // Mask one byte at a time for remaining bytes. 47 | b = b[n:] 48 | for i := range b { 49 | b[i] ^= key[pos&3] 50 | pos++ 51 | } 52 | 53 | return pos & 3 54 | } 55 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/mask_safe.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of 2 | // this source code is governed by a BSD-style license that can be found in the 3 | // LICENSE file. 4 | 5 | // +build appengine 6 | 7 | package websocket 8 | 9 | func maskBytes(key [4]byte, pos int, b []byte) int { 10 | for i := range b { 11 | b[i] ^= key[pos&3] 12 | pos++ 13 | } 14 | return pos & 3 15 | } 16 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/prepared.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "bytes" 9 | "net" 10 | "sync" 11 | "time" 12 | ) 13 | 14 | // PreparedMessage caches on the wire representations of a message payload. 15 | // Use PreparedMessage to efficiently send a message payload to multiple 16 | // connections. PreparedMessage is especially useful when compression is used 17 | // because the CPU and memory expensive compression operation can be executed 18 | // once for a given set of compression options. 19 | type PreparedMessage struct { 20 | messageType int 21 | data []byte 22 | mu sync.Mutex 23 | frames map[prepareKey]*preparedFrame 24 | } 25 | 26 | // prepareKey defines a unique set of options to cache prepared frames in PreparedMessage. 27 | type prepareKey struct { 28 | isServer bool 29 | compress bool 30 | compressionLevel int 31 | } 32 | 33 | // preparedFrame contains data in wire representation. 34 | type preparedFrame struct { 35 | once sync.Once 36 | data []byte 37 | } 38 | 39 | // NewPreparedMessage returns an initialized PreparedMessage. You can then send 40 | // it to connection using WritePreparedMessage method. Valid wire 41 | // representation will be calculated lazily only once for a set of current 42 | // connection options. 43 | func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) { 44 | pm := &PreparedMessage{ 45 | messageType: messageType, 46 | frames: make(map[prepareKey]*preparedFrame), 47 | data: data, 48 | } 49 | 50 | // Prepare a plain server frame. 51 | _, frameData, err := pm.frame(prepareKey{isServer: true, compress: false}) 52 | if err != nil { 53 | return nil, err 54 | } 55 | 56 | // To protect against caller modifying the data argument, remember the data 57 | // copied to the plain server frame. 58 | pm.data = frameData[len(frameData)-len(data):] 59 | return pm, nil 60 | } 61 | 62 | func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) { 63 | pm.mu.Lock() 64 | frame, ok := pm.frames[key] 65 | if !ok { 66 | frame = &preparedFrame{} 67 | pm.frames[key] = frame 68 | } 69 | pm.mu.Unlock() 70 | 71 | var err error 72 | frame.once.Do(func() { 73 | // Prepare a frame using a 'fake' connection. 74 | // TODO: Refactor code in conn.go to allow more direct construction of 75 | // the frame. 76 | mu := make(chan bool, 1) 77 | mu <- true 78 | var nc prepareConn 79 | c := &Conn{ 80 | conn: &nc, 81 | mu: mu, 82 | isServer: key.isServer, 83 | compressionLevel: key.compressionLevel, 84 | enableWriteCompression: true, 85 | writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize), 86 | } 87 | if key.compress { 88 | c.newCompressionWriter = compressNoContextTakeover 89 | } 90 | err = c.WriteMessage(pm.messageType, pm.data) 91 | frame.data = nc.buf.Bytes() 92 | }) 93 | return pm.messageType, frame.data, err 94 | } 95 | 96 | type prepareConn struct { 97 | buf bytes.Buffer 98 | net.Conn 99 | } 100 | 101 | func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) } 102 | func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil } 103 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/proxy.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "bufio" 9 | "encoding/base64" 10 | "errors" 11 | "net" 12 | "net/http" 13 | "net/url" 14 | "strings" 15 | ) 16 | 17 | type netDialerFunc func(network, addr string) (net.Conn, error) 18 | 19 | func (fn netDialerFunc) Dial(network, addr string) (net.Conn, error) { 20 | return fn(network, addr) 21 | } 22 | 23 | func init() { 24 | proxy_RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy_Dialer) (proxy_Dialer, error) { 25 | return &httpProxyDialer{proxyURL: proxyURL, fowardDial: forwardDialer.Dial}, nil 26 | }) 27 | } 28 | 29 | type httpProxyDialer struct { 30 | proxyURL *url.URL 31 | fowardDial func(network, addr string) (net.Conn, error) 32 | } 33 | 34 | func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) { 35 | hostPort, _ := hostPortNoPort(hpd.proxyURL) 36 | conn, err := hpd.fowardDial(network, hostPort) 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | connectHeader := make(http.Header) 42 | if user := hpd.proxyURL.User; user != nil { 43 | proxyUser := user.Username() 44 | if proxyPassword, passwordSet := user.Password(); passwordSet { 45 | credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword)) 46 | connectHeader.Set("Proxy-Authorization", "Basic "+credential) 47 | } 48 | } 49 | 50 | connectReq := &http.Request{ 51 | Method: "CONNECT", 52 | URL: &url.URL{Opaque: addr}, 53 | Host: addr, 54 | Header: connectHeader, 55 | } 56 | 57 | if err := connectReq.Write(conn); err != nil { 58 | conn.Close() 59 | return nil, err 60 | } 61 | 62 | // Read response. It's OK to use and discard buffered reader here becaue 63 | // the remote server does not speak until spoken to. 64 | br := bufio.NewReader(conn) 65 | resp, err := http.ReadResponse(br, connectReq) 66 | if err != nil { 67 | conn.Close() 68 | return nil, err 69 | } 70 | 71 | if resp.StatusCode != 200 { 72 | conn.Close() 73 | f := strings.SplitN(resp.Status, " ", 2) 74 | return nil, errors.New(f[1]) 75 | } 76 | return conn, nil 77 | } 78 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/trace.go: -------------------------------------------------------------------------------- 1 | // +build go1.8 2 | 3 | package websocket 4 | 5 | import ( 6 | "crypto/tls" 7 | "net/http/httptrace" 8 | ) 9 | 10 | func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error { 11 | if trace.TLSHandshakeStart != nil { 12 | trace.TLSHandshakeStart() 13 | } 14 | err := doHandshake(tlsConn, cfg) 15 | if trace.TLSHandshakeDone != nil { 16 | trace.TLSHandshakeDone(tlsConn.ConnectionState(), err) 17 | } 18 | return err 19 | } 20 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/gorilla/websocket/trace_17.go: -------------------------------------------------------------------------------- 1 | // +build !go1.8 2 | 3 | package websocket 4 | 5 | import ( 6 | "crypto/tls" 7 | "net/http/httptrace" 8 | ) 9 | 10 | func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error { 11 | return doHandshake(tlsConn, cfg) 12 | } 13 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/spf13/cast/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | 25 | *.bench 26 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/spf13/cast/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | env: 3 | - GO111MODULE=on 4 | sudo: required 5 | go: 6 | - "1.11.x" 7 | - tip 8 | os: 9 | - linux 10 | matrix: 11 | allow_failures: 12 | - go: tip 13 | fast_finish: true 14 | script: 15 | - make check 16 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/spf13/cast/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Steve Francia 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/spf13/cast/Makefile: -------------------------------------------------------------------------------- 1 | # A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html 2 | 3 | .PHONY: check fmt lint test test-race vet test-cover-html help 4 | .DEFAULT_GOAL := help 5 | 6 | check: test-race fmt vet lint ## Run tests and linters 7 | 8 | test: ## Run tests 9 | go test ./... 10 | 11 | test-race: ## Run tests with race detector 12 | go test -race ./... 13 | 14 | fmt: ## Run gofmt linter 15 | @for d in `go list` ; do \ 16 | if [ "`gofmt -l -s $$GOPATH/src/$$d | tee /dev/stderr`" ]; then \ 17 | echo "^ improperly formatted go files" && echo && exit 1; \ 18 | fi \ 19 | done 20 | 21 | lint: ## Run golint linter 22 | @for d in `go list` ; do \ 23 | if [ "`golint $$d | tee /dev/stderr`" ]; then \ 24 | echo "^ golint errors!" && echo && exit 1; \ 25 | fi \ 26 | done 27 | 28 | vet: ## Run go vet linter 29 | @if [ "`go vet | tee /dev/stderr`" ]; then \ 30 | echo "^ go vet errors!" && echo && exit 1; \ 31 | fi 32 | 33 | test-cover-html: ## Generate test coverage report 34 | go test -coverprofile=coverage.out -covermode=count 35 | go tool cover -func=coverage.out 36 | 37 | help: 38 | @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' 39 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/spf13/cast/README.md: -------------------------------------------------------------------------------- 1 | cast 2 | ==== 3 | [![GoDoc](https://godoc.org/github.com/spf13/cast?status.svg)](https://godoc.org/github.com/spf13/cast) 4 | [![Build Status](https://api.travis-ci.org/spf13/cast.svg?branch=master)](https://travis-ci.org/spf13/cast) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cast)](https://goreportcard.com/report/github.com/spf13/cast) 6 | 7 | Easy and safe casting from one type to another in Go 8 | 9 | Don’t Panic! ... Cast 10 | 11 | ## What is Cast? 12 | 13 | Cast is a library to convert between different go types in a consistent and easy way. 14 | 15 | Cast provides simple functions to easily convert a number to a string, an 16 | interface into a bool, etc. Cast does this intelligently when an obvious 17 | conversion is possible. It doesn’t make any attempts to guess what you meant, 18 | for example you can only convert a string to an int when it is a string 19 | representation of an int such as “8”. Cast was developed for use in 20 | [Hugo](http://hugo.spf13.com), a website engine which uses YAML, TOML or JSON 21 | for meta data. 22 | 23 | ## Why use Cast? 24 | 25 | When working with dynamic data in Go you often need to cast or convert the data 26 | from one type into another. Cast goes beyond just using type assertion (though 27 | it uses that when possible) to provide a very straightforward and convenient 28 | library. 29 | 30 | If you are working with interfaces to handle things like dynamic content 31 | you’ll need an easy way to convert an interface into a given type. This 32 | is the library for you. 33 | 34 | If you are taking in data from YAML, TOML or JSON or other formats which lack 35 | full types, then Cast is the library for you. 36 | 37 | ## Usage 38 | 39 | Cast provides a handful of To_____ methods. These methods will always return 40 | the desired type. **If input is provided that will not convert to that type, the 41 | 0 or nil value for that type will be returned**. 42 | 43 | Cast also provides identical methods To_____E. These return the same result as 44 | the To_____ methods, plus an additional error which tells you if it successfully 45 | converted. Using these methods you can tell the difference between when the 46 | input matched the zero value or when the conversion failed and the zero value 47 | was returned. 48 | 49 | The following examples are merely a sample of what is available. Please review 50 | the code for a complete set. 51 | 52 | ### Example ‘ToString’: 53 | 54 | cast.ToString("mayonegg") // "mayonegg" 55 | cast.ToString(8) // "8" 56 | cast.ToString(8.31) // "8.31" 57 | cast.ToString([]byte("one time")) // "one time" 58 | cast.ToString(nil) // "" 59 | 60 | var foo interface{} = "one more time" 61 | cast.ToString(foo) // "one more time" 62 | 63 | 64 | ### Example ‘ToInt’: 65 | 66 | cast.ToInt(8) // 8 67 | cast.ToInt(8.31) // 8 68 | cast.ToInt("8") // 8 69 | cast.ToInt(true) // 1 70 | cast.ToInt(false) // 0 71 | 72 | var eight interface{} = 8 73 | cast.ToInt(eight) // 8 74 | cast.ToInt(nil) // 0 75 | 76 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/spf13/cast/cast.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2014 Steve Francia . 2 | // 3 | // Use of this source code is governed by an MIT-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // Package cast provides easy and safe casting in Go. 7 | package cast 8 | 9 | import "time" 10 | 11 | // ToBool casts an interface to a bool type. 12 | func ToBool(i interface{}) bool { 13 | v, _ := ToBoolE(i) 14 | return v 15 | } 16 | 17 | // ToTime casts an interface to a time.Time type. 18 | func ToTime(i interface{}) time.Time { 19 | v, _ := ToTimeE(i) 20 | return v 21 | } 22 | 23 | // ToDuration casts an interface to a time.Duration type. 24 | func ToDuration(i interface{}) time.Duration { 25 | v, _ := ToDurationE(i) 26 | return v 27 | } 28 | 29 | // ToFloat64 casts an interface to a float64 type. 30 | func ToFloat64(i interface{}) float64 { 31 | v, _ := ToFloat64E(i) 32 | return v 33 | } 34 | 35 | // ToFloat32 casts an interface to a float32 type. 36 | func ToFloat32(i interface{}) float32 { 37 | v, _ := ToFloat32E(i) 38 | return v 39 | } 40 | 41 | // ToInt64 casts an interface to an int64 type. 42 | func ToInt64(i interface{}) int64 { 43 | v, _ := ToInt64E(i) 44 | return v 45 | } 46 | 47 | // ToInt32 casts an interface to an int32 type. 48 | func ToInt32(i interface{}) int32 { 49 | v, _ := ToInt32E(i) 50 | return v 51 | } 52 | 53 | // ToInt16 casts an interface to an int16 type. 54 | func ToInt16(i interface{}) int16 { 55 | v, _ := ToInt16E(i) 56 | return v 57 | } 58 | 59 | // ToInt8 casts an interface to an int8 type. 60 | func ToInt8(i interface{}) int8 { 61 | v, _ := ToInt8E(i) 62 | return v 63 | } 64 | 65 | // ToInt casts an interface to an int type. 66 | func ToInt(i interface{}) int { 67 | v, _ := ToIntE(i) 68 | return v 69 | } 70 | 71 | // ToUint casts an interface to a uint type. 72 | func ToUint(i interface{}) uint { 73 | v, _ := ToUintE(i) 74 | return v 75 | } 76 | 77 | // ToUint64 casts an interface to a uint64 type. 78 | func ToUint64(i interface{}) uint64 { 79 | v, _ := ToUint64E(i) 80 | return v 81 | } 82 | 83 | // ToUint32 casts an interface to a uint32 type. 84 | func ToUint32(i interface{}) uint32 { 85 | v, _ := ToUint32E(i) 86 | return v 87 | } 88 | 89 | // ToUint16 casts an interface to a uint16 type. 90 | func ToUint16(i interface{}) uint16 { 91 | v, _ := ToUint16E(i) 92 | return v 93 | } 94 | 95 | // ToUint8 casts an interface to a uint8 type. 96 | func ToUint8(i interface{}) uint8 { 97 | v, _ := ToUint8E(i) 98 | return v 99 | } 100 | 101 | // ToString casts an interface to a string type. 102 | func ToString(i interface{}) string { 103 | v, _ := ToStringE(i) 104 | return v 105 | } 106 | 107 | // ToStringMapString casts an interface to a map[string]string type. 108 | func ToStringMapString(i interface{}) map[string]string { 109 | v, _ := ToStringMapStringE(i) 110 | return v 111 | } 112 | 113 | // ToStringMapStringSlice casts an interface to a map[string][]string type. 114 | func ToStringMapStringSlice(i interface{}) map[string][]string { 115 | v, _ := ToStringMapStringSliceE(i) 116 | return v 117 | } 118 | 119 | // ToStringMapBool casts an interface to a map[string]bool type. 120 | func ToStringMapBool(i interface{}) map[string]bool { 121 | v, _ := ToStringMapBoolE(i) 122 | return v 123 | } 124 | 125 | // ToStringMapInt casts an interface to a map[string]int type. 126 | func ToStringMapInt(i interface{}) map[string]int { 127 | v, _ := ToStringMapIntE(i) 128 | return v 129 | } 130 | 131 | // ToStringMapInt64 casts an interface to a map[string]int64 type. 132 | func ToStringMapInt64(i interface{}) map[string]int64 { 133 | v, _ := ToStringMapInt64E(i) 134 | return v 135 | } 136 | 137 | // ToStringMap casts an interface to a map[string]interface{} type. 138 | func ToStringMap(i interface{}) map[string]interface{} { 139 | v, _ := ToStringMapE(i) 140 | return v 141 | } 142 | 143 | // ToSlice casts an interface to a []interface{} type. 144 | func ToSlice(i interface{}) []interface{} { 145 | v, _ := ToSliceE(i) 146 | return v 147 | } 148 | 149 | // ToBoolSlice casts an interface to a []bool type. 150 | func ToBoolSlice(i interface{}) []bool { 151 | v, _ := ToBoolSliceE(i) 152 | return v 153 | } 154 | 155 | // ToStringSlice casts an interface to a []string type. 156 | func ToStringSlice(i interface{}) []string { 157 | v, _ := ToStringSliceE(i) 158 | return v 159 | } 160 | 161 | // ToIntSlice casts an interface to a []int type. 162 | func ToIntSlice(i interface{}) []int { 163 | v, _ := ToIntSliceE(i) 164 | return v 165 | } 166 | 167 | // ToDurationSlice casts an interface to a []time.Duration type. 168 | func ToDurationSlice(i interface{}) []time.Duration { 169 | v, _ := ToDurationSliceE(i) 170 | return v 171 | } 172 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/spf13/cast/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/spf13/cast 2 | 3 | require ( 4 | github.com/davecgh/go-spew v1.1.1 // indirect 5 | github.com/pmezard/go-difflib v1.0.0 // indirect 6 | github.com/stretchr/testify v1.2.2 7 | ) 8 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/github.com/spf13/cast/go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= 6 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 7 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/golang.org/x/net/AUTHORS: -------------------------------------------------------------------------------- 1 | # This source code refers to The Go Authors for copyright purposes. 2 | # The master list of authors is in the main Go distribution, 3 | # visible at http://tip.golang.org/AUTHORS. 4 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/golang.org/x/net/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This source code was written by the Go contributors. 2 | # The master list of contributors is in the main Go distribution, 3 | # visible at http://tip.golang.org/CONTRIBUTORS. 4 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/golang.org/x/net/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/golang.org/x/net/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/golang.org/x/net/websocket/client.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "bufio" 9 | "io" 10 | "net" 11 | "net/http" 12 | "net/url" 13 | ) 14 | 15 | // DialError is an error that occurs while dialling a websocket server. 16 | type DialError struct { 17 | *Config 18 | Err error 19 | } 20 | 21 | func (e *DialError) Error() string { 22 | return "websocket.Dial " + e.Config.Location.String() + ": " + e.Err.Error() 23 | } 24 | 25 | // NewConfig creates a new WebSocket config for client connection. 26 | func NewConfig(server, origin string) (config *Config, err error) { 27 | config = new(Config) 28 | config.Version = ProtocolVersionHybi13 29 | config.Location, err = url.ParseRequestURI(server) 30 | if err != nil { 31 | return 32 | } 33 | config.Origin, err = url.ParseRequestURI(origin) 34 | if err != nil { 35 | return 36 | } 37 | config.Header = http.Header(make(map[string][]string)) 38 | return 39 | } 40 | 41 | // NewClient creates a new WebSocket client connection over rwc. 42 | func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) { 43 | br := bufio.NewReader(rwc) 44 | bw := bufio.NewWriter(rwc) 45 | err = hybiClientHandshake(config, br, bw) 46 | if err != nil { 47 | return 48 | } 49 | buf := bufio.NewReadWriter(br, bw) 50 | ws = newHybiClientConn(config, buf, rwc) 51 | return 52 | } 53 | 54 | // Dial opens a new client connection to a WebSocket. 55 | func Dial(url_, protocol, origin string) (ws *Conn, err error) { 56 | config, err := NewConfig(url_, origin) 57 | if err != nil { 58 | return nil, err 59 | } 60 | if protocol != "" { 61 | config.Protocol = []string{protocol} 62 | } 63 | return DialConfig(config) 64 | } 65 | 66 | var portMap = map[string]string{ 67 | "ws": "80", 68 | "wss": "443", 69 | } 70 | 71 | func parseAuthority(location *url.URL) string { 72 | if _, ok := portMap[location.Scheme]; ok { 73 | if _, _, err := net.SplitHostPort(location.Host); err != nil { 74 | return net.JoinHostPort(location.Host, portMap[location.Scheme]) 75 | } 76 | } 77 | return location.Host 78 | } 79 | 80 | // DialConfig opens a new client connection to a WebSocket with a config. 81 | func DialConfig(config *Config) (ws *Conn, err error) { 82 | var client net.Conn 83 | if config.Location == nil { 84 | return nil, &DialError{config, ErrBadWebSocketLocation} 85 | } 86 | if config.Origin == nil { 87 | return nil, &DialError{config, ErrBadWebSocketOrigin} 88 | } 89 | dialer := config.Dialer 90 | if dialer == nil { 91 | dialer = &net.Dialer{} 92 | } 93 | client, err = dialWithDialer(dialer, config) 94 | if err != nil { 95 | goto Error 96 | } 97 | ws, err = NewClient(config, client) 98 | if err != nil { 99 | client.Close() 100 | goto Error 101 | } 102 | return 103 | 104 | Error: 105 | return nil, &DialError{config, err} 106 | } 107 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/golang.org/x/net/websocket/dial.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "crypto/tls" 9 | "net" 10 | ) 11 | 12 | func dialWithDialer(dialer *net.Dialer, config *Config) (conn net.Conn, err error) { 13 | switch config.Location.Scheme { 14 | case "ws": 15 | conn, err = dialer.Dial("tcp", parseAuthority(config.Location)) 16 | 17 | case "wss": 18 | conn, err = tls.DialWithDialer(dialer, "tcp", parseAuthority(config.Location), config.TlsConfig) 19 | 20 | default: 21 | err = ErrBadScheme 22 | } 23 | return 24 | } 25 | -------------------------------------------------------------------------------- /Futures-Go-demo/_vendor-20190121094707/golang.org/x/net/websocket/server.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "bufio" 9 | "fmt" 10 | "io" 11 | "net/http" 12 | ) 13 | 14 | func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request, config *Config, handshake func(*Config, *http.Request) error) (conn *Conn, err error) { 15 | var hs serverHandshaker = &hybiServerHandshaker{Config: config} 16 | code, err := hs.ReadHandshake(buf.Reader, req) 17 | if err == ErrBadWebSocketVersion { 18 | fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) 19 | fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion) 20 | buf.WriteString("\r\n") 21 | buf.WriteString(err.Error()) 22 | buf.Flush() 23 | return 24 | } 25 | if err != nil { 26 | fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) 27 | buf.WriteString("\r\n") 28 | buf.WriteString(err.Error()) 29 | buf.Flush() 30 | return 31 | } 32 | if handshake != nil { 33 | err = handshake(config, req) 34 | if err != nil { 35 | code = http.StatusForbidden 36 | fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) 37 | buf.WriteString("\r\n") 38 | buf.Flush() 39 | return 40 | } 41 | } 42 | err = hs.AcceptHandshake(buf.Writer) 43 | if err != nil { 44 | code = http.StatusBadRequest 45 | fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) 46 | buf.WriteString("\r\n") 47 | buf.Flush() 48 | return 49 | } 50 | conn = hs.NewServerConn(buf, rwc, req) 51 | return 52 | } 53 | 54 | // Server represents a server of a WebSocket. 55 | type Server struct { 56 | // Config is a WebSocket configuration for new WebSocket connection. 57 | Config 58 | 59 | // Handshake is an optional function in WebSocket handshake. 60 | // For example, you can check, or don't check Origin header. 61 | // Another example, you can select config.Protocol. 62 | Handshake func(*Config, *http.Request) error 63 | 64 | // Handler handles a WebSocket connection. 65 | Handler 66 | } 67 | 68 | // ServeHTTP implements the http.Handler interface for a WebSocket 69 | func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) { 70 | s.serveWebSocket(w, req) 71 | } 72 | 73 | func (s Server) serveWebSocket(w http.ResponseWriter, req *http.Request) { 74 | rwc, buf, err := w.(http.Hijacker).Hijack() 75 | if err != nil { 76 | panic("Hijack failed: " + err.Error()) 77 | } 78 | // The server should abort the WebSocket connection if it finds 79 | // the client did not send a handshake that matches with protocol 80 | // specification. 81 | defer rwc.Close() 82 | conn, err := newServerConn(rwc, buf, req, &s.Config, s.Handshake) 83 | if err != nil { 84 | return 85 | } 86 | if conn == nil { 87 | panic("unexpected nil conn") 88 | } 89 | s.Handler(conn) 90 | } 91 | 92 | // Handler is a simple interface to a WebSocket browser client. 93 | // It checks if Origin header is valid URL by default. 94 | // You might want to verify websocket.Conn.Config().Origin in the func. 95 | // If you use Server instead of Handler, you could call websocket.Origin and 96 | // check the origin in your Handshake func. So, if you want to accept 97 | // non-browser clients, which do not send an Origin header, set a 98 | // Server.Handshake that does not check the origin. 99 | type Handler func(*Conn) 100 | 101 | func checkOrigin(config *Config, req *http.Request) (err error) { 102 | config.Origin, err = Origin(config, req) 103 | if err == nil && config.Origin == nil { 104 | return fmt.Errorf("null origin") 105 | } 106 | return err 107 | } 108 | 109 | // ServeHTTP implements the http.Handler interface for a WebSocket 110 | func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { 111 | s := Server{Handler: h, Handshake: checkOrigin} 112 | s.serveWebSocket(w, req) 113 | } 114 | -------------------------------------------------------------------------------- /Futures-Go-demo/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | // API KEY 4 | const ( 5 | // todo: replace with your own AccessKey and Secret Key 6 | ACCESS_KEY string = "*" // huobi申请的apiKey 必填 7 | SECRET_KEY string = "*" // huobi申请的secretKey 必填 8 | 9 | 10 | // API请求地址, 不要带最后的/ 11 | MARKET_URL string = "https://api.hbdm.com" 12 | TRADE_URL string = "https://api.hbdm.com" 13 | WS_URL string = "wss://www.hbdm.com/ws" 14 | WS_ORDER_URL string = "ws://api.hbdm.com/notification" 15 | Local_IP string = "*.*.*.*" //本地IP地址 Your Local IP 选填 16 | 17 | //replace with real URLs and HostName 18 | HOST_NAME string = "api.hbdm.com" 19 | 20 | ENABLE_PRIVATE_SIGNATURE bool = false 21 | 22 | // generated the key by: openssl ecparam -name prime256v1 -genkey -noout -out privatekey.pem 23 | // only required when Private Signature is enabled 24 | // replace with your own PrivateKey from privatekey.pem 25 | PRIVATE_KEY_PRIME_256 string = `` 26 | ) 27 | -------------------------------------------------------------------------------- /Futures-Go-demo/glide.yaml: -------------------------------------------------------------------------------- 1 | package: mmmmm 2 | 3 | import: 4 | - package: github.com/dgrijalva/jwt-go 5 | version: ~3.2.0 6 | testImport: 7 | - package: github.com/stretchr/testify 8 | version: ~1.2.2 9 | subpackages: 10 | - assert 11 | -------------------------------------------------------------------------------- /Futures-Go-demo/main/ipmain: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huobiapi/Futures-Go-demo/ece4ffbdce90bdbccac9a38e9a97053a6c1bcd56/Futures-Go-demo/main/ipmain -------------------------------------------------------------------------------- /Futures-Go-demo/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "Futures-Go-demo/services" 5 | "Futures-Go-demo/websocket" 6 | "fmt" 7 | "time" 8 | ) 9 | 10 | func main() { 11 | 12 | //------------------------------------------------------------------------------------------ 13 | // 公共API 14 | // 获取合约信息 15 | contractInfo := services.FutureContractInfo("BTC", "", "") 16 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取合约信息: ", contractInfo) 17 | time.Sleep(time.Second / 10) 18 | 19 | // 获取合约指数信息 20 | contract_index := services.FutureContractIndex("BTC") 21 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取合约指数信息: ", contract_index) 22 | time.Sleep(time.Second / 10) 23 | 24 | // 获取合约最高限价和最低限价 25 | contract_price_limit := services.FuturePriceLimit("BTC", "", "") 26 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取合约最高限价和最低限价: ", contract_price_limit) 27 | time.Sleep(time.Second / 10) 28 | 29 | //获取当前可用合约总持仓量 30 | contract_open_interest := services.FutureOpenInterest("BTC", "", "") 31 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取当前可用合约总持仓量: ", contract_open_interest) 32 | time.Sleep(time.Second / 10) 33 | //------------------------------------------------------------------------------------------ 34 | //市场行情API 35 | ////获取交易深度信息 36 | marketDepthReturn := services.FutureMarketDepth("BTC_CW", "step0") 37 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取交易深度信息:", marketDepthReturn) 38 | time.Sleep(time.Second / 10) 39 | 40 | // 获取K线数据 41 | kline := services.FutureMarketHistoryKline("BTC_CW", "1min", 10) 42 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), "获取K线数据:", kline) 43 | time.Sleep(time.Second / 10) 44 | 45 | // 获取聚合行情 46 | tickerReturn := services.FutureMarketDetailMerged("BTC_CW") 47 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取聚合行情:", tickerReturn) 48 | time.Sleep(time.Second / 10) 49 | 50 | //获取市场最近成交记录 51 | tradeDetailReturn := services.FutureMarketDetailTrade("BTC_CW") 52 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取市场最近成交记录:", tradeDetailReturn) 53 | time.Sleep(time.Second / 10) 54 | 55 | //批量获取最近的交易记录 56 | tradeReturn := services.FutureMarketHistoryTrade("BTC_CW", 10) 57 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 批量获取最近的交易记录:", tradeReturn) 58 | time.Sleep(time.Second / 10) 59 | 60 | //获取Market Detail 24小时成交量数据 61 | marketDetailReturn := services.FutureMarketDetail("BTC_CW") 62 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取Market Detail 24小时成交量数据:", marketDetailReturn) 63 | time.Sleep(time.Second / 10) 64 | 65 | //------------------------------------------------------------------------------------------ 66 | // 用户相关API 67 | 68 | //获取用户账户信息 69 | accountInfo := services.FutureContractAccountInfo("BTC") 70 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取用户账户信息: ", accountInfo) 71 | time.Sleep(time.Second / 10) 72 | 73 | //获取用户持仓信息 74 | contract_position_info := services.FutureContractPositionInfo("BTC") 75 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取用户持仓信息: ", contract_position_info) 76 | time.Sleep(time.Second / 10) 77 | 78 | //合约下单 79 | contract_order := services.FutureContractOrder("BTC", "this_week", "BTC181214", "", "6188", "12", 80 | "buy", "open", "10", "limit") 81 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 合约下单: ", contract_order) 82 | time.Sleep(time.Second / 10) 83 | 84 | //合约批量下单 85 | ordersData := make([]*services.Order, 0) 86 | order1 := &services.Order{ 87 | 88 | Symbol: "BTC", 89 | ContractType: "quarter", 90 | ContractCode: "BTC181228", 91 | ClientOrderId: "10", 92 | Price: "6188", 93 | Volume: "1", 94 | Direction: "buy", 95 | Offset: "open", 96 | LeverRate: "10", 97 | OrderPriceType: "limit", 98 | } 99 | 100 | ordersData = append(ordersData, order1) 101 | order2 := &services.Order{ 102 | 103 | Symbol: "BTC", 104 | ContractType: "quarter", 105 | ContractCode: "BTC181228", 106 | ClientOrderId: "11", 107 | Price: "6189", 108 | Volume: "2", 109 | Direction: "buy", 110 | Offset: "open", 111 | LeverRate: "10", 112 | OrderPriceType: "limit", 113 | } 114 | 115 | ordersData = append(ordersData, order2) 116 | //fmt.Println("ordersData:",ordersData) 117 | 118 | contract_batchorder := services.FutureContractBatchorder(ordersData) 119 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 合约批量下单: ", contract_batchorder) 120 | time.Sleep(time.Second / 10) 121 | 122 | //合约取消订单 123 | contract_cancel := services.FutureContractCancel("123456", "BTC", "123456") 124 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 合约取消订单: ", contract_cancel) 125 | time.Sleep(time.Second / 10) 126 | 127 | //合约全部撤单 128 | contract_cancelall := services.FutureContractCancelall("BTC") 129 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 合约全部撤单: ", contract_cancelall) 130 | time.Sleep(time.Second / 10) 131 | 132 | //获取合约订单信息 133 | contract_order_info := services.FutureContractOrderInfo("4.1", "", "BTC", "1.1") 134 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取合约订单信息: ", contract_order_info) 135 | time.Sleep(time.Second / 10) 136 | 137 | //获取订单明细信息 138 | contract_order_detail := services.FutureContractOrderDetail("BTC", "123556789", "10", "20", "1549345271124", "2") 139 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取订单明细信息: ", contract_order_detail) 140 | time.Sleep(time.Second / 10) 141 | 142 | //获取合约当前未成交委托 143 | contract_openorders := services.FutureContractOpenorders("BTC", "1", "100") 144 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取合约当前未成交委托: ", contract_openorders) 145 | time.Sleep(time.Second / 10) 146 | 147 | //获取合约历史委托 148 | contract_hisorders := services.FutureContractHisorders("BTC", "0", "1", "0", "90", "1", "20") 149 | fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000"), " 获取合约历史委托: ", contract_hisorders) 150 | time.Sleep(time.Second / 10) 151 | 152 | // WebSocket 行情,交易 API 153 | fmt.Println() 154 | fmt.Println("********************websocket Run******************************") 155 | 156 | // WebSocket 行情,交易 API 157 | //websocket.WSRun() //无需本地IP地址,直接运行 158 | //websocket.WSRunWithIP(config.Local_IP) //配置文件须填写本地IP地址,WS运行太久,外部原因可能断开,支持自动重连 159 | 160 | 161 | 162 | //WebSocket 订单推送 API 163 | websocket.WSWithOrder() 164 | 165 | 166 | 167 | } 168 | -------------------------------------------------------------------------------- /Futures-Go-demo/main/mainip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huobiapi/Futures-Go-demo/ece4ffbdce90bdbccac9a38e9a97053a6c1bcd56/Futures-Go-demo/main/mainip -------------------------------------------------------------------------------- /Futures-Go-demo/main/wsmain: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huobiapi/Futures-Go-demo/ece4ffbdce90bdbccac9a38e9a97053a6c1bcd56/Futures-Go-demo/main/wsmain -------------------------------------------------------------------------------- /Futures-Go-demo/services/Market_test.go: -------------------------------------------------------------------------------- 1 | package services 2 | 3 | import ( 4 | "Futures-Go-demo/config" 5 | "Futures-Go-demo/websocket" 6 | "fmt" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | //测试获取合约信息接口 12 | func Test_FutureContractInfo(t *testing.T) { 13 | contractInfo := FutureContractInfo("BTC", "", "") 14 | fmt.Println("获取合约信息: ", contractInfo) 15 | 16 | } 17 | 18 | //测试获取合约指数信息接口 19 | func Test_FutureContractIndex(t *testing.T) { 20 | //contract_index := services.FutureContractIndex("BTC") 21 | contract_index := FutureContractIndex("BTC") 22 | fmt.Println("获取合约指数信息: ", contract_index) 23 | 24 | } 25 | 26 | //获取订单明细信息 27 | func Test_FutureContractOrderDetail(t *testing.T) { 28 | 29 | contract_order_detail := FutureContractOrderDetail("BTC", "123556", "1", "100", "1539345271124", "1") 30 | fmt.Println("获取订单明细信息: ", contract_order_detail) 31 | 32 | } 33 | 34 | //合约取消订单 35 | func Test_FutureContractCancel(t *testing.T) { 36 | contract_cancel := FutureContractCancel("123456", "BTC", "123456") 37 | fmt.Println("合约取消订单: ", contract_cancel) 38 | 39 | } 40 | 41 | //合约全部撤单 42 | func Test_FutureContractCancelall(t *testing.T) { 43 | contract_cancelall := FutureContractCancelall("BTC") 44 | fmt.Println("合约全部撤单: ", contract_cancelall) 45 | 46 | } 47 | 48 | //获取合约当前未成交委托 49 | func Test_FutureContractOpenorders(t *testing.T) { 50 | contract_openorders := FutureContractOpenorders("BTC", "1", "100") 51 | fmt.Println("获取合约当前未成交委托: ", contract_openorders) 52 | 53 | } 54 | 55 | //获取合约历史委托 56 | func Test_FutureContractHisorders(t *testing.T) { 57 | contract_hisorders := FutureContractHisorders("BTC", "0", "1", "0", "90", "1", "50") 58 | fmt.Println("获取合约历史委托: ", contract_hisorders) 59 | time.Sleep(time.Second) 60 | 61 | } 62 | 63 | //测试合约下单接口 64 | func Test_FutureContractOrder(t *testing.T) { 65 | //合约下单 66 | contract_order := FutureContractOrder("BTC", "this_week", "BTC181214", "", "6188", "12", 67 | "buy", "open", "10", "limit") 68 | fmt.Println("合约下单: ", contract_order) 69 | 70 | } 71 | 72 | //测试批量下单接口 73 | func Test_FutureContractBatchorder(t *testing.T) { 74 | //合约批量下单 75 | ordersData := make([]*Order, 0) 76 | order1 := &Order{ 77 | 78 | Symbol: "BTC", 79 | ContractType: "quarter", 80 | ContractCode: "BTC181228", 81 | ClientOrderId: "10", 82 | Price: "6188", 83 | Volume: "1", 84 | Direction: "buy", 85 | Offset: "open", 86 | LeverRate: "10", 87 | OrderPriceType: "limit", 88 | } 89 | 90 | ordersData = append(ordersData, order1) 91 | order2 := &Order{ 92 | 93 | Symbol: "BTC", 94 | ContractType: "quarter", 95 | ContractCode: "BTC181228", 96 | ClientOrderId: "11", 97 | Price: "6189", 98 | Volume: "2", 99 | Direction: "buy", 100 | Offset: "open", 101 | LeverRate: "10", 102 | OrderPriceType: "limit", 103 | } 104 | ordersData = append(ordersData, order2) 105 | fmt.Println("ordersData:", ordersData) 106 | 107 | contract_batchorder := FutureContractBatchorder(ordersData) 108 | fmt.Println("合约批量下单ordersDataResult: ", contract_batchorder) 109 | 110 | } 111 | 112 | //测试 WebSocket 行情,交易 API 113 | func Test_Websocket(t *testing.T) { 114 | //websocket.WSRun() //无需本地IP地址,直接运行 115 | websocket.WSRunWithIP(config.Local_IP) //配置文件须填写本地IP地址,WS运行太久,外部原因可能断开,支持自动重连 116 | } 117 | 118 | //测试 WebSocket 订单推送 API 119 | func Test_Websocket_order(t *testing.T) { 120 | 121 | websocket.WSWithOrder() 122 | } 123 | -------------------------------------------------------------------------------- /Futures-Go-demo/untils/CryptoUtil.go: -------------------------------------------------------------------------------- 1 | package untils 2 | 3 | import ( 4 | "github.com/dgrijalva/jwt-go" 5 | ) 6 | 7 | func SignByJWT(pem string, data string) (string, error) { 8 | key, err := jwt.ParseECPrivateKeyFromPEM([]byte(pem)) 9 | if nil != err { 10 | return "", err 11 | } 12 | 13 | alg := jwt.GetSigningMethod("ES256") 14 | return alg.Sign(data, key) 15 | } 16 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | bin 3 | 4 | 5 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | script: 4 | - go vet ./... 5 | - go test -v ./... 6 | 7 | go: 8 | - 1.3 9 | - 1.4 10 | - 1.5 11 | - 1.6 12 | - 1.7 13 | - tip 14 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Dave Grijalva 2 | 3 | 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: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | 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. 8 | 9 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md: -------------------------------------------------------------------------------- 1 | ## Migration Guide from v2 -> v3 2 | 3 | Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code. 4 | 5 | ### `Token.Claims` is now an interface type 6 | 7 | The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`. 8 | 9 | `MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property. 10 | 11 | The old example for parsing a token looked like this.. 12 | 13 | ```go 14 | if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { 15 | fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) 16 | } 17 | ``` 18 | 19 | is now directly mapped to... 20 | 21 | ```go 22 | if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { 23 | claims := token.Claims.(jwt.MapClaims) 24 | fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) 25 | } 26 | ``` 27 | 28 | `StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type. 29 | 30 | ```go 31 | type MyCustomClaims struct { 32 | User string 33 | *StandardClaims 34 | } 35 | 36 | if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil { 37 | claims := token.Claims.(*MyCustomClaims) 38 | fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt) 39 | } 40 | ``` 41 | 42 | ### `ParseFromRequest` has been moved 43 | 44 | To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`. 45 | 46 | `Extractors` do the work of picking the token string out of a request. The interface is simple and composable. 47 | 48 | This simple parsing example: 49 | 50 | ```go 51 | if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil { 52 | fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) 53 | } 54 | ``` 55 | 56 | is directly mapped to: 57 | 58 | ```go 59 | if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil { 60 | claims := token.Claims.(jwt.MapClaims) 61 | fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) 62 | } 63 | ``` 64 | 65 | There are several concrete `Extractor` types provided for your convenience: 66 | 67 | * `HeaderExtractor` will search a list of headers until one contains content. 68 | * `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content. 69 | * `MultiExtractor` will try a list of `Extractors` in order until one returns content. 70 | * `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token. 71 | * `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument 72 | * `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header 73 | 74 | 75 | ### RSA signing methods no longer accept `[]byte` keys 76 | 77 | Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse. 78 | 79 | To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types. 80 | 81 | ```go 82 | func keyLookupFunc(*Token) (interface{}, error) { 83 | // Don't forget to validate the alg is what you expect: 84 | if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { 85 | return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) 86 | } 87 | 88 | // Look up key 89 | key, err := lookupPublicKey(token.Header["kid"]) 90 | if err != nil { 91 | return nil, err 92 | } 93 | 94 | // Unpack key from PEM encoded PKCS8 95 | return jwt.ParseRSAPublicKeyFromPEM(key) 96 | } 97 | ``` 98 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/claims.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/subtle" 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | // For a type to be a Claims object, it must just have a Valid method that determines 10 | // if the token is invalid for any supported reason 11 | type Claims interface { 12 | Valid() error 13 | } 14 | 15 | // Structured version of Claims Section, as referenced at 16 | // https://tools.ietf.org/html/rfc7519#section-4.1 17 | // See examples for how to use this with your own claim types 18 | type StandardClaims struct { 19 | Audience string `json:"aud,omitempty"` 20 | ExpiresAt int64 `json:"exp,omitempty"` 21 | Id string `json:"jti,omitempty"` 22 | IssuedAt int64 `json:"iat,omitempty"` 23 | Issuer string `json:"iss,omitempty"` 24 | NotBefore int64 `json:"nbf,omitempty"` 25 | Subject string `json:"sub,omitempty"` 26 | } 27 | 28 | // Validates time based claims "exp, iat, nbf". 29 | // There is no accounting for clock skew. 30 | // As well, if any of the above claims are not in the token, it will still 31 | // be considered a valid claim. 32 | func (c StandardClaims) Valid() error { 33 | vErr := new(ValidationError) 34 | now := TimeFunc().Unix() 35 | 36 | // The claims below are optional, by default, so if they are set to the 37 | // default value in Go, let's not fail the verification for them. 38 | if c.VerifyExpiresAt(now, false) == false { 39 | delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) 40 | vErr.Inner = fmt.Errorf("token is expired by %v", delta) 41 | vErr.Errors |= ValidationErrorExpired 42 | } 43 | 44 | if c.VerifyIssuedAt(now, false) == false { 45 | vErr.Inner = fmt.Errorf("Token used before issued") 46 | vErr.Errors |= ValidationErrorIssuedAt 47 | } 48 | 49 | if c.VerifyNotBefore(now, false) == false { 50 | vErr.Inner = fmt.Errorf("token is not valid yet") 51 | vErr.Errors |= ValidationErrorNotValidYet 52 | } 53 | 54 | if vErr.valid() { 55 | return nil 56 | } 57 | 58 | return vErr 59 | } 60 | 61 | // Compares the aud claim against cmp. 62 | // If required is false, this method will return true if the value matches or is unset 63 | func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { 64 | return verifyAud(c.Audience, cmp, req) 65 | } 66 | 67 | // Compares the exp claim against cmp. 68 | // If required is false, this method will return true if the value matches or is unset 69 | func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { 70 | return verifyExp(c.ExpiresAt, cmp, req) 71 | } 72 | 73 | // Compares the iat claim against cmp. 74 | // If required is false, this method will return true if the value matches or is unset 75 | func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { 76 | return verifyIat(c.IssuedAt, cmp, req) 77 | } 78 | 79 | // Compares the iss claim against cmp. 80 | // If required is false, this method will return true if the value matches or is unset 81 | func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { 82 | return verifyIss(c.Issuer, cmp, req) 83 | } 84 | 85 | // Compares the nbf claim against cmp. 86 | // If required is false, this method will return true if the value matches or is unset 87 | func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { 88 | return verifyNbf(c.NotBefore, cmp, req) 89 | } 90 | 91 | // ----- helpers 92 | 93 | func verifyAud(aud string, cmp string, required bool) bool { 94 | if aud == "" { 95 | return !required 96 | } 97 | if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 { 98 | return true 99 | } else { 100 | return false 101 | } 102 | } 103 | 104 | func verifyExp(exp int64, now int64, required bool) bool { 105 | if exp == 0 { 106 | return !required 107 | } 108 | return now <= exp 109 | } 110 | 111 | func verifyIat(iat int64, now int64, required bool) bool { 112 | if iat == 0 { 113 | return !required 114 | } 115 | return now >= iat 116 | } 117 | 118 | func verifyIss(iss string, cmp string, required bool) bool { 119 | if iss == "" { 120 | return !required 121 | } 122 | if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { 123 | return true 124 | } else { 125 | return false 126 | } 127 | } 128 | 129 | func verifyNbf(nbf int64, now int64, required bool) bool { 130 | if nbf == 0 { 131 | return !required 132 | } 133 | return now >= nbf 134 | } 135 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/doc.go: -------------------------------------------------------------------------------- 1 | // Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html 2 | // 3 | // See README.md for more info. 4 | package jwt 5 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/ecdsa.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/ecdsa" 6 | "crypto/rand" 7 | "errors" 8 | "math/big" 9 | ) 10 | 11 | var ( 12 | // Sadly this is missing from crypto/ecdsa compared to crypto/rsa 13 | ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") 14 | ) 15 | 16 | // Implements the ECDSA family of signing methods signing methods 17 | // Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification 18 | type SigningMethodECDSA struct { 19 | Name string 20 | Hash crypto.Hash 21 | KeySize int 22 | CurveBits int 23 | } 24 | 25 | // Specific instances for EC256 and company 26 | var ( 27 | SigningMethodES256 *SigningMethodECDSA 28 | SigningMethodES384 *SigningMethodECDSA 29 | SigningMethodES512 *SigningMethodECDSA 30 | ) 31 | 32 | func init() { 33 | // ES256 34 | SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} 35 | RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { 36 | return SigningMethodES256 37 | }) 38 | 39 | // ES384 40 | SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} 41 | RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { 42 | return SigningMethodES384 43 | }) 44 | 45 | // ES512 46 | SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} 47 | RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { 48 | return SigningMethodES512 49 | }) 50 | } 51 | 52 | func (m *SigningMethodECDSA) Alg() string { 53 | return m.Name 54 | } 55 | 56 | // Implements the Verify method from SigningMethod 57 | // For this verify method, key must be an ecdsa.PublicKey struct 58 | func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { 59 | var err error 60 | 61 | // Decode the signature 62 | var sig []byte 63 | if sig, err = DecodeSegment(signature); err != nil { 64 | return err 65 | } 66 | 67 | // Get the key 68 | var ecdsaKey *ecdsa.PublicKey 69 | switch k := key.(type) { 70 | case *ecdsa.PublicKey: 71 | ecdsaKey = k 72 | default: 73 | return ErrInvalidKeyType 74 | } 75 | 76 | if len(sig) != 2*m.KeySize { 77 | return ErrECDSAVerification 78 | } 79 | 80 | r := big.NewInt(0).SetBytes(sig[:m.KeySize]) 81 | s := big.NewInt(0).SetBytes(sig[m.KeySize:]) 82 | 83 | // Create hasher 84 | if !m.Hash.Available() { 85 | return ErrHashUnavailable 86 | } 87 | hasher := m.Hash.New() 88 | hasher.Write([]byte(signingString)) 89 | 90 | // Verify the signature 91 | if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { 92 | return nil 93 | } else { 94 | return ErrECDSAVerification 95 | } 96 | } 97 | 98 | // Implements the Sign method from SigningMethod 99 | // For this signing method, key must be an ecdsa.PrivateKey struct 100 | func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { 101 | // Get the key 102 | var ecdsaKey *ecdsa.PrivateKey 103 | switch k := key.(type) { 104 | case *ecdsa.PrivateKey: 105 | ecdsaKey = k 106 | default: 107 | return "", ErrInvalidKeyType 108 | } 109 | 110 | // Create the hasher 111 | if !m.Hash.Available() { 112 | return "", ErrHashUnavailable 113 | } 114 | 115 | hasher := m.Hash.New() 116 | hasher.Write([]byte(signingString)) 117 | 118 | // Sign the string and return r, s 119 | if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { 120 | curveBits := ecdsaKey.Curve.Params().BitSize 121 | 122 | if m.CurveBits != curveBits { 123 | return "", ErrInvalidKey 124 | } 125 | 126 | keyBytes := curveBits / 8 127 | if curveBits%8 > 0 { 128 | keyBytes += 1 129 | } 130 | 131 | // We serialize the outpus (r and s) into big-endian byte arrays and pad 132 | // them with zeros on the left to make sure the sizes work out. Both arrays 133 | // must be keyBytes long, and the output must be 2*keyBytes long. 134 | rBytes := r.Bytes() 135 | rBytesPadded := make([]byte, keyBytes) 136 | copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) 137 | 138 | sBytes := s.Bytes() 139 | sBytesPadded := make([]byte, keyBytes) 140 | copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) 141 | 142 | out := append(rBytesPadded, sBytesPadded...) 143 | 144 | return EncodeSegment(out), nil 145 | } else { 146 | return "", err 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/ecdsa" 5 | "crypto/x509" 6 | "encoding/pem" 7 | "errors" 8 | ) 9 | 10 | var ( 11 | ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") 12 | ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") 13 | ) 14 | 15 | // Parse PEM encoded Elliptic Curve Private Key Structure 16 | func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { 17 | var err error 18 | 19 | // Parse PEM block 20 | var block *pem.Block 21 | if block, _ = pem.Decode(key); block == nil { 22 | return nil, ErrKeyMustBePEMEncoded 23 | } 24 | 25 | // Parse the key 26 | var parsedKey interface{} 27 | if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { 28 | return nil, err 29 | } 30 | 31 | var pkey *ecdsa.PrivateKey 32 | var ok bool 33 | if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { 34 | return nil, ErrNotECPrivateKey 35 | } 36 | 37 | return pkey, nil 38 | } 39 | 40 | // Parse PEM encoded PKCS1 or PKCS8 public key 41 | func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { 42 | var err error 43 | 44 | // Parse PEM block 45 | var block *pem.Block 46 | if block, _ = pem.Decode(key); block == nil { 47 | return nil, ErrKeyMustBePEMEncoded 48 | } 49 | 50 | // Parse the key 51 | var parsedKey interface{} 52 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 53 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil { 54 | parsedKey = cert.PublicKey 55 | } else { 56 | return nil, err 57 | } 58 | } 59 | 60 | var pkey *ecdsa.PublicKey 61 | var ok bool 62 | if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { 63 | return nil, ErrNotECPublicKey 64 | } 65 | 66 | return pkey, nil 67 | } 68 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/errors.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | // Error constants 8 | var ( 9 | ErrInvalidKey = errors.New("key is invalid") 10 | ErrInvalidKeyType = errors.New("key is of invalid type") 11 | ErrHashUnavailable = errors.New("the requested hash function is unavailable") 12 | ) 13 | 14 | // The errors that might occur when parsing and validating a token 15 | const ( 16 | ValidationErrorMalformed uint32 = 1 << iota // Token is malformed 17 | ValidationErrorUnverifiable // Token could not be verified because of signing problems 18 | ValidationErrorSignatureInvalid // Signature validation failed 19 | 20 | // Standard Claim validation errors 21 | ValidationErrorAudience // AUD validation failed 22 | ValidationErrorExpired // EXP validation failed 23 | ValidationErrorIssuedAt // IAT validation failed 24 | ValidationErrorIssuer // ISS validation failed 25 | ValidationErrorNotValidYet // NBF validation failed 26 | ValidationErrorId // JTI validation failed 27 | ValidationErrorClaimsInvalid // Generic claims validation error 28 | ) 29 | 30 | // Helper for constructing a ValidationError with a string error message 31 | func NewValidationError(errorText string, errorFlags uint32) *ValidationError { 32 | return &ValidationError{ 33 | text: errorText, 34 | Errors: errorFlags, 35 | } 36 | } 37 | 38 | // The error from Parse if token is not valid 39 | type ValidationError struct { 40 | Inner error // stores the error returned by external dependencies, i.e.: KeyFunc 41 | Errors uint32 // bitfield. see ValidationError... constants 42 | text string // errors that do not have a valid error just have text 43 | } 44 | 45 | // Validation error is an error type 46 | func (e ValidationError) Error() string { 47 | if e.Inner != nil { 48 | return e.Inner.Error() 49 | } else if e.text != "" { 50 | return e.text 51 | } else { 52 | return "token is invalid" 53 | } 54 | } 55 | 56 | // No errors 57 | func (e *ValidationError) valid() bool { 58 | return e.Errors == 0 59 | } 60 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/hmac.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/hmac" 6 | "errors" 7 | ) 8 | 9 | // Implements the HMAC-SHA family of signing methods signing methods 10 | // Expects key type of []byte for both signing and validation 11 | type SigningMethodHMAC struct { 12 | Name string 13 | Hash crypto.Hash 14 | } 15 | 16 | // Specific instances for HS256 and company 17 | var ( 18 | SigningMethodHS256 *SigningMethodHMAC 19 | SigningMethodHS384 *SigningMethodHMAC 20 | SigningMethodHS512 *SigningMethodHMAC 21 | ErrSignatureInvalid = errors.New("signature is invalid") 22 | ) 23 | 24 | func init() { 25 | // HS256 26 | SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} 27 | RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { 28 | return SigningMethodHS256 29 | }) 30 | 31 | // HS384 32 | SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} 33 | RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { 34 | return SigningMethodHS384 35 | }) 36 | 37 | // HS512 38 | SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} 39 | RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { 40 | return SigningMethodHS512 41 | }) 42 | } 43 | 44 | func (m *SigningMethodHMAC) Alg() string { 45 | return m.Name 46 | } 47 | 48 | // Verify the signature of HSXXX tokens. Returns nil if the signature is valid. 49 | func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { 50 | // Verify the key is the right type 51 | keyBytes, ok := key.([]byte) 52 | if !ok { 53 | return ErrInvalidKeyType 54 | } 55 | 56 | // Decode signature, for comparison 57 | sig, err := DecodeSegment(signature) 58 | if err != nil { 59 | return err 60 | } 61 | 62 | // Can we use the specified hashing method? 63 | if !m.Hash.Available() { 64 | return ErrHashUnavailable 65 | } 66 | 67 | // This signing method is symmetric, so we validate the signature 68 | // by reproducing the signature from the signing string and key, then 69 | // comparing that against the provided signature. 70 | hasher := hmac.New(m.Hash.New, keyBytes) 71 | hasher.Write([]byte(signingString)) 72 | if !hmac.Equal(sig, hasher.Sum(nil)) { 73 | return ErrSignatureInvalid 74 | } 75 | 76 | // No validation errors. Signature is good. 77 | return nil 78 | } 79 | 80 | // Implements the Sign method from SigningMethod for this signing method. 81 | // Key must be []byte 82 | func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { 83 | if keyBytes, ok := key.([]byte); ok { 84 | if !m.Hash.Available() { 85 | return "", ErrHashUnavailable 86 | } 87 | 88 | hasher := hmac.New(m.Hash.New, keyBytes) 89 | hasher.Write([]byte(signingString)) 90 | 91 | return EncodeSegment(hasher.Sum(nil)), nil 92 | } 93 | 94 | return "", ErrInvalidKeyType 95 | } 96 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/map_claims.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | // "fmt" 7 | ) 8 | 9 | // Claims type that uses the map[string]interface{} for JSON decoding 10 | // This is the default claims type if you don't supply one 11 | type MapClaims map[string]interface{} 12 | 13 | // Compares the aud claim against cmp. 14 | // If required is false, this method will return true if the value matches or is unset 15 | func (m MapClaims) VerifyAudience(cmp string, req bool) bool { 16 | aud, _ := m["aud"].(string) 17 | return verifyAud(aud, cmp, req) 18 | } 19 | 20 | // Compares the exp claim against cmp. 21 | // If required is false, this method will return true if the value matches or is unset 22 | func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { 23 | switch exp := m["exp"].(type) { 24 | case float64: 25 | return verifyExp(int64(exp), cmp, req) 26 | case json.Number: 27 | v, _ := exp.Int64() 28 | return verifyExp(v, cmp, req) 29 | } 30 | return req == false 31 | } 32 | 33 | // Compares the iat claim against cmp. 34 | // If required is false, this method will return true if the value matches or is unset 35 | func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { 36 | switch iat := m["iat"].(type) { 37 | case float64: 38 | return verifyIat(int64(iat), cmp, req) 39 | case json.Number: 40 | v, _ := iat.Int64() 41 | return verifyIat(v, cmp, req) 42 | } 43 | return req == false 44 | } 45 | 46 | // Compares the iss claim against cmp. 47 | // If required is false, this method will return true if the value matches or is unset 48 | func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { 49 | iss, _ := m["iss"].(string) 50 | return verifyIss(iss, cmp, req) 51 | } 52 | 53 | // Compares the nbf claim against cmp. 54 | // If required is false, this method will return true if the value matches or is unset 55 | func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { 56 | switch nbf := m["nbf"].(type) { 57 | case float64: 58 | return verifyNbf(int64(nbf), cmp, req) 59 | case json.Number: 60 | v, _ := nbf.Int64() 61 | return verifyNbf(v, cmp, req) 62 | } 63 | return req == false 64 | } 65 | 66 | // Validates time based claims "exp, iat, nbf". 67 | // There is no accounting for clock skew. 68 | // As well, if any of the above claims are not in the token, it will still 69 | // be considered a valid claim. 70 | func (m MapClaims) Valid() error { 71 | vErr := new(ValidationError) 72 | now := TimeFunc().Unix() 73 | 74 | if m.VerifyExpiresAt(now, false) == false { 75 | vErr.Inner = errors.New("Token is expired") 76 | vErr.Errors |= ValidationErrorExpired 77 | } 78 | 79 | if m.VerifyIssuedAt(now, false) == false { 80 | vErr.Inner = errors.New("Token used before issued") 81 | vErr.Errors |= ValidationErrorIssuedAt 82 | } 83 | 84 | if m.VerifyNotBefore(now, false) == false { 85 | vErr.Inner = errors.New("Token is not valid yet") 86 | vErr.Errors |= ValidationErrorNotValidYet 87 | } 88 | 89 | if vErr.valid() { 90 | return nil 91 | } 92 | 93 | return vErr 94 | } 95 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/none.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | // Implements the none signing method. This is required by the spec 4 | // but you probably should never use it. 5 | var SigningMethodNone *signingMethodNone 6 | 7 | const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" 8 | 9 | var NoneSignatureTypeDisallowedError error 10 | 11 | type signingMethodNone struct{} 12 | type unsafeNoneMagicConstant string 13 | 14 | func init() { 15 | SigningMethodNone = &signingMethodNone{} 16 | NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) 17 | 18 | RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { 19 | return SigningMethodNone 20 | }) 21 | } 22 | 23 | func (m *signingMethodNone) Alg() string { 24 | return "none" 25 | } 26 | 27 | // Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key 28 | func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { 29 | // Key must be UnsafeAllowNoneSignatureType to prevent accidentally 30 | // accepting 'none' signing method 31 | if _, ok := key.(unsafeNoneMagicConstant); !ok { 32 | return NoneSignatureTypeDisallowedError 33 | } 34 | // If signing method is none, signature must be an empty string 35 | if signature != "" { 36 | return NewValidationError( 37 | "'none' signing method with non-empty signature", 38 | ValidationErrorSignatureInvalid, 39 | ) 40 | } 41 | 42 | // Accept 'none' signing method. 43 | return nil 44 | } 45 | 46 | // Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key 47 | func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { 48 | if _, ok := key.(unsafeNoneMagicConstant); ok { 49 | return "", nil 50 | } 51 | return "", NoneSignatureTypeDisallowedError 52 | } 53 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/parser.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "strings" 8 | ) 9 | 10 | type Parser struct { 11 | ValidMethods []string // If populated, only these methods will be considered valid 12 | UseJSONNumber bool // Use JSON Number format in JSON decoder 13 | SkipClaimsValidation bool // Skip claims validation during token parsing 14 | } 15 | 16 | // Parse, validate, and return a token. 17 | // keyFunc will receive the parsed token and should return the key for validating. 18 | // If everything is kosher, err will be nil 19 | func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { 20 | return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) 21 | } 22 | 23 | func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { 24 | token, parts, err := p.ParseUnverified(tokenString, claims) 25 | if err != nil { 26 | return token, err 27 | } 28 | 29 | // Verify signing method is in the required set 30 | if p.ValidMethods != nil { 31 | var signingMethodValid = false 32 | var alg = token.Method.Alg() 33 | for _, m := range p.ValidMethods { 34 | if m == alg { 35 | signingMethodValid = true 36 | break 37 | } 38 | } 39 | if !signingMethodValid { 40 | // signing method is not in the listed set 41 | return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) 42 | } 43 | } 44 | 45 | // Lookup key 46 | var key interface{} 47 | if keyFunc == nil { 48 | // keyFunc was not provided. short circuiting validation 49 | return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) 50 | } 51 | if key, err = keyFunc(token); err != nil { 52 | // keyFunc returned an error 53 | if ve, ok := err.(*ValidationError); ok { 54 | return token, ve 55 | } 56 | return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} 57 | } 58 | 59 | vErr := &ValidationError{} 60 | 61 | // Validate Claims 62 | if !p.SkipClaimsValidation { 63 | if err := token.Claims.Valid(); err != nil { 64 | 65 | // If the Claims Valid returned an error, check if it is a validation error, 66 | // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set 67 | if e, ok := err.(*ValidationError); !ok { 68 | vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} 69 | } else { 70 | vErr = e 71 | } 72 | } 73 | } 74 | 75 | // Perform validation 76 | token.Signature = parts[2] 77 | if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { 78 | vErr.Inner = err 79 | vErr.Errors |= ValidationErrorSignatureInvalid 80 | } 81 | 82 | if vErr.valid() { 83 | token.Valid = true 84 | return token, nil 85 | } 86 | 87 | return token, vErr 88 | } 89 | 90 | // WARNING: Don't use this method unless you know what you're doing 91 | // 92 | // This method parses the token but doesn't validate the signature. It's only 93 | // ever useful in cases where you know the signature is valid (because it has 94 | // been checked previously in the stack) and you want to extract values from 95 | // it. 96 | func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { 97 | parts = strings.Split(tokenString, ".") 98 | if len(parts) != 3 { 99 | return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) 100 | } 101 | 102 | token = &Token{Raw: tokenString} 103 | 104 | // parse Header 105 | var headerBytes []byte 106 | if headerBytes, err = DecodeSegment(parts[0]); err != nil { 107 | if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { 108 | return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) 109 | } 110 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 111 | } 112 | if err = json.Unmarshal(headerBytes, &token.Header); err != nil { 113 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 114 | } 115 | 116 | // parse Claims 117 | var claimBytes []byte 118 | token.Claims = claims 119 | 120 | if claimBytes, err = DecodeSegment(parts[1]); err != nil { 121 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 122 | } 123 | dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) 124 | if p.UseJSONNumber { 125 | dec.UseNumber() 126 | } 127 | // JSON Decode. Special case for map type to avoid weird pointer behavior 128 | if c, ok := token.Claims.(MapClaims); ok { 129 | err = dec.Decode(&c) 130 | } else { 131 | err = dec.Decode(&claims) 132 | } 133 | // Handle decode error 134 | if err != nil { 135 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 136 | } 137 | 138 | // Lookup signature method 139 | if method, ok := token.Header["alg"].(string); ok { 140 | if token.Method = GetSigningMethod(method); token.Method == nil { 141 | return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) 142 | } 143 | } else { 144 | return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) 145 | } 146 | 147 | return token, parts, nil 148 | } 149 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/rsa.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | ) 8 | 9 | // Implements the RSA family of signing methods signing methods 10 | // Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation 11 | type SigningMethodRSA struct { 12 | Name string 13 | Hash crypto.Hash 14 | } 15 | 16 | // Specific instances for RS256 and company 17 | var ( 18 | SigningMethodRS256 *SigningMethodRSA 19 | SigningMethodRS384 *SigningMethodRSA 20 | SigningMethodRS512 *SigningMethodRSA 21 | ) 22 | 23 | func init() { 24 | // RS256 25 | SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} 26 | RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { 27 | return SigningMethodRS256 28 | }) 29 | 30 | // RS384 31 | SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} 32 | RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { 33 | return SigningMethodRS384 34 | }) 35 | 36 | // RS512 37 | SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} 38 | RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { 39 | return SigningMethodRS512 40 | }) 41 | } 42 | 43 | func (m *SigningMethodRSA) Alg() string { 44 | return m.Name 45 | } 46 | 47 | // Implements the Verify method from SigningMethod 48 | // For this signing method, must be an *rsa.PublicKey structure. 49 | func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { 50 | var err error 51 | 52 | // Decode the signature 53 | var sig []byte 54 | if sig, err = DecodeSegment(signature); err != nil { 55 | return err 56 | } 57 | 58 | var rsaKey *rsa.PublicKey 59 | var ok bool 60 | 61 | if rsaKey, ok = key.(*rsa.PublicKey); !ok { 62 | return ErrInvalidKeyType 63 | } 64 | 65 | // Create hasher 66 | if !m.Hash.Available() { 67 | return ErrHashUnavailable 68 | } 69 | hasher := m.Hash.New() 70 | hasher.Write([]byte(signingString)) 71 | 72 | // Verify the signature 73 | return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) 74 | } 75 | 76 | // Implements the Sign method from SigningMethod 77 | // For this signing method, must be an *rsa.PrivateKey structure. 78 | func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { 79 | var rsaKey *rsa.PrivateKey 80 | var ok bool 81 | 82 | // Validate type of key 83 | if rsaKey, ok = key.(*rsa.PrivateKey); !ok { 84 | return "", ErrInvalidKey 85 | } 86 | 87 | // Create the hasher 88 | if !m.Hash.Available() { 89 | return "", ErrHashUnavailable 90 | } 91 | 92 | hasher := m.Hash.New() 93 | hasher.Write([]byte(signingString)) 94 | 95 | // Sign the string and return the encoded bytes 96 | if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { 97 | return EncodeSegment(sigBytes), nil 98 | } else { 99 | return "", err 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go: -------------------------------------------------------------------------------- 1 | // +build go1.4 2 | 3 | package jwt 4 | 5 | import ( 6 | "crypto" 7 | "crypto/rand" 8 | "crypto/rsa" 9 | ) 10 | 11 | // Implements the RSAPSS family of signing methods signing methods 12 | type SigningMethodRSAPSS struct { 13 | *SigningMethodRSA 14 | Options *rsa.PSSOptions 15 | } 16 | 17 | // Specific instances for RS/PS and company 18 | var ( 19 | SigningMethodPS256 *SigningMethodRSAPSS 20 | SigningMethodPS384 *SigningMethodRSAPSS 21 | SigningMethodPS512 *SigningMethodRSAPSS 22 | ) 23 | 24 | func init() { 25 | // PS256 26 | SigningMethodPS256 = &SigningMethodRSAPSS{ 27 | &SigningMethodRSA{ 28 | Name: "PS256", 29 | Hash: crypto.SHA256, 30 | }, 31 | &rsa.PSSOptions{ 32 | SaltLength: rsa.PSSSaltLengthAuto, 33 | Hash: crypto.SHA256, 34 | }, 35 | } 36 | RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { 37 | return SigningMethodPS256 38 | }) 39 | 40 | // PS384 41 | SigningMethodPS384 = &SigningMethodRSAPSS{ 42 | &SigningMethodRSA{ 43 | Name: "PS384", 44 | Hash: crypto.SHA384, 45 | }, 46 | &rsa.PSSOptions{ 47 | SaltLength: rsa.PSSSaltLengthAuto, 48 | Hash: crypto.SHA384, 49 | }, 50 | } 51 | RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { 52 | return SigningMethodPS384 53 | }) 54 | 55 | // PS512 56 | SigningMethodPS512 = &SigningMethodRSAPSS{ 57 | &SigningMethodRSA{ 58 | Name: "PS512", 59 | Hash: crypto.SHA512, 60 | }, 61 | &rsa.PSSOptions{ 62 | SaltLength: rsa.PSSSaltLengthAuto, 63 | Hash: crypto.SHA512, 64 | }, 65 | } 66 | RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { 67 | return SigningMethodPS512 68 | }) 69 | } 70 | 71 | // Implements the Verify method from SigningMethod 72 | // For this verify method, key must be an rsa.PublicKey struct 73 | func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { 74 | var err error 75 | 76 | // Decode the signature 77 | var sig []byte 78 | if sig, err = DecodeSegment(signature); err != nil { 79 | return err 80 | } 81 | 82 | var rsaKey *rsa.PublicKey 83 | switch k := key.(type) { 84 | case *rsa.PublicKey: 85 | rsaKey = k 86 | default: 87 | return ErrInvalidKey 88 | } 89 | 90 | // Create hasher 91 | if !m.Hash.Available() { 92 | return ErrHashUnavailable 93 | } 94 | hasher := m.Hash.New() 95 | hasher.Write([]byte(signingString)) 96 | 97 | return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options) 98 | } 99 | 100 | // Implements the Sign method from SigningMethod 101 | // For this signing method, key must be an rsa.PrivateKey struct 102 | func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { 103 | var rsaKey *rsa.PrivateKey 104 | 105 | switch k := key.(type) { 106 | case *rsa.PrivateKey: 107 | rsaKey = k 108 | default: 109 | return "", ErrInvalidKeyType 110 | } 111 | 112 | // Create the hasher 113 | if !m.Hash.Available() { 114 | return "", ErrHashUnavailable 115 | } 116 | 117 | hasher := m.Hash.New() 118 | hasher.Write([]byte(signingString)) 119 | 120 | // Sign the string and return the encoded bytes 121 | if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { 122 | return EncodeSegment(sigBytes), nil 123 | } else { 124 | return "", err 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/rsa" 5 | "crypto/x509" 6 | "encoding/pem" 7 | "errors" 8 | ) 9 | 10 | var ( 11 | ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") 12 | ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") 13 | ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") 14 | ) 15 | 16 | // Parse PEM encoded PKCS1 or PKCS8 private key 17 | func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { 18 | var err error 19 | 20 | // Parse PEM block 21 | var block *pem.Block 22 | if block, _ = pem.Decode(key); block == nil { 23 | return nil, ErrKeyMustBePEMEncoded 24 | } 25 | 26 | var parsedKey interface{} 27 | if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { 28 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { 29 | return nil, err 30 | } 31 | } 32 | 33 | var pkey *rsa.PrivateKey 34 | var ok bool 35 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { 36 | return nil, ErrNotRSAPrivateKey 37 | } 38 | 39 | return pkey, nil 40 | } 41 | 42 | // Parse PEM encoded PKCS1 or PKCS8 private key protected with password 43 | func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { 44 | var err error 45 | 46 | // Parse PEM block 47 | var block *pem.Block 48 | if block, _ = pem.Decode(key); block == nil { 49 | return nil, ErrKeyMustBePEMEncoded 50 | } 51 | 52 | var parsedKey interface{} 53 | 54 | var blockDecrypted []byte 55 | if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { 56 | return nil, err 57 | } 58 | 59 | if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { 60 | if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { 61 | return nil, err 62 | } 63 | } 64 | 65 | var pkey *rsa.PrivateKey 66 | var ok bool 67 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { 68 | return nil, ErrNotRSAPrivateKey 69 | } 70 | 71 | return pkey, nil 72 | } 73 | 74 | // Parse PEM encoded PKCS1 or PKCS8 public key 75 | func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { 76 | var err error 77 | 78 | // Parse PEM block 79 | var block *pem.Block 80 | if block, _ = pem.Decode(key); block == nil { 81 | return nil, ErrKeyMustBePEMEncoded 82 | } 83 | 84 | // Parse the key 85 | var parsedKey interface{} 86 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 87 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil { 88 | parsedKey = cert.PublicKey 89 | } else { 90 | return nil, err 91 | } 92 | } 93 | 94 | var pkey *rsa.PublicKey 95 | var ok bool 96 | if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { 97 | return nil, ErrNotRSAPublicKey 98 | } 99 | 100 | return pkey, nil 101 | } 102 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/signing_method.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "sync" 5 | ) 6 | 7 | var signingMethods = map[string]func() SigningMethod{} 8 | var signingMethodLock = new(sync.RWMutex) 9 | 10 | // Implement SigningMethod to add new methods for signing or verifying tokens. 11 | type SigningMethod interface { 12 | Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid 13 | Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error 14 | Alg() string // returns the alg identifier for this method (example: 'HS256') 15 | } 16 | 17 | // Register the "alg" name and a factory function for signing method. 18 | // This is typically done during init() in the method's implementation 19 | func RegisterSigningMethod(alg string, f func() SigningMethod) { 20 | signingMethodLock.Lock() 21 | defer signingMethodLock.Unlock() 22 | 23 | signingMethods[alg] = f 24 | } 25 | 26 | // Get a signing method from an "alg" string 27 | func GetSigningMethod(alg string) (method SigningMethod) { 28 | signingMethodLock.RLock() 29 | defer signingMethodLock.RUnlock() 30 | 31 | if methodF, ok := signingMethods[alg]; ok { 32 | method = methodF() 33 | } 34 | return 35 | } 36 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/dgrijalva/jwt-go/token.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "encoding/base64" 5 | "encoding/json" 6 | "strings" 7 | "time" 8 | ) 9 | 10 | // TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). 11 | // You can override it to use another time value. This is useful for testing or if your 12 | // server uses a different time zone than your tokens. 13 | var TimeFunc = time.Now 14 | 15 | // Parse methods use this callback function to supply 16 | // the key for verification. The function receives the parsed, 17 | // but unverified Token. This allows you to use properties in the 18 | // Header of the token (such as `kid`) to identify which key to use. 19 | type Keyfunc func(*Token) (interface{}, error) 20 | 21 | // A JWT Token. Different fields will be used depending on whether you're 22 | // creating or parsing/verifying a token. 23 | type Token struct { 24 | Raw string // The raw token. Populated when you Parse a token 25 | Method SigningMethod // The signing method used or to be used 26 | Header map[string]interface{} // The first segment of the token 27 | Claims Claims // The second segment of the token 28 | Signature string // The third segment of the token. Populated when you Parse a token 29 | Valid bool // Is the token valid? Populated when you Parse/Verify a token 30 | } 31 | 32 | // Create a new Token. Takes a signing method 33 | func New(method SigningMethod) *Token { 34 | return NewWithClaims(method, MapClaims{}) 35 | } 36 | 37 | func NewWithClaims(method SigningMethod, claims Claims) *Token { 38 | return &Token{ 39 | Header: map[string]interface{}{ 40 | "typ": "JWT", 41 | "alg": method.Alg(), 42 | }, 43 | Claims: claims, 44 | Method: method, 45 | } 46 | } 47 | 48 | // Get the complete, signed token 49 | func (t *Token) SignedString(key interface{}) (string, error) { 50 | var sig, sstr string 51 | var err error 52 | if sstr, err = t.SigningString(); err != nil { 53 | return "", err 54 | } 55 | if sig, err = t.Method.Sign(sstr, key); err != nil { 56 | return "", err 57 | } 58 | return strings.Join([]string{sstr, sig}, "."), nil 59 | } 60 | 61 | // Generate the signing string. This is the 62 | // most expensive part of the whole deal. Unless you 63 | // need this for something special, just go straight for 64 | // the SignedString. 65 | func (t *Token) SigningString() (string, error) { 66 | var err error 67 | parts := make([]string, 2) 68 | for i, _ := range parts { 69 | var jsonValue []byte 70 | if i == 0 { 71 | if jsonValue, err = json.Marshal(t.Header); err != nil { 72 | return "", err 73 | } 74 | } else { 75 | if jsonValue, err = json.Marshal(t.Claims); err != nil { 76 | return "", err 77 | } 78 | } 79 | 80 | parts[i] = EncodeSegment(jsonValue) 81 | } 82 | return strings.Join(parts, "."), nil 83 | } 84 | 85 | // Parse, validate, and return a token. 86 | // keyFunc will receive the parsed token and should return the key for validating. 87 | // If everything is kosher, err will be nil 88 | func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { 89 | return new(Parser).Parse(tokenString, keyFunc) 90 | } 91 | 92 | func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { 93 | return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) 94 | } 95 | 96 | // Encode JWT specific base64url encoding with padding stripped 97 | func EncodeSegment(seg []byte) string { 98 | return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") 99 | } 100 | 101 | // Decode JWT specific base64url encoding with padding stripped 102 | func DecodeSegment(seg string) ([]byte, error) { 103 | if l := len(seg) % 4; l > 0 { 104 | seg += strings.Repeat("=", 4-l) 105 | } 106 | 107 | return base64.URLEncoding.DecodeString(seg) 108 | } 109 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | 24 | .idea/ 25 | *.iml 26 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | sudo: false 3 | 4 | matrix: 5 | include: 6 | - go: 1.7.x 7 | - go: 1.8.x 8 | - go: 1.9.x 9 | - go: 1.10.x 10 | - go: 1.11.x 11 | - go: tip 12 | allow_failures: 13 | - go: tip 14 | 15 | script: 16 | - go get -t -v ./... 17 | - diff -u <(echo -n) <(gofmt -d .) 18 | - go vet $(go list ./... | grep -v /vendor/) 19 | - go test -v -race ./... 20 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the official list of Gorilla WebSocket authors for copyright 2 | # purposes. 3 | # 4 | # Please keep the list sorted. 5 | 6 | Gary Burd 7 | Google LLC (https://opensource.google.com/) 8 | Joachim Bauch 9 | 10 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are met: 5 | 6 | Redistributions of source code must retain the above copyright notice, this 7 | list of conditions and the following disclaimer. 8 | 9 | Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 17 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 18 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 19 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 20 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 21 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 22 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/README.md: -------------------------------------------------------------------------------- 1 | # Gorilla WebSocket 2 | 3 | Gorilla WebSocket is a [Go](http://golang.org/) implementation of the 4 | [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. 5 | 6 | [![Build Status](https://travis-ci.org/gorilla/websocket.svg?branch=master)](https://travis-ci.org/gorilla/websocket) 7 | [![GoDoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket) 8 | 9 | ### Documentation 10 | 11 | * [API Reference](http://godoc.org/github.com/gorilla/websocket) 12 | * [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat) 13 | * [Command example](https://github.com/gorilla/websocket/tree/master/examples/command) 14 | * [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo) 15 | * [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch) 16 | 17 | ### Status 18 | 19 | The Gorilla WebSocket package provides a complete and tested implementation of 20 | the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. The 21 | package API is stable. 22 | 23 | ### Installation 24 | 25 | go get github.com/gorilla/websocket 26 | 27 | ### Protocol Compliance 28 | 29 | The Gorilla WebSocket package passes the server tests in the [Autobahn Test 30 | Suite](http://autobahn.ws/testsuite) using the application in the [examples/autobahn 31 | subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn). 32 | 33 | ### Gorilla WebSocket compared with other packages 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 |
github.com/gorillagolang.org/x/net
RFC 6455 Features
Passes Autobahn Test SuiteYesNo
Receive fragmented messageYesNo, see note 1
Send close messageYesNo
Send pings and receive pongsYesNo
Get the type of a received data messageYesYes, see note 2
Other Features
Compression ExtensionsExperimentalNo
Read message using io.ReaderYesNo, see note 3
Write message using io.WriteCloserYesNo, see note 3
53 | 54 | Notes: 55 | 56 | 1. Large messages are fragmented in [Chrome's new WebSocket implementation](http://www.ietf.org/mail-archive/web/hybi/current/msg10503.html). 57 | 2. The application can get the type of a received data message by implementing 58 | a [Codec marshal](http://godoc.org/golang.org/x/net/websocket#Codec.Marshal) 59 | function. 60 | 3. The go.net io.Reader and io.Writer operate across WebSocket frame boundaries. 61 | Read returns when the input buffer is full or a frame boundary is 62 | encountered. Each call to Write sends a single frame message. The Gorilla 63 | io.Reader and io.WriteCloser operate on a single WebSocket message. 64 | 65 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/client_clone.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.8 6 | 7 | package websocket 8 | 9 | import "crypto/tls" 10 | 11 | func cloneTLSConfig(cfg *tls.Config) *tls.Config { 12 | if cfg == nil { 13 | return &tls.Config{} 14 | } 15 | return cfg.Clone() 16 | } 17 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/client_clone_legacy.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !go1.8 6 | 7 | package websocket 8 | 9 | import "crypto/tls" 10 | 11 | // cloneTLSConfig clones all public fields except the fields 12 | // SessionTicketsDisabled and SessionTicketKey. This avoids copying the 13 | // sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a 14 | // config in active use. 15 | func cloneTLSConfig(cfg *tls.Config) *tls.Config { 16 | if cfg == nil { 17 | return &tls.Config{} 18 | } 19 | return &tls.Config{ 20 | Rand: cfg.Rand, 21 | Time: cfg.Time, 22 | Certificates: cfg.Certificates, 23 | NameToCertificate: cfg.NameToCertificate, 24 | GetCertificate: cfg.GetCertificate, 25 | RootCAs: cfg.RootCAs, 26 | NextProtos: cfg.NextProtos, 27 | ServerName: cfg.ServerName, 28 | ClientAuth: cfg.ClientAuth, 29 | ClientCAs: cfg.ClientCAs, 30 | InsecureSkipVerify: cfg.InsecureSkipVerify, 31 | CipherSuites: cfg.CipherSuites, 32 | PreferServerCipherSuites: cfg.PreferServerCipherSuites, 33 | ClientSessionCache: cfg.ClientSessionCache, 34 | MinVersion: cfg.MinVersion, 35 | MaxVersion: cfg.MaxVersion, 36 | CurvePreferences: cfg.CurvePreferences, 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/compression.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "compress/flate" 9 | "errors" 10 | "io" 11 | "strings" 12 | "sync" 13 | ) 14 | 15 | const ( 16 | minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6 17 | maxCompressionLevel = flate.BestCompression 18 | defaultCompressionLevel = 1 19 | ) 20 | 21 | var ( 22 | flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool 23 | flateReaderPool = sync.Pool{New: func() interface{} { 24 | return flate.NewReader(nil) 25 | }} 26 | ) 27 | 28 | func decompressNoContextTakeover(r io.Reader) io.ReadCloser { 29 | const tail = 30 | // Add four bytes as specified in RFC 31 | "\x00\x00\xff\xff" + 32 | // Add final block to squelch unexpected EOF error from flate reader. 33 | "\x01\x00\x00\xff\xff" 34 | 35 | fr, _ := flateReaderPool.Get().(io.ReadCloser) 36 | fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil) 37 | return &flateReadWrapper{fr} 38 | } 39 | 40 | func isValidCompressionLevel(level int) bool { 41 | return minCompressionLevel <= level && level <= maxCompressionLevel 42 | } 43 | 44 | func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser { 45 | p := &flateWriterPools[level-minCompressionLevel] 46 | tw := &truncWriter{w: w} 47 | fw, _ := p.Get().(*flate.Writer) 48 | if fw == nil { 49 | fw, _ = flate.NewWriter(tw, level) 50 | } else { 51 | fw.Reset(tw) 52 | } 53 | return &flateWriteWrapper{fw: fw, tw: tw, p: p} 54 | } 55 | 56 | // truncWriter is an io.Writer that writes all but the last four bytes of the 57 | // stream to another io.Writer. 58 | type truncWriter struct { 59 | w io.WriteCloser 60 | n int 61 | p [4]byte 62 | } 63 | 64 | func (w *truncWriter) Write(p []byte) (int, error) { 65 | n := 0 66 | 67 | // fill buffer first for simplicity. 68 | if w.n < len(w.p) { 69 | n = copy(w.p[w.n:], p) 70 | p = p[n:] 71 | w.n += n 72 | if len(p) == 0 { 73 | return n, nil 74 | } 75 | } 76 | 77 | m := len(p) 78 | if m > len(w.p) { 79 | m = len(w.p) 80 | } 81 | 82 | if nn, err := w.w.Write(w.p[:m]); err != nil { 83 | return n + nn, err 84 | } 85 | 86 | copy(w.p[:], w.p[m:]) 87 | copy(w.p[len(w.p)-m:], p[len(p)-m:]) 88 | nn, err := w.w.Write(p[:len(p)-m]) 89 | return n + nn, err 90 | } 91 | 92 | type flateWriteWrapper struct { 93 | fw *flate.Writer 94 | tw *truncWriter 95 | p *sync.Pool 96 | } 97 | 98 | func (w *flateWriteWrapper) Write(p []byte) (int, error) { 99 | if w.fw == nil { 100 | return 0, errWriteClosed 101 | } 102 | return w.fw.Write(p) 103 | } 104 | 105 | func (w *flateWriteWrapper) Close() error { 106 | if w.fw == nil { 107 | return errWriteClosed 108 | } 109 | err1 := w.fw.Flush() 110 | w.p.Put(w.fw) 111 | w.fw = nil 112 | if w.tw.p != [4]byte{0, 0, 0xff, 0xff} { 113 | return errors.New("websocket: internal error, unexpected bytes at end of flate stream") 114 | } 115 | err2 := w.tw.w.Close() 116 | if err1 != nil { 117 | return err1 118 | } 119 | return err2 120 | } 121 | 122 | type flateReadWrapper struct { 123 | fr io.ReadCloser 124 | } 125 | 126 | func (r *flateReadWrapper) Read(p []byte) (int, error) { 127 | if r.fr == nil { 128 | return 0, io.ErrClosedPipe 129 | } 130 | n, err := r.fr.Read(p) 131 | if err == io.EOF { 132 | // Preemptively place the reader back in the pool. This helps with 133 | // scenarios where the application does not call NextReader() soon after 134 | // this final read. 135 | r.Close() 136 | } 137 | return n, err 138 | } 139 | 140 | func (r *flateReadWrapper) Close() error { 141 | if r.fr == nil { 142 | return io.ErrClosedPipe 143 | } 144 | err := r.fr.Close() 145 | flateReaderPool.Put(r.fr) 146 | r.fr = nil 147 | return err 148 | } 149 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/conn_write.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.8 6 | 7 | package websocket 8 | 9 | import "net" 10 | 11 | func (c *Conn) writeBufs(bufs ...[]byte) error { 12 | b := net.Buffers(bufs) 13 | _, err := b.WriteTo(c.conn) 14 | return err 15 | } 16 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/conn_write_legacy.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !go1.8 6 | 7 | package websocket 8 | 9 | func (c *Conn) writeBufs(bufs ...[]byte) error { 10 | for _, buf := range bufs { 11 | if len(buf) > 0 { 12 | if _, err := c.conn.Write(buf); err != nil { 13 | return err 14 | } 15 | } 16 | } 17 | return nil 18 | } 19 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/json.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "encoding/json" 9 | "io" 10 | ) 11 | 12 | // WriteJSON writes the JSON encoding of v as a message. 13 | // 14 | // Deprecated: Use c.WriteJSON instead. 15 | func WriteJSON(c *Conn, v interface{}) error { 16 | return c.WriteJSON(v) 17 | } 18 | 19 | // WriteJSON writes the JSON encoding of v as a message. 20 | // 21 | // See the documentation for encoding/json Marshal for details about the 22 | // conversion of Go values to JSON. 23 | func (c *Conn) WriteJSON(v interface{}) error { 24 | w, err := c.NextWriter(TextMessage) 25 | if err != nil { 26 | return err 27 | } 28 | err1 := json.NewEncoder(w).Encode(v) 29 | err2 := w.Close() 30 | if err1 != nil { 31 | return err1 32 | } 33 | return err2 34 | } 35 | 36 | // ReadJSON reads the next JSON-encoded message from the connection and stores 37 | // it in the value pointed to by v. 38 | // 39 | // Deprecated: Use c.ReadJSON instead. 40 | func ReadJSON(c *Conn, v interface{}) error { 41 | return c.ReadJSON(v) 42 | } 43 | 44 | // ReadJSON reads the next JSON-encoded message from the connection and stores 45 | // it in the value pointed to by v. 46 | // 47 | // See the documentation for the encoding/json Unmarshal function for details 48 | // about the conversion of JSON to a Go value. 49 | func (c *Conn) ReadJSON(v interface{}) error { 50 | _, r, err := c.NextReader() 51 | if err != nil { 52 | return err 53 | } 54 | err = json.NewDecoder(r).Decode(v) 55 | if err == io.EOF { 56 | // One value is expected in the message. 57 | err = io.ErrUnexpectedEOF 58 | } 59 | return err 60 | } 61 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/mask.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of 2 | // this source code is governed by a BSD-style license that can be found in the 3 | // LICENSE file. 4 | 5 | // +build !appengine 6 | 7 | package websocket 8 | 9 | import "unsafe" 10 | 11 | const wordSize = int(unsafe.Sizeof(uintptr(0))) 12 | 13 | func maskBytes(key [4]byte, pos int, b []byte) int { 14 | // Mask one byte at a time for small buffers. 15 | if len(b) < 2*wordSize { 16 | for i := range b { 17 | b[i] ^= key[pos&3] 18 | pos++ 19 | } 20 | return pos & 3 21 | } 22 | 23 | // Mask one byte at a time to word boundary. 24 | if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 { 25 | n = wordSize - n 26 | for i := range b[:n] { 27 | b[i] ^= key[pos&3] 28 | pos++ 29 | } 30 | b = b[n:] 31 | } 32 | 33 | // Create aligned word size key. 34 | var k [wordSize]byte 35 | for i := range k { 36 | k[i] = key[(pos+i)&3] 37 | } 38 | kw := *(*uintptr)(unsafe.Pointer(&k)) 39 | 40 | // Mask one word at a time. 41 | n := (len(b) / wordSize) * wordSize 42 | for i := 0; i < n; i += wordSize { 43 | *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw 44 | } 45 | 46 | // Mask one byte at a time for remaining bytes. 47 | b = b[n:] 48 | for i := range b { 49 | b[i] ^= key[pos&3] 50 | pos++ 51 | } 52 | 53 | return pos & 3 54 | } 55 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/mask_safe.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of 2 | // this source code is governed by a BSD-style license that can be found in the 3 | // LICENSE file. 4 | 5 | // +build appengine 6 | 7 | package websocket 8 | 9 | func maskBytes(key [4]byte, pos int, b []byte) int { 10 | for i := range b { 11 | b[i] ^= key[pos&3] 12 | pos++ 13 | } 14 | return pos & 3 15 | } 16 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/prepared.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "bytes" 9 | "net" 10 | "sync" 11 | "time" 12 | ) 13 | 14 | // PreparedMessage caches on the wire representations of a message payload. 15 | // Use PreparedMessage to efficiently send a message payload to multiple 16 | // connections. PreparedMessage is especially useful when compression is used 17 | // because the CPU and memory expensive compression operation can be executed 18 | // once for a given set of compression options. 19 | type PreparedMessage struct { 20 | messageType int 21 | data []byte 22 | mu sync.Mutex 23 | frames map[prepareKey]*preparedFrame 24 | } 25 | 26 | // prepareKey defines a unique set of options to cache prepared frames in PreparedMessage. 27 | type prepareKey struct { 28 | isServer bool 29 | compress bool 30 | compressionLevel int 31 | } 32 | 33 | // preparedFrame contains data in wire representation. 34 | type preparedFrame struct { 35 | once sync.Once 36 | data []byte 37 | } 38 | 39 | // NewPreparedMessage returns an initialized PreparedMessage. You can then send 40 | // it to connection using WritePreparedMessage method. Valid wire 41 | // representation will be calculated lazily only once for a set of current 42 | // connection options. 43 | func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) { 44 | pm := &PreparedMessage{ 45 | messageType: messageType, 46 | frames: make(map[prepareKey]*preparedFrame), 47 | data: data, 48 | } 49 | 50 | // Prepare a plain server frame. 51 | _, frameData, err := pm.frame(prepareKey{isServer: true, compress: false}) 52 | if err != nil { 53 | return nil, err 54 | } 55 | 56 | // To protect against caller modifying the data argument, remember the data 57 | // copied to the plain server frame. 58 | pm.data = frameData[len(frameData)-len(data):] 59 | return pm, nil 60 | } 61 | 62 | func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) { 63 | pm.mu.Lock() 64 | frame, ok := pm.frames[key] 65 | if !ok { 66 | frame = &preparedFrame{} 67 | pm.frames[key] = frame 68 | } 69 | pm.mu.Unlock() 70 | 71 | var err error 72 | frame.once.Do(func() { 73 | // Prepare a frame using a 'fake' connection. 74 | // TODO: Refactor code in conn.go to allow more direct construction of 75 | // the frame. 76 | mu := make(chan bool, 1) 77 | mu <- true 78 | var nc prepareConn 79 | c := &Conn{ 80 | conn: &nc, 81 | mu: mu, 82 | isServer: key.isServer, 83 | compressionLevel: key.compressionLevel, 84 | enableWriteCompression: true, 85 | writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize), 86 | } 87 | if key.compress { 88 | c.newCompressionWriter = compressNoContextTakeover 89 | } 90 | err = c.WriteMessage(pm.messageType, pm.data) 91 | frame.data = nc.buf.Bytes() 92 | }) 93 | return pm.messageType, frame.data, err 94 | } 95 | 96 | type prepareConn struct { 97 | buf bytes.Buffer 98 | net.Conn 99 | } 100 | 101 | func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) } 102 | func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil } 103 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/proxy.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "bufio" 9 | "encoding/base64" 10 | "errors" 11 | "net" 12 | "net/http" 13 | "net/url" 14 | "strings" 15 | ) 16 | 17 | type netDialerFunc func(network, addr string) (net.Conn, error) 18 | 19 | func (fn netDialerFunc) Dial(network, addr string) (net.Conn, error) { 20 | return fn(network, addr) 21 | } 22 | 23 | func init() { 24 | proxy_RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy_Dialer) (proxy_Dialer, error) { 25 | return &httpProxyDialer{proxyURL: proxyURL, fowardDial: forwardDialer.Dial}, nil 26 | }) 27 | } 28 | 29 | type httpProxyDialer struct { 30 | proxyURL *url.URL 31 | fowardDial func(network, addr string) (net.Conn, error) 32 | } 33 | 34 | func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) { 35 | hostPort, _ := hostPortNoPort(hpd.proxyURL) 36 | conn, err := hpd.fowardDial(network, hostPort) 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | connectHeader := make(http.Header) 42 | if user := hpd.proxyURL.User; user != nil { 43 | proxyUser := user.Username() 44 | if proxyPassword, passwordSet := user.Password(); passwordSet { 45 | credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword)) 46 | connectHeader.Set("Proxy-Authorization", "Basic "+credential) 47 | } 48 | } 49 | 50 | connectReq := &http.Request{ 51 | Method: "CONNECT", 52 | URL: &url.URL{Opaque: addr}, 53 | Host: addr, 54 | Header: connectHeader, 55 | } 56 | 57 | if err := connectReq.Write(conn); err != nil { 58 | conn.Close() 59 | return nil, err 60 | } 61 | 62 | // Read response. It's OK to use and discard buffered reader here becaue 63 | // the remote server does not speak until spoken to. 64 | br := bufio.NewReader(conn) 65 | resp, err := http.ReadResponse(br, connectReq) 66 | if err != nil { 67 | conn.Close() 68 | return nil, err 69 | } 70 | 71 | if resp.StatusCode != 200 { 72 | conn.Close() 73 | f := strings.SplitN(resp.Status, " ", 2) 74 | return nil, errors.New(f[1]) 75 | } 76 | return conn, nil 77 | } 78 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/trace.go: -------------------------------------------------------------------------------- 1 | // +build go1.8 2 | 3 | package websocket 4 | 5 | import ( 6 | "crypto/tls" 7 | "net/http/httptrace" 8 | ) 9 | 10 | func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error { 11 | if trace.TLSHandshakeStart != nil { 12 | trace.TLSHandshakeStart() 13 | } 14 | err := doHandshake(tlsConn, cfg) 15 | if trace.TLSHandshakeDone != nil { 16 | trace.TLSHandshakeDone(tlsConn.ConnectionState(), err) 17 | } 18 | return err 19 | } 20 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/gorilla/websocket/trace_17.go: -------------------------------------------------------------------------------- 1 | // +build !go1.8 2 | 3 | package websocket 4 | 5 | import ( 6 | "crypto/tls" 7 | "net/http/httptrace" 8 | ) 9 | 10 | func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error { 11 | return doHandshake(tlsConn, cfg) 12 | } 13 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/spf13/cast/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | 25 | *.bench 26 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/spf13/cast/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | env: 3 | - GO111MODULE=on 4 | sudo: required 5 | go: 6 | - "1.11.x" 7 | - tip 8 | os: 9 | - linux 10 | matrix: 11 | allow_failures: 12 | - go: tip 13 | fast_finish: true 14 | script: 15 | - make check 16 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/spf13/cast/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Steve Francia 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/spf13/cast/Makefile: -------------------------------------------------------------------------------- 1 | # A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html 2 | 3 | .PHONY: check fmt lint test test-race vet test-cover-html help 4 | .DEFAULT_GOAL := help 5 | 6 | check: test-race fmt vet lint ## Run tests and linters 7 | 8 | test: ## Run tests 9 | go test ./... 10 | 11 | test-race: ## Run tests with race detector 12 | go test -race ./... 13 | 14 | fmt: ## Run gofmt linter 15 | @for d in `go list` ; do \ 16 | if [ "`gofmt -l -s $$GOPATH/src/$$d | tee /dev/stderr`" ]; then \ 17 | echo "^ improperly formatted go files" && echo && exit 1; \ 18 | fi \ 19 | done 20 | 21 | lint: ## Run golint linter 22 | @for d in `go list` ; do \ 23 | if [ "`golint $$d | tee /dev/stderr`" ]; then \ 24 | echo "^ golint errors!" && echo && exit 1; \ 25 | fi \ 26 | done 27 | 28 | vet: ## Run go vet linter 29 | @if [ "`go vet | tee /dev/stderr`" ]; then \ 30 | echo "^ go vet errors!" && echo && exit 1; \ 31 | fi 32 | 33 | test-cover-html: ## Generate test coverage report 34 | go test -coverprofile=coverage.out -covermode=count 35 | go tool cover -func=coverage.out 36 | 37 | help: 38 | @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' 39 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/spf13/cast/README.md: -------------------------------------------------------------------------------- 1 | cast 2 | ==== 3 | [![GoDoc](https://godoc.org/github.com/spf13/cast?status.svg)](https://godoc.org/github.com/spf13/cast) 4 | [![Build Status](https://api.travis-ci.org/spf13/cast.svg?branch=master)](https://travis-ci.org/spf13/cast) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cast)](https://goreportcard.com/report/github.com/spf13/cast) 6 | 7 | Easy and safe casting from one type to another in Go 8 | 9 | Don’t Panic! ... Cast 10 | 11 | ## What is Cast? 12 | 13 | Cast is a library to convert between different go types in a consistent and easy way. 14 | 15 | Cast provides simple functions to easily convert a number to a string, an 16 | interface into a bool, etc. Cast does this intelligently when an obvious 17 | conversion is possible. It doesn’t make any attempts to guess what you meant, 18 | for example you can only convert a string to an int when it is a string 19 | representation of an int such as “8”. Cast was developed for use in 20 | [Hugo](http://hugo.spf13.com), a website engine which uses YAML, TOML or JSON 21 | for meta data. 22 | 23 | ## Why use Cast? 24 | 25 | When working with dynamic data in Go you often need to cast or convert the data 26 | from one type into another. Cast goes beyond just using type assertion (though 27 | it uses that when possible) to provide a very straightforward and convenient 28 | library. 29 | 30 | If you are working with interfaces to handle things like dynamic content 31 | you’ll need an easy way to convert an interface into a given type. This 32 | is the library for you. 33 | 34 | If you are taking in data from YAML, TOML or JSON or other formats which lack 35 | full types, then Cast is the library for you. 36 | 37 | ## Usage 38 | 39 | Cast provides a handful of To_____ methods. These methods will always return 40 | the desired type. **If input is provided that will not convert to that type, the 41 | 0 or nil value for that type will be returned**. 42 | 43 | Cast also provides identical methods To_____E. These return the same result as 44 | the To_____ methods, plus an additional error which tells you if it successfully 45 | converted. Using these methods you can tell the difference between when the 46 | input matched the zero value or when the conversion failed and the zero value 47 | was returned. 48 | 49 | The following examples are merely a sample of what is available. Please review 50 | the code for a complete set. 51 | 52 | ### Example ‘ToString’: 53 | 54 | cast.ToString("mayonegg") // "mayonegg" 55 | cast.ToString(8) // "8" 56 | cast.ToString(8.31) // "8.31" 57 | cast.ToString([]byte("one time")) // "one time" 58 | cast.ToString(nil) // "" 59 | 60 | var foo interface{} = "one more time" 61 | cast.ToString(foo) // "one more time" 62 | 63 | 64 | ### Example ‘ToInt’: 65 | 66 | cast.ToInt(8) // 8 67 | cast.ToInt(8.31) // 8 68 | cast.ToInt("8") // 8 69 | cast.ToInt(true) // 1 70 | cast.ToInt(false) // 0 71 | 72 | var eight interface{} = 8 73 | cast.ToInt(eight) // 8 74 | cast.ToInt(nil) // 0 75 | 76 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/spf13/cast/cast.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2014 Steve Francia . 2 | // 3 | // Use of this source code is governed by an MIT-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // Package cast provides easy and safe casting in Go. 7 | package cast 8 | 9 | import "time" 10 | 11 | // ToBool casts an interface to a bool type. 12 | func ToBool(i interface{}) bool { 13 | v, _ := ToBoolE(i) 14 | return v 15 | } 16 | 17 | // ToTime casts an interface to a time.Time type. 18 | func ToTime(i interface{}) time.Time { 19 | v, _ := ToTimeE(i) 20 | return v 21 | } 22 | 23 | // ToDuration casts an interface to a time.Duration type. 24 | func ToDuration(i interface{}) time.Duration { 25 | v, _ := ToDurationE(i) 26 | return v 27 | } 28 | 29 | // ToFloat64 casts an interface to a float64 type. 30 | func ToFloat64(i interface{}) float64 { 31 | v, _ := ToFloat64E(i) 32 | return v 33 | } 34 | 35 | // ToFloat32 casts an interface to a float32 type. 36 | func ToFloat32(i interface{}) float32 { 37 | v, _ := ToFloat32E(i) 38 | return v 39 | } 40 | 41 | // ToInt64 casts an interface to an int64 type. 42 | func ToInt64(i interface{}) int64 { 43 | v, _ := ToInt64E(i) 44 | return v 45 | } 46 | 47 | // ToInt32 casts an interface to an int32 type. 48 | func ToInt32(i interface{}) int32 { 49 | v, _ := ToInt32E(i) 50 | return v 51 | } 52 | 53 | // ToInt16 casts an interface to an int16 type. 54 | func ToInt16(i interface{}) int16 { 55 | v, _ := ToInt16E(i) 56 | return v 57 | } 58 | 59 | // ToInt8 casts an interface to an int8 type. 60 | func ToInt8(i interface{}) int8 { 61 | v, _ := ToInt8E(i) 62 | return v 63 | } 64 | 65 | // ToInt casts an interface to an int type. 66 | func ToInt(i interface{}) int { 67 | v, _ := ToIntE(i) 68 | return v 69 | } 70 | 71 | // ToUint casts an interface to a uint type. 72 | func ToUint(i interface{}) uint { 73 | v, _ := ToUintE(i) 74 | return v 75 | } 76 | 77 | // ToUint64 casts an interface to a uint64 type. 78 | func ToUint64(i interface{}) uint64 { 79 | v, _ := ToUint64E(i) 80 | return v 81 | } 82 | 83 | // ToUint32 casts an interface to a uint32 type. 84 | func ToUint32(i interface{}) uint32 { 85 | v, _ := ToUint32E(i) 86 | return v 87 | } 88 | 89 | // ToUint16 casts an interface to a uint16 type. 90 | func ToUint16(i interface{}) uint16 { 91 | v, _ := ToUint16E(i) 92 | return v 93 | } 94 | 95 | // ToUint8 casts an interface to a uint8 type. 96 | func ToUint8(i interface{}) uint8 { 97 | v, _ := ToUint8E(i) 98 | return v 99 | } 100 | 101 | // ToString casts an interface to a string type. 102 | func ToString(i interface{}) string { 103 | v, _ := ToStringE(i) 104 | return v 105 | } 106 | 107 | // ToStringMapString casts an interface to a map[string]string type. 108 | func ToStringMapString(i interface{}) map[string]string { 109 | v, _ := ToStringMapStringE(i) 110 | return v 111 | } 112 | 113 | // ToStringMapStringSlice casts an interface to a map[string][]string type. 114 | func ToStringMapStringSlice(i interface{}) map[string][]string { 115 | v, _ := ToStringMapStringSliceE(i) 116 | return v 117 | } 118 | 119 | // ToStringMapBool casts an interface to a map[string]bool type. 120 | func ToStringMapBool(i interface{}) map[string]bool { 121 | v, _ := ToStringMapBoolE(i) 122 | return v 123 | } 124 | 125 | // ToStringMapInt casts an interface to a map[string]int type. 126 | func ToStringMapInt(i interface{}) map[string]int { 127 | v, _ := ToStringMapIntE(i) 128 | return v 129 | } 130 | 131 | // ToStringMapInt64 casts an interface to a map[string]int64 type. 132 | func ToStringMapInt64(i interface{}) map[string]int64 { 133 | v, _ := ToStringMapInt64E(i) 134 | return v 135 | } 136 | 137 | // ToStringMap casts an interface to a map[string]interface{} type. 138 | func ToStringMap(i interface{}) map[string]interface{} { 139 | v, _ := ToStringMapE(i) 140 | return v 141 | } 142 | 143 | // ToSlice casts an interface to a []interface{} type. 144 | func ToSlice(i interface{}) []interface{} { 145 | v, _ := ToSliceE(i) 146 | return v 147 | } 148 | 149 | // ToBoolSlice casts an interface to a []bool type. 150 | func ToBoolSlice(i interface{}) []bool { 151 | v, _ := ToBoolSliceE(i) 152 | return v 153 | } 154 | 155 | // ToStringSlice casts an interface to a []string type. 156 | func ToStringSlice(i interface{}) []string { 157 | v, _ := ToStringSliceE(i) 158 | return v 159 | } 160 | 161 | // ToIntSlice casts an interface to a []int type. 162 | func ToIntSlice(i interface{}) []int { 163 | v, _ := ToIntSliceE(i) 164 | return v 165 | } 166 | 167 | // ToDurationSlice casts an interface to a []time.Duration type. 168 | func ToDurationSlice(i interface{}) []time.Duration { 169 | v, _ := ToDurationSliceE(i) 170 | return v 171 | } 172 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/spf13/cast/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/spf13/cast 2 | 3 | require ( 4 | github.com/davecgh/go-spew v1.1.1 // indirect 5 | github.com/pmezard/go-difflib v1.0.0 // indirect 6 | github.com/stretchr/testify v1.2.2 7 | ) 8 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/github.com/spf13/cast/go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= 6 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 7 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/golang.org/x/net/AUTHORS: -------------------------------------------------------------------------------- 1 | # This source code refers to The Go Authors for copyright purposes. 2 | # The master list of authors is in the main Go distribution, 3 | # visible at http://tip.golang.org/AUTHORS. 4 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/golang.org/x/net/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This source code was written by the Go contributors. 2 | # The master list of contributors is in the main Go distribution, 3 | # visible at http://tip.golang.org/CONTRIBUTORS. 4 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/golang.org/x/net/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/golang.org/x/net/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/golang.org/x/net/websocket/client.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "bufio" 9 | "io" 10 | "net" 11 | "net/http" 12 | "net/url" 13 | ) 14 | 15 | // DialError is an error that occurs while dialling a websocket server. 16 | type DialError struct { 17 | *Config 18 | Err error 19 | } 20 | 21 | func (e *DialError) Error() string { 22 | return "websocket.Dial " + e.Config.Location.String() + ": " + e.Err.Error() 23 | } 24 | 25 | // NewConfig creates a new WebSocket config for client connection. 26 | func NewConfig(server, origin string) (config *Config, err error) { 27 | config = new(Config) 28 | config.Version = ProtocolVersionHybi13 29 | config.Location, err = url.ParseRequestURI(server) 30 | if err != nil { 31 | return 32 | } 33 | config.Origin, err = url.ParseRequestURI(origin) 34 | if err != nil { 35 | return 36 | } 37 | config.Header = http.Header(make(map[string][]string)) 38 | return 39 | } 40 | 41 | // NewClient creates a new WebSocket client connection over rwc. 42 | func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) { 43 | br := bufio.NewReader(rwc) 44 | bw := bufio.NewWriter(rwc) 45 | err = hybiClientHandshake(config, br, bw) 46 | if err != nil { 47 | return 48 | } 49 | buf := bufio.NewReadWriter(br, bw) 50 | ws = newHybiClientConn(config, buf, rwc) 51 | return 52 | } 53 | 54 | // Dial opens a new client connection to a WebSocket. 55 | func Dial(url_, protocol, origin string) (ws *Conn, err error) { 56 | config, err := NewConfig(url_, origin) 57 | if err != nil { 58 | return nil, err 59 | } 60 | if protocol != "" { 61 | config.Protocol = []string{protocol} 62 | } 63 | return DialConfig(config) 64 | } 65 | 66 | var portMap = map[string]string{ 67 | "ws": "80", 68 | "wss": "443", 69 | } 70 | 71 | func parseAuthority(location *url.URL) string { 72 | if _, ok := portMap[location.Scheme]; ok { 73 | if _, _, err := net.SplitHostPort(location.Host); err != nil { 74 | return net.JoinHostPort(location.Host, portMap[location.Scheme]) 75 | } 76 | } 77 | return location.Host 78 | } 79 | 80 | // DialConfig opens a new client connection to a WebSocket with a config. 81 | func DialConfig(config *Config) (ws *Conn, err error) { 82 | var client net.Conn 83 | if config.Location == nil { 84 | return nil, &DialError{config, ErrBadWebSocketLocation} 85 | } 86 | if config.Origin == nil { 87 | return nil, &DialError{config, ErrBadWebSocketOrigin} 88 | } 89 | dialer := config.Dialer 90 | if dialer == nil { 91 | dialer = &net.Dialer{} 92 | } 93 | client, err = dialWithDialer(dialer, config) 94 | if err != nil { 95 | goto Error 96 | } 97 | ws, err = NewClient(config, client) 98 | if err != nil { 99 | client.Close() 100 | goto Error 101 | } 102 | return 103 | 104 | Error: 105 | return nil, &DialError{config, err} 106 | } 107 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/golang.org/x/net/websocket/dial.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "crypto/tls" 9 | "net" 10 | ) 11 | 12 | func dialWithDialer(dialer *net.Dialer, config *Config) (conn net.Conn, err error) { 13 | switch config.Location.Scheme { 14 | case "ws": 15 | conn, err = dialer.Dial("tcp", parseAuthority(config.Location)) 16 | 17 | case "wss": 18 | conn, err = tls.DialWithDialer(dialer, "tcp", parseAuthority(config.Location), config.TlsConfig) 19 | 20 | default: 21 | err = ErrBadScheme 22 | } 23 | return 24 | } 25 | -------------------------------------------------------------------------------- /Futures-Go-demo/vendor/golang.org/x/net/websocket/server.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "bufio" 9 | "fmt" 10 | "io" 11 | "net/http" 12 | ) 13 | 14 | func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request, config *Config, handshake func(*Config, *http.Request) error) (conn *Conn, err error) { 15 | var hs serverHandshaker = &hybiServerHandshaker{Config: config} 16 | code, err := hs.ReadHandshake(buf.Reader, req) 17 | if err == ErrBadWebSocketVersion { 18 | fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) 19 | fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion) 20 | buf.WriteString("\r\n") 21 | buf.WriteString(err.Error()) 22 | buf.Flush() 23 | return 24 | } 25 | if err != nil { 26 | fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) 27 | buf.WriteString("\r\n") 28 | buf.WriteString(err.Error()) 29 | buf.Flush() 30 | return 31 | } 32 | if handshake != nil { 33 | err = handshake(config, req) 34 | if err != nil { 35 | code = http.StatusForbidden 36 | fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) 37 | buf.WriteString("\r\n") 38 | buf.Flush() 39 | return 40 | } 41 | } 42 | err = hs.AcceptHandshake(buf.Writer) 43 | if err != nil { 44 | code = http.StatusBadRequest 45 | fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) 46 | buf.WriteString("\r\n") 47 | buf.Flush() 48 | return 49 | } 50 | conn = hs.NewServerConn(buf, rwc, req) 51 | return 52 | } 53 | 54 | // Server represents a server of a WebSocket. 55 | type Server struct { 56 | // Config is a WebSocket configuration for new WebSocket connection. 57 | Config 58 | 59 | // Handshake is an optional function in WebSocket handshake. 60 | // For example, you can check, or don't check Origin header. 61 | // Another example, you can select config.Protocol. 62 | Handshake func(*Config, *http.Request) error 63 | 64 | // Handler handles a WebSocket connection. 65 | Handler 66 | } 67 | 68 | // ServeHTTP implements the http.Handler interface for a WebSocket 69 | func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) { 70 | s.serveWebSocket(w, req) 71 | } 72 | 73 | func (s Server) serveWebSocket(w http.ResponseWriter, req *http.Request) { 74 | rwc, buf, err := w.(http.Hijacker).Hijack() 75 | if err != nil { 76 | panic("Hijack failed: " + err.Error()) 77 | } 78 | // The server should abort the WebSocket connection if it finds 79 | // the client did not send a handshake that matches with protocol 80 | // specification. 81 | defer rwc.Close() 82 | conn, err := newServerConn(rwc, buf, req, &s.Config, s.Handshake) 83 | if err != nil { 84 | return 85 | } 86 | if conn == nil { 87 | panic("unexpected nil conn") 88 | } 89 | s.Handler(conn) 90 | } 91 | 92 | // Handler is a simple interface to a WebSocket browser client. 93 | // It checks if Origin header is valid URL by default. 94 | // You might want to verify websocket.Conn.Config().Origin in the func. 95 | // If you use Server instead of Handler, you could call websocket.Origin and 96 | // check the origin in your Handshake func. So, if you want to accept 97 | // non-browser clients, which do not send an Origin header, set a 98 | // Server.Handshake that does not check the origin. 99 | type Handler func(*Conn) 100 | 101 | func checkOrigin(config *Config, req *http.Request) (err error) { 102 | config.Origin, err = Origin(config, req) 103 | if err == nil && config.Origin == nil { 104 | return fmt.Errorf("null origin") 105 | } 106 | return err 107 | } 108 | 109 | // ServeHTTP implements the http.Handler interface for a WebSocket 110 | func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { 111 | s := Server{Handler: h, Handshake: checkOrigin} 112 | s.serveWebSocket(w, req) 113 | } 114 | -------------------------------------------------------------------------------- /Futures-Go-demo/websocket/ws.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | import ( 4 | "Futures-Go-demo/config" 5 | "bytes" 6 | "compress/gzip" 7 | "encoding/binary" 8 | "fmt" 9 | "io/ioutil" 10 | "log" 11 | 12 | "golang.org/x/net/websocket" 13 | ) 14 | 15 | var origin = "http://www.baidu.com" 16 | 17 | //var url = "wss://www.hbdm.com/ws" 18 | var buffer bytes.Buffer 19 | 20 | func ParseGzip(data []byte, handleErr bool) ([]byte, error) { 21 | b := new(bytes.Buffer) 22 | binary.Write(b, binary.LittleEndian, data) 23 | r, err := gzip.NewReader(b) 24 | if err != nil { 25 | //with error 26 | fmt.Printf("[ParseGzip %t %d] NewReader error: %v, maybe data is ungzip: [%s]\n", handleErr, len(data), err) 27 | if handleErr { 28 | errHandler(data) 29 | } 30 | return nil, err 31 | } else { 32 | defer r.Close() 33 | undatas, err := ioutil.ReadAll(r) 34 | if err != nil { 35 | //with error 36 | fmt.Printf("[ParseGzip %t %d] ioutil.ReadAll error: %v: [%s]\n", handleErr, len(data), err) 37 | if handleErr { 38 | errHandler(data) 39 | } 40 | return nil, err 41 | } else { 42 | //buffer.Reset() 43 | return undatas, nil 44 | } 45 | } 46 | } 47 | 48 | func errHandler(data []byte) { 49 | buffer.Write(data) 50 | msg, err := ParseGzip(buffer.Bytes(), false) 51 | if err == nil { 52 | fmt.Println("!!!!!!", string(msg[:])) 53 | } 54 | } 55 | 56 | func send(message []byte, ws *websocket.Conn) { 57 | _, err := ws.Write(message) 58 | if err != nil { 59 | log.Fatal(err) 60 | } 61 | fmt.Printf("Send: %s\n", message) 62 | } 63 | 64 | func WSRun() { 65 | ws, err := websocket.Dial(config.WS_URL, "", origin) 66 | if err != nil { 67 | log.Fatal(err) 68 | } 69 | 70 | //=============================================================================== 71 | 72 | //订阅websocket kline 73 | /* 74 | "market.$symbol.kline.$period" 75 | symbol true string 交易对 如"BTC_CW"表示BTC当周合约,"BTC_NW"表示BTC次周合约,"BTC_CQ"表示BTC季度合约 76 | period true string K线周期 1min, 5min, 15min, 30min, 60min,4hour,1day, 1mon 77 | */ 78 | message := []byte("{\"Sub\":\"market.BTC_CW.kline.1min\"}") 79 | send(message, ws) 80 | 81 | 82 | //订阅websocket Market Detail 数据 83 | /* 84 | "market.$symbol.detail" 85 | symbol true string 交易对 如"BTC_CW"表示BTC当周合约,"BTC_NW"表示BTC次周合约,"BTC_CQ"表示BTC季度合约 86 | */ 87 | message = []byte("{\"Sub\":\"market.BTC_CW.detail\"}") 88 | send(message, ws) 89 | 90 | //订阅websocket Trade Detail 数据 91 | /* 92 | "market.$symbol.trade.detail" 93 | symbol true string 交易对 如"BTC_CW"表示BTC当周合约,"BTC_NW"表示BTC次周合约,"BTC_CQ"表示BTC季度合约 94 | */ 95 | message = []byte("{\"Sub\":\"market.BTC_CW.trade.detail\"}") 96 | send(message, ws) 97 | 98 | 99 | //订阅websocket Market Depth 数据 100 | /* 101 | "market.$symbol.depth.$type" 102 | symbol true string 交易对 如"BTC_CW"表示BTC当周合约,"BTC_NW"表示BTC次周合约,"BTC_CQ"表示BTC季度合约. 103 | type true string Depth 类型 (150档数据) step0, step1, step2, step3, step4, step5(合并深度1-5);step0时,不合并深度 104 | (20档数据) step6, step7, step8, step9, step10, step11(合并深度7-11);step6时,不合并深度 105 | */ 106 | message = []byte("{\"Sub\":\"market.BTC_CW.depth.step0\"}") 107 | send(message, ws) 108 | 109 | 110 | //请求websocket KLine 数据 111 | /* 112 | "market.$symbol.kline.$period" 113 | symbol true string 交易对 如"BTC_CW"表示BTC当周合约,"BTC_NW"表示BTC次周合约,"BTC_CQ"表示BTC季度合约 114 | period true string K线周期 1min, 5min, 15min, 30min, 60min,4hour,1day, 1mon 115 | 116 | "from": "optional, type: long, 2017-07-28T00:00:00+08:00 至2050-01-01T00:00:00+08:00 之间的时间点,单位:秒", 117 | "to": "optional, type: long, 2017-07-28T00:00:00+08:00 至2050-01-01T00:00:00+08:00 之间的时间点,单位:秒,必须比 from 大"} 118 | 119 | [t1, t5] 假设有 t1 ~ t5 的K线: 120 | 121 | from: t1, to: t5, return [t1, t5]. 122 | from: t5, to: t1, which t5 > t1, return []. 123 | from: t5, return [t5]. 124 | from: t3, return [t3, t5]. 125 | to: t5, return [t1, t5]. 126 | from: t which t3 < t 21 { 159 | pingcmd := string(unzipmsg[2:6]) 160 | if "ping" == pingcmd { 161 | pingtime := string(unzipmsg[8:21]) 162 | pongstr := fmt.Sprintf("{\"pong\":%s}", pingtime) 163 | message := []byte(pongstr) 164 | 165 | send(message, ws) 166 | } 167 | } 168 | } 169 | 170 | ws.Close() //关闭连接 171 | 172 | } 173 | -------------------------------------------------------------------------------- /Futures-Go-demo/websocket/ws_order.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "Futures-Go-demo/untils" 8 | "golang.org/x/net/websocket" 9 | 10 | "Futures-Go-demo/config" 11 | ) 12 | 13 | func sendOrder(message []byte, ws *websocket.Conn) { 14 | _, err := ws.Write(message) 15 | if err != nil { 16 | log.Fatal(err) 17 | } 18 | //fmt.Printf("Send: %s\n", message) 19 | } 20 | func WSWithOrder() { 21 | 22 | params :=make(map[string]string) 23 | resultParams := untils.ApiKeyGetOrder(params, "/notification") 24 | 25 | run(resultParams) 26 | 27 | } 28 | func run(mapParams map[string]string) { 29 | 30 | 31 | 32 | 33 | ws, err := websocket.Dial(config.WS_ORDER_URL, "", origin) 34 | if err != nil { 35 | log.Fatal(err) 36 | } 37 | 38 | /************************************************/ 39 | /** 40 | * 发送账户订单请求鉴权 41 | * Send account order authentication request 42 | */ 43 | str := fmt.Sprintf("{\"op\":\"%s\",\"type\":\"%s\",\"AccessKeyId\":\"%s\",\"SignatureMethod\":\"%s\"," + 44 | "\"SignatureVersion\":\"%s\",\"Timestamp\":\"%s\",\"Signature\":\"%s\"}",mapParams["op"],mapParams["type"], 45 | mapParams["AccessKeyId"],mapParams["SignatureMethod"],mapParams["SignatureVersion"],mapParams["Timestamp"],mapParams["Signature"]) 46 | 47 | message := []byte(str) 48 | sendOrder(message, ws) 49 | 50 | //sub 51 | /** 52 | * 发送账户订单sub请求 53 | * Send account order sub request 54 | * @param topic 订阅topic 55 | * @param cid 标识 56 | */ 57 | // orders.btc 这样的格式,可以填写orders.eth orders.ltc ... 58 | subStr := fmt.Sprintf("{\"op\":\"%s\",\"topic\":\"%s\",\"cid\":\"%s\"}","sub","orders.btc","btc") 59 | subMessage := []byte(subStr) 60 | sendOrder(subMessage, ws) 61 | fmt.Printf("Send: %s\n", subMessage) 62 | 63 | //unsub 64 | /** 65 | * 发送账户订单取消订阅发送unsub请求 66 | * Send account order unsub request 67 | * @param topic unsub请求topic、 topic unsub request topic 68 | * @param cid 标识、 cid identifying 69 | */ 70 | 71 | /* 72 | unsubStr := fmt.Sprintf("{\"op\":\"%s\",\"topic\":\"%s\",\"cid\":\"%s\"}","unsub","orders.btc","btc") 73 | unsubMessage := []byte(unsubStr) 74 | sendOrder(unsubMessage, ws) 75 | fmt.Printf("Send: %s\n", unsubMessage) 76 | 77 | */ 78 | 79 | 80 | 81 | var msg = make([]byte, 512000) 82 | 83 | for { 84 | m, err := ws.Read(msg) 85 | if err != nil { 86 | log.Fatal(err) 87 | } 88 | 89 | newmsg := msg[:m] 90 | 91 | unzipmsg, _ := ParseGzip(newmsg, true) 92 | fmt.Printf("Receive: %s\n", unzipmsg) 93 | 94 | 95 | if len(unzipmsg) > 33 { 96 | pingcmd := string(unzipmsg[7:11]) 97 | if "ping" == pingcmd { 98 | 99 | pingtime := string(unzipmsg[19:33]) 100 | pongsStr := fmt.Sprintf("{\"op\":\"%s\",\"ts\":\"%s}","pong",pingtime) 101 | pongMessage := []byte(pongsStr) 102 | sendOrder(pongMessage, ws) 103 | fmt.Printf("Send: %s\n", pongMessage) 104 | } 105 | } 106 | } 107 | 108 | ws.Close() //关闭连接 109 | 110 | 111 | } 112 | 113 | 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Futures-Go-demo --------------------------------------------------------------------------------