Merge pull request #200 from fnproject/fix-deps

Fix deps
This commit is contained in:
oracloud
2017-08-09 14:21:36 +02:00
committed by GitHub
5614 changed files with 188194 additions and 1135763 deletions

View File

@@ -2,46 +2,20 @@ package docker
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
"github.com/Sirupsen/logrus"
manifest "github.com/docker/distribution/manifest/schema1"
"github.com/fnproject/fn/api/runner/common"
"github.com/fnproject/fn/api/runner/drivers"
"github.com/fsouza/go-dockerclient"
"github.com/heroku/docker-registry-client/registry"
"github.com/opentracing/opentracing-go"
)
const hubURL = "https://registry.hub.docker.com"
var registryClient = &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 2 * time.Minute,
}).Dial,
TLSClientConfig: &tls.Config{
ClientSessionCache: tls.NewLRUClientSessionCache(8192),
},
TLSHandshakeTimeout: 10 * time.Second,
MaxIdleConnsPerHost: 32, // TODO tune; we will likely be making lots of requests to same place
Proxy: http.ProxyFromEnvironment,
IdleConnTimeout: 90 * time.Second,
MaxIdleConns: 512,
ExpectContinueTimeout: 1 * time.Second,
},
}
// A drivers.ContainerTask should implement the Auther interface if it would
// like to use not-necessarily-public docker images for any or all task
// invocations.
@@ -97,122 +71,6 @@ func NewDocker(env *common.Environment, conf drivers.Config) *DockerDriver {
}
}
// CheckRegistry will return a sizer, which can be used to check the size of an
// image if the returned error is nil. If the error returned is nil, then
// authentication against the given credentials was successful, if the
// configuration does not specify a config.ServerAddress,
// https://hub.docker.com will be tried. CheckRegistry is a package level
// method since rkt can also use docker images, we may be interested in using
// rkt w/o a docker driver configured; also, we don't have to tote around a
// driver in any tasker that may be interested in registry information (2/2
// cases thus far).
func CheckRegistry(ctx context.Context, image string, config docker.AuthConfiguration) (Sizer, error) {
ctx, log := common.LoggerWithFields(ctx, logrus.Fields{"stack": "CheckRegistry"})
registry, repo, tag := drivers.ParseImage(image)
reg, err := registryForConfig(ctx, config, registry)
if err != nil {
return nil, err
}
mani, err := reg.Manifest(repo, tag)
if err != nil {
log.WithFields(logrus.Fields{"username": config.Username, "server": config.ServerAddress, "image": image}).WithError(err).Error("Credentials not authorized, trying next.")
//if !isAuthError(err) {
// // TODO we might retry this, since if this was the registry that was supposed to
// // auth the task will erroneously be set to 'error'
//}
return nil, err
}
return &sizer{mani, reg, repo}, nil
}
// Sizer returns size information. This interface is liable to contain more
// than a size at some point, change as needed.
type Sizer interface {
Size() (int64, error)
}
type sizer struct {
mani *manifest.SignedManifest
reg *registry.Registry
repo string
}
func (s *sizer) Size() (int64, error) {
var sum int64
for _, r := range s.mani.References() {
desc, err := s.reg.LayerMetadata(s.repo, r.Digest)
if err != nil {
return 0, err
}
sum += desc.Size
}
return sum, nil
}
func registryURL(ctx context.Context, addr string) (string, error) {
log := common.Logger(ctx)
if addr == "" || strings.Contains(addr, "hub.docker.com") || strings.Contains(addr, "index.docker.io") {
return hubURL, nil
}
url, err := url.Parse(addr)
if err != nil {
// TODO we could error the task out from this with a user error but since
// we have a list of auths to check, just return the error so as to be
// skipped... horrible api as it is
log.WithFields(logrus.Fields{"auth_addr": addr}).WithError(err).Error("error parsing server address url, skipping")
return "", err
}
if url.Scheme == "" {
url.Scheme = "https"
}
url.Path = strings.TrimSuffix(url.Path, "/")
url.Path = strings.TrimPrefix(url.Path, "/v2")
url.Path = strings.TrimPrefix(url.Path, "/v1") // just try this, if it fails it fails, not supporting v1
return url.String(), nil
}
func isAuthError(err error) bool {
// AARGH!
if urlError, ok := err.(*url.Error); ok {
if httpError, ok := urlError.Err.(*registry.HttpStatusError); ok {
if httpError.Response.StatusCode == 401 {
return true
}
}
}
return false
}
func registryForConfig(ctx context.Context, config docker.AuthConfiguration, reg string) (*registry.Registry, error) {
if reg == "" {
reg = config.ServerAddress
}
var err error
config.ServerAddress, err = registryURL(ctx, reg)
if err != nil {
return nil, err
}
// Use this instead of registry.New to avoid the Ping().
transport := registry.WrapTransport(registryClient.Transport, reg, config.Username, config.Password)
r := &registry.Registry{
URL: config.ServerAddress,
Client: &http.Client{
Transport: transport,
},
Logf: registry.Quiet,
}
return r, nil
}
func (drv *DockerDriver) Prepare(ctx context.Context, task drivers.ContainerTask) (drivers.Cookie, error) {
ctx, log := common.LoggerWithFields(ctx, logrus.Fields{"stack": "Prepare"})
var cmd []string
@@ -348,7 +206,7 @@ func (drv *DockerDriver) pullImage(ctx context.Context, task drivers.ContainerTa
}
var err error
config.ServerAddress, err = registryURL(ctx, config.ServerAddress)
config.ServerAddress, err = registryURL(config.ServerAddress)
if err != nil {
return err
}

View File

@@ -10,6 +10,7 @@ import (
"github.com/fnproject/fn/api/runner/common"
"github.com/fnproject/fn/api/runner/drivers"
"github.com/fsouza/go-dockerclient"
)
type taskDockerTest struct {
@@ -89,3 +90,21 @@ func TestRunnerDockerStdin(t *testing.T) {
t.Errorf("Test expected output to contain '%s', got '%s'", expect, got)
}
}
func TestRegistry(t *testing.T) {
image := "funcy/hello"
sizer, err := CheckRegistry(context.Background(), image, docker.AuthConfiguration{})
if err != nil {
t.Fatal("expected registry check not to fail, got:", err)
}
size, err := sizer.Size()
if err != nil {
t.Fatal("expected sizer not to fail, got:", err)
}
if size <= 0 {
t.Fatalf("expected positive size for image that exists, got size:", size)
}
}

View File

@@ -0,0 +1,208 @@
package docker
import (
"context"
"crypto/tls"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/docker/distribution"
"github.com/docker/distribution/manifest/schema1"
"github.com/docker/distribution/manifest/schema2"
"github.com/docker/distribution/reference"
registry "github.com/docker/distribution/registry/client"
"github.com/docker/distribution/registry/client/auth"
"github.com/docker/distribution/registry/client/auth/challenge"
"github.com/docker/distribution/registry/client/transport"
"github.com/fnproject/fn/api/runner/drivers"
docker "github.com/fsouza/go-dockerclient"
)
var (
// we need these imported so that they can be unmarshaled properly (yes, docker is mean)
_ = schema1.SchemaVersion
_ = schema2.SchemaVersion
registryTransport = &http.Transport{
Dial: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 2 * time.Minute,
}).Dial,
TLSClientConfig: &tls.Config{
ClientSessionCache: tls.NewLRUClientSessionCache(8192),
},
TLSHandshakeTimeout: 10 * time.Second,
MaxIdleConnsPerHost: 32, // TODO tune; we will likely be making lots of requests to same place
Proxy: http.ProxyFromEnvironment,
IdleConnTimeout: 90 * time.Second,
MaxIdleConns: 512,
ExpectContinueTimeout: 1 * time.Second,
}
)
const hubURL = "https://registry.hub.docker.com"
// CheckRegistry will return a sizer, which can be used to check the size of an
// image if the returned error is nil. If the error returned is nil, then
// authentication against the given credentials was successful, if the
// configuration or image do not specify a config.ServerAddress,
// https://hub.docker.com will be tried. CheckRegistry is a package level
// method since rkt can also use docker images, we may be interested in using
// rkt w/o a docker driver configured; also, we don't have to tote around a
// driver in any tasker that may be interested in registry information (2/2
// cases thus far).
func CheckRegistry(ctx context.Context, image string, config docker.AuthConfiguration) (Sizer, error) {
regURL, repoName, tag := drivers.ParseImage(image)
repoNamed, err := reference.WithName(repoName)
if err != nil {
return nil, err
}
if regURL == "" {
// image address overrides credential address
regURL = config.ServerAddress
}
regURL, err = registryURL(regURL)
if err != nil {
return nil, err
}
cm := challenge.NewSimpleManager()
creds := newCreds(config.Username, config.Password)
tran := transport.NewTransport(registryTransport,
auth.NewAuthorizer(cm,
auth.NewTokenHandler(registryTransport,
creds,
repoNamed.Name(),
"pull",
),
auth.NewBasicHandler(creds),
),
)
tran = &retryWrap{cm, tran}
repo, err := registry.NewRepository(ctx, repoNamed, regURL, tran)
if err != nil {
return nil, err
}
manis, err := repo.Manifests(ctx)
if err != nil {
return nil, err
}
mani, err := manis.Get(context.TODO(), "", distribution.WithTag(tag))
if err != nil {
return nil, err
}
blobs := repo.Blobs(ctx)
// most registries aren't that great, and won't provide a size for the top
// level digest, so we need to sum up all the layers. let this be optional
// with the sizer, since tag is good enough to check existence / auth.
return &sizer{mani, blobs}, nil
}
type retryWrap struct {
cm challenge.Manager
tran http.RoundTripper
}
func (d *retryWrap) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := d.tran.RoundTrip(req)
// if it's not authed, we have to add this to the challenge manager,
// and then retry it (it will get authed and the challenge then accepted).
// why the docker distribution transport doesn't do this for you is
// a real testament to what sadists those docker people are.
if resp.StatusCode == http.StatusUnauthorized {
pingPath := req.URL.Path
if v2Root := strings.Index(req.URL.Path, "/v2/"); v2Root != -1 {
pingPath = pingPath[:v2Root+4]
} else if v1Root := strings.Index(req.URL.Path, "/v1/"); v1Root != -1 {
pingPath = pingPath[:v1Root] + "/v2/"
}
// seriously, we have to rewrite this to the ping path,
// since looking up challenges strips to this path. YUP. GLHF.
ogURL := req.URL.Path
resp.Request.URL.Path = pingPath
d.cm.AddResponse(resp)
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
// put the original URL path back and try again now...
req.URL.Path = ogURL
resp, err = d.tran.RoundTrip(req)
}
return resp, err
}
func newCreds(user, pass string) *creds {
return &creds{m: make(map[string]string), user: user, pass: pass}
}
// implement auth.CredentialStore
type creds struct {
m map[string]string
user, pass string
}
func (c *creds) Basic(u *url.URL) (string, string) { return c.user, c.pass }
func (c *creds) RefreshToken(u *url.URL, service string) string { return c.m[service] }
func (c *creds) SetRefreshToken(u *url.URL, service, token string) { c.m[service] = token }
// Sizer returns size information. This interface is liable to contain more
// than a size at some point, change as needed.
type Sizer interface {
Size() (int64, error)
}
type sizer struct {
mani distribution.Manifest
blobs distribution.BlobStore
}
func (s *sizer) Size() (int64, error) {
var sum int64
for _, r := range s.mani.References() {
desc, err := s.blobs.Stat(context.TODO(), r.Digest)
if err != nil {
return 0, err
}
sum += desc.Size
}
return sum, nil
}
func registryURL(addr string) (string, error) {
if addr == "" || strings.Contains(addr, "hub.docker.com") || strings.Contains(addr, "index.docker.io") {
return hubURL, nil
}
uri, err := url.Parse(addr)
if err != nil {
return "", err
}
if uri.Scheme == "" {
uri.Scheme = "https"
}
uri.Path = strings.TrimSuffix(uri.Path, "/")
uri.Path = strings.TrimPrefix(uri.Path, "/v2")
uri.Path = strings.TrimPrefix(uri.Path, "/v1") // just try this, if it fails it fails, not supporting v1
return uri.String(), nil
}

196
glide.lock generated
View File

@@ -1,82 +1,48 @@
hash: a333d90d0cb65a059f0459e426d4a1a11cc4b7385beca641a11ebf2e67b2a371
updated: 2017-07-26T12:30:24.327734143-07:00
hash: b555054a6f86ac84f6104ad9efabdcd85966c8f6574e485be7337c3ee9f29aa0
updated: 2017-08-03T03:58:34.544868553-07:00
imports:
- name: code.cloudfoundry.org/bytefmt
version: f4415fafc5619dd75599a54a7c91fb3948ad58bd
- name: github.com/amir/raidman
version: 1ccc43bfb9c93cb401a4025e49c64ba71e5e668b
subpackages:
- proto
- name: github.com/apache/thrift
version: 0dd823580c78a79ae9696eb9b3650e400fff140f
version: 0eda909573cc7d8550c285035652e8b883ebc8f7
subpackages:
- lib/go/thrift
- name: github.com/asaskevich/govalidator
version: aa5cce4a76edb1a5acecab1870c17abbffb5419e
- name: github.com/aws/aws-sdk-go
version: 90dec2183a5f5458ee79cbaf4b8e9ab910bc81a6
subpackages:
- aws
- aws/awserr
- aws/awsutil
- aws/client
- aws/client/metadata
- aws/corehandlers
- aws/credentials
- aws/credentials/ec2rolecreds
- aws/defaults
- aws/ec2metadata
- aws/request
- aws/session
- aws/signer/v4
- private/endpoints
- private/protocol
- private/protocol/json/jsonutil
- private/protocol/jsonrpc
- private/protocol/query
- private/protocol/query/queryutil
- private/protocol/rest
- private/protocol/restjson
- private/protocol/restxml
- private/protocol/xml/xmlutil
- private/waiter
- service/cloudfront/sign
- service/lambda
- service/s3
- vendor/github.com/go-ini/ini
- vendor/github.com/jmespath/go-jmespath
version: 15028e809df8c71964e8efa6c11e81d5c0262302
- name: github.com/Azure/go-ansiterm
version: fa152c58bc15761d0200cb75fe958b89a9d4888e
subpackages:
- winterm
- name: github.com/boltdb/bolt
version: e9cf4fae01b5a8ff89d0ec6b32f0d9c9f79aefdd
version: 2f1ce7a837dcb8da3ec595b1dac9d0632f0f99e8
- name: github.com/cactus/go-statsd-client
version: 1139cdac1a56e404b5382e3a3503a2c587d2c0c3
version: ad551ee7f9f3465fb1ce1695899c612f7808a06a
subpackages:
- statsd
- name: github.com/ccirello/supervisor
version: 230eff6403e22b43f5fba7b28466dae4718934dd
- name: github.com/cenkalti/backoff
version: 5d150e7eec023ce7a124856b37c68e54b4050ac7
version: 61153c768f31ee5f130071d08fc82b85208528de
- name: github.com/coreos/go-semver
version: 1817cd4bea52af76542157eeabd74b057d1a199e
subpackages:
- semver
- name: github.com/davecgh/go-spew
version: 5215b55f46b2b919f50a1df0eaa5886afe4e3b3d
version: adab96458c51a58dc1783b3335dcce5461522e75
subpackages:
- spew
- name: github.com/dchest/siphash
version: 4ebf1de738443ea7f45f02dc394c4df1942a126d
- name: github.com/dghubble/go-twitter
version: d7141a7cba567120d53d0a136fce068864b43f8c
version: f74be7f0f20b142558537ca43852457f7c52e051
subpackages:
- twitter
- name: github.com/dghubble/oauth1
version: 7d51c10e15ca32917b32ce43f6e25840d6951db4
- name: github.com/dghubble/sling
version: bbfb8293bd33a6baad33d718aacf66ef73a29f30
version: 80ec33c6152a53edb5545864ca37567b506c4ca5
- name: github.com/dgrijalva/jwt-go
version: a539ee1a749a2b895533f979515ac7e6e0f5b650
- name: github.com/docker/cli
@@ -84,14 +50,22 @@ imports:
subpackages:
- cli/config/configfile
- name: github.com/docker/distribution
version: 99cb7c0946d2f5a38015443e515dc916295064d7
version: 5ccd03d28ae2b23a3b2863216bcb97e9f650f6d2
subpackages:
- context
- digest
- digestset
- manifest
- manifest/schema1
- manifest/schema2
- reference
- registry/api/errcode
- registry/api/v2
- registry/client
- registry/client/auth
- registry/client/auth/challenge
- registry/client/transport
- registry/storage/cache
- registry/storage/cache/memory
- uuid
- name: github.com/docker/docker
version: 89658bed64c2a8fe05a978e5b87dbec409d57a0f
@@ -122,7 +96,7 @@ imports:
- pkg/term
- pkg/term/windows
- name: github.com/docker/go-connections
version: e15c02316c12de00874640cd76311849de2aeed5
version: 3ede32e2033de7505e6500d6c868c2b9ed9f169d
subpackages:
- nat
- name: github.com/docker/go-units
@@ -140,7 +114,7 @@ imports:
- name: github.com/fsnotify/fsnotify
version: 4da3e2cfbabc9f751898f250b49f2439785783a1
- name: github.com/fsouza/go-dockerclient
version: c933ed18bef34ec2955de03de8ef9a3bb996e3df
version: 443bd55851743b8b85c5c3819777f43aaa8e275e
- name: github.com/funcy/functions_go
version: c540b7a8e1af8dad992a3b520175db85f8e53636
subpackages:
@@ -153,22 +127,18 @@ imports:
- client/version
- models
- name: github.com/garyburd/redigo
version: 95d11dba2d44531bdb8022752b98912baafae03a
version: 9e66b83d15a259978be267d0b61838c42c3904e3
subpackages:
- internal
- redis
- name: github.com/giantswarm/semver-bump
version: 7ec6ac8985c24dd50b4942f9a908d13cdfe70f23
subpackages:
- bump
- storage
- name: github.com/gin-contrib/sse
version: 22d885f9ecc78bf4ee5d72b937e4bbcdc58e8cae
- name: github.com/gin-gonic/gin
version: d5b353c5d5a560322e6d96121c814115562501f7
version: 81007d2ce0176f7a9ce52dd12e56edd7ef40e72c
subpackages:
- binding
- json
- render
- name: github.com/go-ini/ini
version: 3d73f4b845efdf9989fffd4b4e562727744a34ba
- name: github.com/go-logfmt/logfmt
version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5
- name: github.com/go-openapi/analysis
@@ -184,27 +154,25 @@ imports:
subpackages:
- fmts
- name: github.com/go-openapi/runtime
version: 2e9e988df6c290425033bacd425e008950c96be6
version: 73a94727f26953a79ffd70902d0f24977b6297d1
subpackages:
- client
- name: github.com/go-openapi/spec
version: e81a13315ac92ce3e73075856c5cd50301695405
version: 51363c5ae11ba8152bd9f35d17da715fbd1a1136
- name: github.com/go-openapi/strfmt
version: 93a31ef21ac23f317792fff78f9539219dd74619
- name: github.com/go-openapi/swag
version: f3f9494671f93fcff853e3c6e9e948b3eb71e590
- name: github.com/go-openapi/validate
version: 035dcd74f1f61e83debe1c22950dc53556e7e4b2
- name: github.com/go-resty/resty
version: 6d8c785a63e4b7505c88451cf9c5b452ccf2454c
version: 8a82927c942c94794a5cd8b8b50ce2f48a955c0c
- name: github.com/go-sql-driver/mysql
version: 56226343bd543f91a3930ed73ebdd03cfd633e85
version: 3955978caca48c1658a4bb7a9c6a0f084e326af3
- name: github.com/gogo/protobuf
version: 83c564581ed68caafcec877c710d7ac243232c93
version: eda389564aa83cc6949f47e0524c47cc2e4aaa23
subpackages:
- proto
- name: github.com/golang/protobuf
version: 2402d76f3d41f928c7902a765dfc872356dd3aad
version: 748d386b5c1ea99658fd69fe9f03991ce86a90c1
subpackages:
- proto
- name: github.com/golang/snappy
@@ -232,72 +200,46 @@ imports:
- json/parser
- json/scanner
- json/token
- name: github.com/heroku/docker-registry-client
version: 95467b6cacee2a06f112a3cf7e47a70fad6000cf
subpackages:
- registry
- name: github.com/iron-io/iron_go3
version: 830335d420db87fc84cbff7f0d1348a46b499946
subpackages:
- api
- config
- mq
- name: github.com/jmespath/go-jmespath
version: bd40a432e4c76585ef6b72d3fd96fb9b6dc7b68d
- name: github.com/jmoiron/jsonq
version: e874b168d07ecc7808bc950a17998a8aa3141d82
- name: github.com/jmoiron/sqlx
version: d9bd385d68c068f1fabb5057e3dedcbcbb039d0f
subpackages:
- reflectx
- name: github.com/juju/errgo
version: 08cceb5d0b5331634b9826762a8fd53b29b86ad8
subpackages:
- errors
- name: github.com/json-iterator/go
version: 1cfa233923ea407d7f0c70d7a7d835030678e788
- name: github.com/kr/logfmt
version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0
- name: github.com/lib/pq
version: 8837942c3e09574accbc5f150e2c5e057189cace
version: dd1fe2071026ce53f36a39112e645b4d4f5793a4
subpackages:
- oid
- name: github.com/magiconair/properties
version: 51463bfca2576e06c62a8504b5c0f06d61312647
version: be5ece7dd465ab0765a9682137865547526d1dfb
- name: github.com/mailru/easyjson
version: 44c0351a5bc860bcb2608d54aa03ea686c4e7b25
version: 2f5df55504ebc322e4d52d34df6a1f5b503bf26d
subpackages:
- buffer
- jlexer
- jwriter
- name: github.com/manucorporat/sse
version: ee05b128a739a0fb76c7ebd3ae4810c1de808d6d
- name: github.com/mattn/go-isatty
version: fc9e8d8ef48496124e79ae0df75490096eccf6fe
- name: github.com/mattn/go-sqlite3
version: 9cbb0970444f7ee9ccc65376394a504150b25de1
version: 6654e412c3c7eabb310d920cf73a2102dbf8c632
- name: github.com/Microsoft/go-winio
version: f533f7a102197536779ea3a8cb881d639e21ec5a
version: 78439966b38d69bf38227fbf57ac8a6fee70f69a
- name: github.com/mitchellh/mapstructure
version: d0303fe809921458f417bcf828397a65db30a7e4
- name: github.com/moby/moby
version: 72cda6a6c2f25854bea2d69168082684f2c9feca
subpackages:
- pkg/jsonmessage
- name: github.com/Nvveen/Gotty
version: cd527374f1e5bff4938207604a14f2e38a9cf512
- name: github.com/onsi/gomega
version: c893efa28eb45626cdaa76c9f653b62488858837
subpackages:
- format
- internal/assertion
- internal/asyncassertion
- internal/oraclematcher
- internal/testingtsupport
- matchers
- matchers/support/goraph/bipartitegraph
- matchers/support/goraph/edge
- matchers/support/goraph/node
- matchers/support/goraph/util
- types
- name: github.com/opencontainers/go-digest
version: 279bed98673dd5bef374d3b6e4b09e2af76183bf
- name: github.com/opencontainers/runc
version: ea35825a6350511ab93fe24e69c0723d6728616d
subpackages:
@@ -311,7 +253,7 @@ imports:
- ext
- log
- name: github.com/openzipkin/zipkin-go-opentracing
version: e6b1ad87c0787de9cb033d4f680fe69cd69e19fe
version: a3f24586d6771f7a52012fc17b05a3f781592173
subpackages:
- flag
- thrift/gen-go/scribe
@@ -319,11 +261,9 @@ imports:
- types
- wire
- name: github.com/patrickmn/go-cache
version: 7ac151875ffb48b9f3ccce9ea20f020b0c1596c8
- name: github.com/pelletier/go-buffruneio
version: c37440a7cf42ac63b919c752ca73a85067e05992
version: a3647f8e31d79543b2d0f0ae2fe5c379d72cedc0
- name: github.com/pelletier/go-toml
version: fe7536c3dee2596cdd23ee9976a17c22bdaae286
version: 69d355db5304c0f7f809a2edc054553e7142f016
- name: github.com/pierrec/lz4
version: 5a3d2245f97fc249850e7802e3c01fad02a1c316
- name: github.com/pierrec/xxHash
@@ -340,14 +280,14 @@ imports:
version: 1f30fe9094a513ce4c700b9a54458bbb0c96996c
- name: github.com/Shopify/sarama
version: 2fd980e23bdcbb8edeb78fc704de0c39a6567ffc
- name: github.com/sirupsen/logrus
version: ba1b36c82c5e05c4f912a88eab0dcd91a171688f
- name: github.com/Sirupsen/logrus
version: ba1b36c82c5e05c4f912a88eab0dcd91a171688f
repo: https://github.com/sirupsen/logrus.git
vcs: git
subpackages:
- hooks/syslog
- name: github.com/sirupsen/logrus
version: ba1b36c82c5e05c4f912a88eab0dcd91a171688f
- name: github.com/spf13/afero
version: 9be650865eab0c12963d8753212f4f9c66cdcf12
subpackages:
@@ -359,52 +299,36 @@ imports:
- name: github.com/spf13/pflag
version: 5644820622454e71517561946e3d94b9f9db6842
- name: github.com/spf13/viper
version: 0967fc9aceab2ce9da34061253ac10fb99bba5b2
- name: github.com/urfave/cli
version: 4b90d79a682b4bf685762c7452db20f2a676ecb2
version: 25b30aa063fc18e48662b86996252eabdcf2f0c7
- name: github.com/ugorji/go
version: 5efa3251c7f7d05e5d9704a69a984ec9f1386a40
subpackages:
- codec
- name: golang.org/x/crypto
version: c10c31b5e94b6f7a0283272dc2bb27163dcea24b
subpackages:
- bcrypt
- blowfish
- name: golang.org/x/net
version: f315505cf3349909cdf013ea56690da34e96a451
version: 4876518f9e71663000c348837735820161a42df7
subpackages:
- context
- context/ctxhttp
- html
- html/atom
- html/charset
- idna
- proxy
- publicsuffix
- name: golang.org/x/sys
version: 0b25a408a50076fbbcae6b7ac0ea5fbb0b085e79
version: d8f5ea21b9295e315e612b4bcf4bedea93454d4d
subpackages:
- unix
- windows
- name: golang.org/x/text
version: 210eee5cf7323015d097341bcf7166130d001cd8
version: 3bd178b88a8180be2df394a1fbb81313916f0e7b
subpackages:
- encoding
- encoding/charmap
- encoding/htmlindex
- encoding/internal
- encoding/internal/identifier
- encoding/japanese
- encoding/korean
- encoding/simplifiedchinese
- encoding/traditionalchinese
- encoding/unicode
- internal/tag
- internal/utf8internal
- language
- runes
- transform
- unicode/norm
- width
- name: gopkg.in/go-playground/validator.v8
version: c193cecd124b5cc722d7ee5538e945bdb3348435
version: 5f1438d3fca68893a817e4a66806cea46a9e4ebf
- name: gopkg.in/mgo.v2
version: 3f83fa5005286a7fe593b055f0d7771a7dce4655
subpackages:
@@ -413,9 +337,5 @@ imports:
- internal/sasl
- internal/scram
- name: gopkg.in/yaml.v2
version: cd8b52f8269e0feb286dfeef29f8fe4d5b397e0b
testImports:
- name: github.com/opencontainers/go-digest
version: 279bed98673dd5bef374d3b6e4b09e2af76183bf
- name: github.com/vrischmann/envconfig
version: 757beaaeac8d14bcc7ea3f71488d65cf45cf2eff
version: 25c4ec802a7d637f88d584ab26798e94ad14c13b
testImports: []

View File

@@ -6,6 +6,8 @@ import:
version: ^0.1.35
subpackages:
- models
- package: github.com/sirupsen/logrus
version: ^v0.11.5
- package: github.com/Sirupsen/logrus
repo: https://github.com/sirupsen/logrus.git
vcs: git
@@ -25,10 +27,11 @@ import:
- package: github.com/dghubble/oauth1
- package: github.com/dgrijalva/jwt-go
- package: github.com/docker/cli
version: dd585ad4fb8046aa66eb56babef0c63aa5c5244d
subpackages:
- cli/config/configfile
- package: github.com/docker/distribution
branch: master
version: 5ccd03d28ae2b23a3b2863216bcb97e9f650f6d2
- package: github.com/fsouza/go-dockerclient
- package: github.com/garyburd/redigo
subpackages:
@@ -47,9 +50,6 @@ import:
- package: github.com/go-openapi/validate
- package: github.com/go-sql-driver/mysql
- package: github.com/google/btree
- package: github.com/heroku/docker-registry-client
subpackages:
- registry
- package: github.com/iron-io/iron_go3
subpackages:
- config
@@ -70,8 +70,12 @@ import:
- package: github.com/mattn/go-sqlite3
- package: github.com/opentracing/opentracing-go
- package: github.com/openzipkin/zipkin-go-opentracing
testImport:
- package: github.com/opencontainers/go-digest
branch: master
version: 279bed98673dd5bef374d3b6e4b09e2af76183bf
- package: github.com/opencontainers/runc
version: ea35825a6350511ab93fe24e69c0723d6728616d
- package: github.com/Azure/go-ansiterm
version: fa152c58bc15761d0200cb75fe958b89a9d4888e
testImport:
- package: github.com/patrickmn/go-cache
branch: master

View File

@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,20 +0,0 @@
Copyright (c) 2015-Present CloudFoundry.org Foundation, Inc. All Rights Reserved.
This project contains software that is Copyright (c) 2013-2015 Pivotal Software, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This project may include a number of subcomponents with separate
copyright notices and license terms. Your use of these subcomponents
is subject to the terms and conditions of each subcomponent's license,
as noted in the LICENSE file.

View File

@@ -1,15 +0,0 @@
bytefmt
=======
**Note**: This repository should be imported as `code.cloudfoundry.org/bytefmt`.
Human-readable byte formatter.
Example:
```go
bytefmt.ByteSize(100.5*bytefmt.MEGABYTE) // returns "100.5M"
bytefmt.ByteSize(uint64(1024)) // returns "1K"
```
For documentation, please see http://godoc.org/code.cloudfoundry.org/bytefmt

View File

@@ -1,101 +0,0 @@
// Package bytefmt contains helper methods and constants for converting to and from a human-readable byte format.
//
// bytefmt.ByteSize(100.5*bytefmt.MEGABYTE) // "100.5M"
// bytefmt.ByteSize(uint64(1024)) // "1K"
//
package bytefmt
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
)
const (
BYTE = 1.0
KILOBYTE = 1024 * BYTE
MEGABYTE = 1024 * KILOBYTE
GIGABYTE = 1024 * MEGABYTE
TERABYTE = 1024 * GIGABYTE
)
var bytesPattern *regexp.Regexp = regexp.MustCompile(`(?i)^(-?\d+(?:\.\d+)?)([KMGT]B?|B)$`)
var invalidByteQuantityError = errors.New("Byte quantity must be a positive integer with a unit of measurement like M, MB, G, or GB")
// ByteSize returns a human-readable byte string of the form 10M, 12.5K, and so forth. The following units are available:
// T: Terabyte
// G: Gigabyte
// M: Megabyte
// K: Kilobyte
// B: Byte
// The unit that results in the smallest number greater than or equal to 1 is always chosen.
func ByteSize(bytes uint64) string {
unit := ""
value := float32(bytes)
switch {
case bytes >= TERABYTE:
unit = "T"
value = value / TERABYTE
case bytes >= GIGABYTE:
unit = "G"
value = value / GIGABYTE
case bytes >= MEGABYTE:
unit = "M"
value = value / MEGABYTE
case bytes >= KILOBYTE:
unit = "K"
value = value / KILOBYTE
case bytes >= BYTE:
unit = "B"
case bytes == 0:
return "0"
}
stringValue := fmt.Sprintf("%.1f", value)
stringValue = strings.TrimSuffix(stringValue, ".0")
return fmt.Sprintf("%s%s", stringValue, unit)
}
// ToMegabytes parses a string formatted by ByteSize as megabytes.
func ToMegabytes(s string) (uint64, error) {
bytes, err := ToBytes(s)
if err != nil {
return 0, err
}
return bytes / MEGABYTE, nil
}
// ToBytes parses a string formatted by ByteSize as bytes.
func ToBytes(s string) (uint64, error) {
parts := bytesPattern.FindStringSubmatch(strings.TrimSpace(s))
if len(parts) < 3 {
return 0, invalidByteQuantityError
}
value, err := strconv.ParseFloat(parts[1], 64)
if err != nil || value <= 0 {
return 0, invalidByteQuantityError
}
var bytes uint64
unit := strings.ToUpper(parts[2])
switch unit[:1] {
case "T":
bytes = uint64(value * TERABYTE)
case "G":
bytes = uint64(value * GIGABYTE)
case "M":
bytes = uint64(value * MEGABYTE)
case "K":
bytes = uint64(value * KILOBYTE)
case "B":
bytes = uint64(value * BYTE)
}
return bytes, nil
}

View File

@@ -1,225 +0,0 @@
package bytefmt_test
import (
. "code.cloudfoundry.org/bytefmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("bytefmt", func() {
Context("ByteSize", func() {
It("Prints in the largest possible unit", func() {
Expect(ByteSize(10 * TERABYTE)).To(Equal("10T"))
Expect(ByteSize(uint64(10.5 * TERABYTE))).To(Equal("10.5T"))
Expect(ByteSize(10 * GIGABYTE)).To(Equal("10G"))
Expect(ByteSize(uint64(10.5 * GIGABYTE))).To(Equal("10.5G"))
Expect(ByteSize(100 * MEGABYTE)).To(Equal("100M"))
Expect(ByteSize(uint64(100.5 * MEGABYTE))).To(Equal("100.5M"))
Expect(ByteSize(100 * KILOBYTE)).To(Equal("100K"))
Expect(ByteSize(uint64(100.5 * KILOBYTE))).To(Equal("100.5K"))
Expect(ByteSize(1)).To(Equal("1B"))
})
It("prints '0' for zero bytes", func() {
Expect(ByteSize(0)).To(Equal("0"))
})
})
Context("ToMegabytes", func() {
It("parses byte amounts with short units (e.g. M, G)", func() {
var (
megabytes uint64
err error
)
megabytes, err = ToMegabytes("5B")
Expect(megabytes).To(Equal(uint64(0)))
Expect(err).NotTo(HaveOccurred())
megabytes, err = ToMegabytes("5K")
Expect(megabytes).To(Equal(uint64(0)))
Expect(err).NotTo(HaveOccurred())
megabytes, err = ToMegabytes("5M")
Expect(megabytes).To(Equal(uint64(5)))
Expect(err).NotTo(HaveOccurred())
megabytes, err = ToMegabytes("5m")
Expect(megabytes).To(Equal(uint64(5)))
Expect(err).NotTo(HaveOccurred())
megabytes, err = ToMegabytes("2G")
Expect(megabytes).To(Equal(uint64(2 * 1024)))
Expect(err).NotTo(HaveOccurred())
megabytes, err = ToMegabytes("3T")
Expect(megabytes).To(Equal(uint64(3 * 1024 * 1024)))
Expect(err).NotTo(HaveOccurred())
})
It("parses byte amounts with long units (e.g MB, GB)", func() {
var (
megabytes uint64
err error
)
megabytes, err = ToMegabytes("5MB")
Expect(megabytes).To(Equal(uint64(5)))
Expect(err).NotTo(HaveOccurred())
megabytes, err = ToMegabytes("5mb")
Expect(megabytes).To(Equal(uint64(5)))
Expect(err).NotTo(HaveOccurred())
megabytes, err = ToMegabytes("2GB")
Expect(megabytes).To(Equal(uint64(2 * 1024)))
Expect(err).NotTo(HaveOccurred())
megabytes, err = ToMegabytes("3TB")
Expect(megabytes).To(Equal(uint64(3 * 1024 * 1024)))
Expect(err).NotTo(HaveOccurred())
})
It("returns an error when the unit is missing", func() {
_, err := ToMegabytes("5")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("unit of measurement"))
})
It("returns an error when the unit is unrecognized", func() {
_, err := ToMegabytes("5MBB")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("unit of measurement"))
_, err = ToMegabytes("5BB")
Expect(err).To(HaveOccurred())
})
It("allows whitespace before and after the value", func() {
megabytes, err := ToMegabytes("\t\n\r 5MB ")
Expect(megabytes).To(Equal(uint64(5)))
Expect(err).NotTo(HaveOccurred())
})
It("returns an error for negative values", func() {
_, err := ToMegabytes("-5MB")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("unit of measurement"))
})
It("returns an error for zero values", func() {
_, err := ToMegabytes("0TB")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("unit of measurement"))
})
})
Context("ToBytes", func() {
It("parses byte amounts with short units (e.g. M, G)", func() {
var (
bytes uint64
err error
)
bytes, err = ToBytes("5B")
Expect(bytes).To(Equal(uint64(5)))
Expect(err).NotTo(HaveOccurred())
bytes, err = ToBytes("5K")
Expect(bytes).To(Equal(uint64(5 * KILOBYTE)))
Expect(err).NotTo(HaveOccurred())
bytes, err = ToBytes("5M")
Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
Expect(err).NotTo(HaveOccurred())
bytes, err = ToBytes("5m")
Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
Expect(err).NotTo(HaveOccurred())
bytes, err = ToBytes("2G")
Expect(bytes).To(Equal(uint64(2 * GIGABYTE)))
Expect(err).NotTo(HaveOccurred())
bytes, err = ToBytes("3T")
Expect(bytes).To(Equal(uint64(3 * TERABYTE)))
Expect(err).NotTo(HaveOccurred())
})
It("parses byte amounts that are float (e.g. 5.3KB)", func() {
var (
bytes uint64
err error
)
bytes, err = ToBytes("13.5KB")
Expect(bytes).To(Equal(uint64(13824)))
Expect(err).NotTo(HaveOccurred())
bytes, err = ToBytes("4.5KB")
Expect(bytes).To(Equal(uint64(4608)))
Expect(err).NotTo(HaveOccurred())
})
It("parses byte amounts with long units (e.g MB, GB)", func() {
var (
bytes uint64
err error
)
bytes, err = ToBytes("5MB")
Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
Expect(err).NotTo(HaveOccurred())
bytes, err = ToBytes("5mb")
Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
Expect(err).NotTo(HaveOccurred())
bytes, err = ToBytes("2GB")
Expect(bytes).To(Equal(uint64(2 * GIGABYTE)))
Expect(err).NotTo(HaveOccurred())
bytes, err = ToBytes("3TB")
Expect(bytes).To(Equal(uint64(3 * TERABYTE)))
Expect(err).NotTo(HaveOccurred())
})
It("returns an error when the unit is missing", func() {
_, err := ToBytes("5")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("unit of measurement"))
})
It("returns an error when the unit is unrecognized", func() {
_, err := ToBytes("5MBB")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("unit of measurement"))
_, err = ToBytes("5BB")
Expect(err).To(HaveOccurred())
})
It("allows whitespace before and after the value", func() {
bytes, err := ToBytes("\t\n\r 5MB ")
Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
Expect(err).NotTo(HaveOccurred())
})
It("returns an error for negative values", func() {
_, err := ToBytes("-5MB")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("unit of measurement"))
})
It("returns an error for zero values", func() {
_, err := ToBytes("0TB")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("unit of measurement"))
})
})
})

View File

@@ -1,13 +0,0 @@
package bytefmt_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestFormatters(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Bytefmt Suite")
}

View File

@@ -1 +0,0 @@
package bytefmt // import "code.cloudfoundry.org/bytefmt"

View File

@@ -68,10 +68,20 @@ func NewBackupStreamReader(r io.Reader) *BackupStreamReader {
return &BackupStreamReader{r, 0}
}
// Next returns the next backup stream and prepares for calls to Write(). It skips the remainder of the current stream if
// Next returns the next backup stream and prepares for calls to Read(). It skips the remainder of the current stream if
// it was not completely read.
func (r *BackupStreamReader) Next() (*BackupHeader, error) {
if r.bytesLeft > 0 {
if s, ok := r.r.(io.Seeker); ok {
// Make sure Seek on io.SeekCurrent sometimes succeeds
// before trying the actual seek.
if _, err := s.Seek(0, io.SeekCurrent); err == nil {
if _, err = s.Seek(r.bytesLeft, io.SeekCurrent); err != nil {
return nil, err
}
r.bytesLeft = 0
}
}
if _, err := io.Copy(ioutil.Discard, r); err != nil {
return nil, err
}
@@ -220,7 +230,7 @@ type BackupFileWriter struct {
ctx uintptr
}
// NewBackupFileWrtier returns a new BackupFileWriter from a file handle. If includeSecurity is true,
// NewBackupFileWriter returns a new BackupFileWriter from a file handle. If includeSecurity is true,
// Write() will attempt to restore the security descriptor from the stream.
func NewBackupFileWriter(f *os.File, includeSecurity bool) *BackupFileWriter {
w := &BackupFileWriter{f, includeSecurity, 0}

View File

@@ -36,6 +36,7 @@ const (
hdrSecurityDescriptor = "sd"
hdrRawSecurityDescriptor = "rawsd"
hdrMountPoint = "mountpoint"
hdrEaPrefix = "xattr."
)
func writeZeroes(w io.Writer, count int64) error {
@@ -118,6 +119,21 @@ func BasicInfoHeader(name string, size int64, fileInfo *winio.FileBasicInfo) *ta
func WriteTarFileFromBackupStream(t *tar.Writer, r io.Reader, name string, size int64, fileInfo *winio.FileBasicInfo) error {
name = filepath.ToSlash(name)
hdr := BasicInfoHeader(name, size, fileInfo)
// If r can be seeked, then this function is two-pass: pass 1 collects the
// tar header data, and pass 2 copies the data stream. If r cannot be
// seeked, then some header data (in particular EAs) will be silently lost.
var (
restartPos int64
err error
)
sr, readTwice := r.(io.Seeker)
if readTwice {
if restartPos, err = sr.Seek(0, io.SeekCurrent); err != nil {
readTwice = false
}
}
br := winio.NewBackupStreamReader(r)
var dataHdr *winio.BackupHeader
for dataHdr == nil {
@@ -131,7 +147,9 @@ func WriteTarFileFromBackupStream(t *tar.Writer, r io.Reader, name string, size
switch bhdr.Id {
case winio.BackupData:
hdr.Mode |= c_ISREG
dataHdr = bhdr
if !readTwice {
dataHdr = bhdr
}
case winio.BackupSecurity:
sd, err := ioutil.ReadAll(br)
if err != nil {
@@ -151,18 +169,54 @@ func WriteTarFileFromBackupStream(t *tar.Writer, r io.Reader, name string, size
hdr.Winheaders[hdrMountPoint] = "1"
}
hdr.Linkname = rp.Target
case winio.BackupEaData, winio.BackupLink, winio.BackupPropertyData, winio.BackupObjectId, winio.BackupTxfsData:
case winio.BackupEaData:
eab, err := ioutil.ReadAll(br)
if err != nil {
return err
}
eas, err := winio.DecodeExtendedAttributes(eab)
if err != nil {
return err
}
for _, ea := range eas {
// Use base64 encoding for the binary value. Note that there
// is no way to encode the EA's flags, since their use doesn't
// make any sense for persisted EAs.
hdr.Winheaders[hdrEaPrefix+ea.Name] = base64.StdEncoding.EncodeToString(ea.Value)
}
case winio.BackupAlternateData, winio.BackupLink, winio.BackupPropertyData, winio.BackupObjectId, winio.BackupTxfsData:
// ignore these streams
default:
return fmt.Errorf("%s: unknown stream ID %d", name, bhdr.Id)
}
}
err := t.WriteHeader(hdr)
err = t.WriteHeader(hdr)
if err != nil {
return err
}
if readTwice {
// Get back to the data stream.
if _, err = sr.Seek(restartPos, io.SeekStart); err != nil {
return err
}
for dataHdr == nil {
bhdr, err := br.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
if bhdr.Id == winio.BackupData {
dataHdr = bhdr
}
}
}
if dataHdr != nil {
// A data stream was found. Copy the data.
if (dataHdr.Attributes & winio.StreamSparseAttributes) == 0 {
@@ -293,6 +347,38 @@ func WriteBackupStreamFromTarFile(w io.Writer, t *tar.Reader, hdr *tar.Header) (
return nil, err
}
}
var eas []winio.ExtendedAttribute
for k, v := range hdr.Winheaders {
if !strings.HasPrefix(k, hdrEaPrefix) {
continue
}
data, err := base64.StdEncoding.DecodeString(v)
if err != nil {
return nil, err
}
eas = append(eas, winio.ExtendedAttribute{
Name: k[len(hdrEaPrefix):],
Value: data,
})
}
if len(eas) != 0 {
eadata, err := winio.EncodeExtendedAttributes(eas)
if err != nil {
return nil, err
}
bhdr := winio.BackupHeader{
Id: winio.BackupEaData,
Size: int64(len(eadata)),
}
err = bw.WriteHeader(&bhdr)
if err != nil {
return nil, err
}
_, err = bw.Write(eadata)
if err != nil {
return nil, err
}
}
if hdr.Typeflag == tar.TypeSymlink {
_, isMountPoint := hdr.Winheaders[hdrMountPoint]
rp := winio.ReparsePoint{

View File

@@ -80,5 +80,5 @@ func TestRoundTrip(t *testing.T) {
t.Errorf("got %#v, expected %#v", *bi, *bi2)
}
ensurePresent(t, hdr.Winheaders, "fileattr", "sd")
ensurePresent(t, hdr.Winheaders, "fileattr", "rawsd")
}

137
vendor/github.com/Microsoft/go-winio/ea.go generated vendored Normal file
View File

@@ -0,0 +1,137 @@
package winio
import (
"bytes"
"encoding/binary"
"errors"
)
type fileFullEaInformation struct {
NextEntryOffset uint32
Flags uint8
NameLength uint8
ValueLength uint16
}
var (
fileFullEaInformationSize = binary.Size(&fileFullEaInformation{})
errInvalidEaBuffer = errors.New("invalid extended attribute buffer")
errEaNameTooLarge = errors.New("extended attribute name too large")
errEaValueTooLarge = errors.New("extended attribute value too large")
)
// ExtendedAttribute represents a single Windows EA.
type ExtendedAttribute struct {
Name string
Value []byte
Flags uint8
}
func parseEa(b []byte) (ea ExtendedAttribute, nb []byte, err error) {
var info fileFullEaInformation
err = binary.Read(bytes.NewReader(b), binary.LittleEndian, &info)
if err != nil {
err = errInvalidEaBuffer
return
}
nameOffset := fileFullEaInformationSize
nameLen := int(info.NameLength)
valueOffset := nameOffset + int(info.NameLength) + 1
valueLen := int(info.ValueLength)
nextOffset := int(info.NextEntryOffset)
if valueLen+valueOffset > len(b) || nextOffset < 0 || nextOffset > len(b) {
err = errInvalidEaBuffer
return
}
ea.Name = string(b[nameOffset : nameOffset+nameLen])
ea.Value = b[valueOffset : valueOffset+valueLen]
ea.Flags = info.Flags
if info.NextEntryOffset != 0 {
nb = b[info.NextEntryOffset:]
}
return
}
// DecodeExtendedAttributes decodes a list of EAs from a FILE_FULL_EA_INFORMATION
// buffer retrieved from BackupRead, ZwQueryEaFile, etc.
func DecodeExtendedAttributes(b []byte) (eas []ExtendedAttribute, err error) {
for len(b) != 0 {
ea, nb, err := parseEa(b)
if err != nil {
return nil, err
}
eas = append(eas, ea)
b = nb
}
return
}
func writeEa(buf *bytes.Buffer, ea *ExtendedAttribute, last bool) error {
if int(uint8(len(ea.Name))) != len(ea.Name) {
return errEaNameTooLarge
}
if int(uint16(len(ea.Value))) != len(ea.Value) {
return errEaValueTooLarge
}
entrySize := uint32(fileFullEaInformationSize + len(ea.Name) + 1 + len(ea.Value))
withPadding := (entrySize + 3) &^ 3
nextOffset := uint32(0)
if !last {
nextOffset = withPadding
}
info := fileFullEaInformation{
NextEntryOffset: nextOffset,
Flags: ea.Flags,
NameLength: uint8(len(ea.Name)),
ValueLength: uint16(len(ea.Value)),
}
err := binary.Write(buf, binary.LittleEndian, &info)
if err != nil {
return err
}
_, err = buf.Write([]byte(ea.Name))
if err != nil {
return err
}
err = buf.WriteByte(0)
if err != nil {
return err
}
_, err = buf.Write(ea.Value)
if err != nil {
return err
}
_, err = buf.Write([]byte{0, 0, 0}[0 : withPadding-entrySize])
if err != nil {
return err
}
return nil
}
// EncodeExtendedAttributes encodes a list of EAs into a FILE_FULL_EA_INFORMATION
// buffer for use with BackupWrite, ZwSetEaFile, etc.
func EncodeExtendedAttributes(eas []ExtendedAttribute) ([]byte, error) {
var buf bytes.Buffer
for i := range eas {
last := false
if i == len(eas)-1 {
last = true
}
err := writeEa(&buf, &eas[i], last)
if err != nil {
return nil, err
}
}
return buf.Bytes(), nil
}

89
vendor/github.com/Microsoft/go-winio/ea_test.go generated vendored Normal file
View File

@@ -0,0 +1,89 @@
package winio
import (
"io/ioutil"
"os"
"reflect"
"syscall"
"testing"
"unsafe"
)
var (
testEas = []ExtendedAttribute{
{Name: "foo", Value: []byte("bar")},
{Name: "fizz", Value: []byte("buzz")},
}
testEasEncoded = []byte{16, 0, 0, 0, 0, 3, 3, 0, 102, 111, 111, 0, 98, 97, 114, 0, 0, 0, 0, 0, 0, 4, 4, 0, 102, 105, 122, 122, 0, 98, 117, 122, 122, 0, 0, 0}
testEasNotPadded = testEasEncoded[0 : len(testEasEncoded)-3]
testEasTruncated = testEasEncoded[0:20]
)
func Test_RoundTripEas(t *testing.T) {
b, err := EncodeExtendedAttributes(testEas)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(testEasEncoded, b) {
t.Fatalf("encoded mismatch %v %v", testEasEncoded, b)
}
eas, err := DecodeExtendedAttributes(b)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(testEas, eas) {
t.Fatalf("mismatch %+v %+v", testEas, eas)
}
}
func Test_EasDontNeedPaddingAtEnd(t *testing.T) {
eas, err := DecodeExtendedAttributes(testEasNotPadded)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(testEas, eas) {
t.Fatalf("mismatch %+v %+v", testEas, eas)
}
}
func Test_TruncatedEasFailCorrectly(t *testing.T) {
_, err := DecodeExtendedAttributes(testEasTruncated)
if err == nil {
t.Fatal("expected error")
}
}
func Test_NilEasEncodeAndDecodeAsNil(t *testing.T) {
b, err := EncodeExtendedAttributes(nil)
if err != nil {
t.Fatal(err)
}
if len(b) != 0 {
t.Fatal("expected empty")
}
eas, err := DecodeExtendedAttributes(nil)
if err != nil {
t.Fatal(err)
}
if len(eas) != 0 {
t.Fatal("expected empty")
}
}
// Test_SetFileEa makes sure that the test buffer is actually parsable by NtSetEaFile.
func Test_SetFileEa(t *testing.T) {
f, err := ioutil.TempFile("", "winio")
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
defer f.Close()
ntdll := syscall.MustLoadDLL("ntdll.dll")
ntSetEaFile := ntdll.MustFindProc("NtSetEaFile")
var iosb [2]uintptr
r, _, _ := ntSetEaFile.Call(f.Fd(), uintptr(unsafe.Pointer(&iosb[0])), uintptr(unsafe.Pointer(&testEasEncoded[0])), uintptr(len(testEasEncoded)))
if r != 0 {
t.Fatalf("NtSetEaFile failed with %08x", r)
}
}

View File

@@ -23,6 +23,13 @@ type atomicBool int32
func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 }
func (b *atomicBool) setFalse() { atomic.StoreInt32((*int32)(b), 0) }
func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) }
func (b *atomicBool) swap(new bool) bool {
var newInt int32
if new {
newInt = 1
}
return atomic.SwapInt32((*int32)(b), newInt) == 1
}
const (
cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1
@@ -71,7 +78,8 @@ func initIo() {
type win32File struct {
handle syscall.Handle
wg sync.WaitGroup
closing bool
wgLock sync.RWMutex
closing atomicBool
readDeadline deadlineHandler
writeDeadline deadlineHandler
}
@@ -107,14 +115,18 @@ func MakeOpenFile(h syscall.Handle) (io.ReadWriteCloser, error) {
// closeHandle closes the resources associated with a Win32 handle
func (f *win32File) closeHandle() {
if !f.closing {
f.wgLock.Lock()
// Atomically set that we are closing, releasing the resources only once.
if !f.closing.swap(true) {
f.wgLock.Unlock()
// cancel all IO and wait for it to complete
f.closing = true
cancelIoEx(f.handle, nil)
f.wg.Wait()
// at this point, no new IO can start
syscall.Close(f.handle)
f.handle = 0
} else {
f.wgLock.Unlock()
}
}
@@ -127,10 +139,13 @@ func (f *win32File) Close() error {
// prepareIo prepares for a new IO operation.
// The caller must call f.wg.Done() when the IO is finished, prior to Close() returning.
func (f *win32File) prepareIo() (*ioOperation, error) {
f.wg.Add(1)
if f.closing {
f.wgLock.RLock()
if f.closing.isSet() {
f.wgLock.RUnlock()
return nil, ErrFileClosed
}
f.wg.Add(1)
f.wgLock.RUnlock()
c := &ioOperation{}
c.ch = make(chan ioResult)
return c, nil
@@ -159,7 +174,7 @@ func (f *win32File) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, er
return int(bytes), err
}
if f.closing {
if f.closing.isSet() {
cancelIoEx(f.handle, &c.o)
}
@@ -175,7 +190,7 @@ func (f *win32File) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, er
case r = <-c.ch:
err = r.err
if err == syscall.ERROR_OPERATION_ABORTED {
if f.closing {
if f.closing.isSet() {
err = ErrFileClosed
}
}

View File

@@ -265,9 +265,9 @@ func (l *win32PipeListener) listenerRoutine() {
if err == nil {
// Wait for the client to connect.
ch := make(chan error)
go func() {
go func(p *win32File) {
ch <- connectPipe(p)
}()
}(p)
select {
case err = <-ch:
if err != nil {

View File

@@ -367,11 +367,11 @@ func TestEchoWithMessaging(t *testing.T) {
OutputBufferSize: 65536,
}
l, err := ListenPipe(testPipeName, &c)
if err != nil {
t.Fatal(err)
}
defer l.Close()
listenerDone := make(chan bool)
clientDone := make(chan bool)
go func() {
@@ -380,6 +380,8 @@ func TestEchoWithMessaging(t *testing.T) {
if e != nil {
t.Fatal(e)
}
defer conn.Close()
time.Sleep(500 * time.Millisecond) // make *sure* we don't begin to read before eof signal is sent
io.Copy(conn, conn)
conn.(CloseWriter).CloseWrite()

View File

@@ -0,0 +1,901 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Hard-coding unicode mode for VHD library.
// +build ignore
/*
mksyscall_windows generates windows system call bodies
It parses all files specified on command line containing function
prototypes (like syscall_windows.go) and prints system call bodies
to standard output.
The prototypes are marked by lines beginning with "//sys" and read
like func declarations if //sys is replaced by func, but:
* The parameter lists must give a name for each argument. This
includes return parameters.
* The parameter lists must give a type for each argument:
the (x, y, z int) shorthand is not allowed.
* If the return parameter is an error number, it must be named err.
* If go func name needs to be different from it's winapi dll name,
the winapi name could be specified at the end, after "=" sign, like
//sys LoadLibrary(libname string) (handle uint32, err error) = LoadLibraryA
* Each function that returns err needs to supply a condition, that
return value of winapi will be tested against to detect failure.
This would set err to windows "last-error", otherwise it will be nil.
The value can be provided at end of //sys declaration, like
//sys LoadLibrary(libname string) (handle uint32, err error) [failretval==-1] = LoadLibraryA
and is [failretval==0] by default.
Usage:
mksyscall_windows [flags] [path ...]
The flags are:
-output
Specify output file name (outputs to console if blank).
-trace
Generate print statement after every syscall.
*/
package main
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"go/format"
"go/parser"
"go/token"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"text/template"
)
var (
filename = flag.String("output", "", "output file name (standard output if omitted)")
printTraceFlag = flag.Bool("trace", false, "generate print statement after every syscall")
systemDLL = flag.Bool("systemdll", true, "whether all DLLs should be loaded from the Windows system directory")
)
func trim(s string) string {
return strings.Trim(s, " \t")
}
var packageName string
func packagename() string {
return packageName
}
func syscalldot() string {
if packageName == "syscall" {
return ""
}
return "syscall."
}
// Param is function parameter
type Param struct {
Name string
Type string
fn *Fn
tmpVarIdx int
}
// tmpVar returns temp variable name that will be used to represent p during syscall.
func (p *Param) tmpVar() string {
if p.tmpVarIdx < 0 {
p.tmpVarIdx = p.fn.curTmpVarIdx
p.fn.curTmpVarIdx++
}
return fmt.Sprintf("_p%d", p.tmpVarIdx)
}
// BoolTmpVarCode returns source code for bool temp variable.
func (p *Param) BoolTmpVarCode() string {
const code = `var %s uint32
if %s {
%s = 1
} else {
%s = 0
}`
tmp := p.tmpVar()
return fmt.Sprintf(code, tmp, p.Name, tmp, tmp)
}
// SliceTmpVarCode returns source code for slice temp variable.
func (p *Param) SliceTmpVarCode() string {
const code = `var %s *%s
if len(%s) > 0 {
%s = &%s[0]
}`
tmp := p.tmpVar()
return fmt.Sprintf(code, tmp, p.Type[2:], p.Name, tmp, p.Name)
}
// StringTmpVarCode returns source code for string temp variable.
func (p *Param) StringTmpVarCode() string {
errvar := p.fn.Rets.ErrorVarName()
if errvar == "" {
errvar = "_"
}
tmp := p.tmpVar()
const code = `var %s %s
%s, %s = %s(%s)`
s := fmt.Sprintf(code, tmp, p.fn.StrconvType(), tmp, errvar, p.fn.StrconvFunc(), p.Name)
if errvar == "-" {
return s
}
const morecode = `
if %s != nil {
return
}`
return s + fmt.Sprintf(morecode, errvar)
}
// TmpVarCode returns source code for temp variable.
func (p *Param) TmpVarCode() string {
switch {
case p.Type == "bool":
return p.BoolTmpVarCode()
case strings.HasPrefix(p.Type, "[]"):
return p.SliceTmpVarCode()
default:
return ""
}
}
// TmpVarHelperCode returns source code for helper's temp variable.
func (p *Param) TmpVarHelperCode() string {
if p.Type != "string" {
return ""
}
return p.StringTmpVarCode()
}
// SyscallArgList returns source code fragments representing p parameter
// in syscall. Slices are translated into 2 syscall parameters: pointer to
// the first element and length.
func (p *Param) SyscallArgList() []string {
t := p.HelperType()
var s string
switch {
case t[0] == '*':
s = fmt.Sprintf("unsafe.Pointer(%s)", p.Name)
case t == "bool":
s = p.tmpVar()
case strings.HasPrefix(t, "[]"):
return []string{
fmt.Sprintf("uintptr(unsafe.Pointer(%s))", p.tmpVar()),
fmt.Sprintf("uintptr(len(%s))", p.Name),
}
default:
s = p.Name
}
return []string{fmt.Sprintf("uintptr(%s)", s)}
}
// IsError determines if p parameter is used to return error.
func (p *Param) IsError() bool {
return p.Name == "err" && p.Type == "error"
}
// HelperType returns type of parameter p used in helper function.
func (p *Param) HelperType() string {
if p.Type == "string" {
return p.fn.StrconvType()
}
return p.Type
}
// join concatenates parameters ps into a string with sep separator.
// Each parameter is converted into string by applying fn to it
// before conversion.
func join(ps []*Param, fn func(*Param) string, sep string) string {
if len(ps) == 0 {
return ""
}
a := make([]string, 0)
for _, p := range ps {
a = append(a, fn(p))
}
return strings.Join(a, sep)
}
// Rets describes function return parameters.
type Rets struct {
Name string
Type string
ReturnsError bool
FailCond string
}
// ErrorVarName returns error variable name for r.
func (r *Rets) ErrorVarName() string {
if r.ReturnsError {
return "err"
}
if r.Type == "error" {
return r.Name
}
return ""
}
// ToParams converts r into slice of *Param.
func (r *Rets) ToParams() []*Param {
ps := make([]*Param, 0)
if len(r.Name) > 0 {
ps = append(ps, &Param{Name: r.Name, Type: r.Type})
}
if r.ReturnsError {
ps = append(ps, &Param{Name: "err", Type: "error"})
}
return ps
}
// List returns source code of syscall return parameters.
func (r *Rets) List() string {
s := join(r.ToParams(), func(p *Param) string { return p.Name + " " + p.Type }, ", ")
if len(s) > 0 {
s = "(" + s + ")"
}
return s
}
// PrintList returns source code of trace printing part correspondent
// to syscall return values.
func (r *Rets) PrintList() string {
return join(r.ToParams(), func(p *Param) string { return fmt.Sprintf(`"%s=", %s, `, p.Name, p.Name) }, `", ", `)
}
// SetReturnValuesCode returns source code that accepts syscall return values.
func (r *Rets) SetReturnValuesCode() string {
if r.Name == "" && !r.ReturnsError {
return ""
}
retvar := "r0"
if r.Name == "" {
retvar = "r1"
}
errvar := "_"
if r.ReturnsError {
errvar = "e1"
}
return fmt.Sprintf("%s, _, %s := ", retvar, errvar)
}
func (r *Rets) useLongHandleErrorCode(retvar string) string {
const code = `if %s {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = %sEINVAL
}
}`
cond := retvar + " == 0"
if r.FailCond != "" {
cond = strings.Replace(r.FailCond, "failretval", retvar, 1)
}
return fmt.Sprintf(code, cond, syscalldot())
}
// SetErrorCode returns source code that sets return parameters.
func (r *Rets) SetErrorCode() string {
const code = `if r0 != 0 {
%s = %sErrno(r0)
}`
if r.Name == "" && !r.ReturnsError {
return ""
}
if r.Name == "" {
return r.useLongHandleErrorCode("r1")
}
if r.Type == "error" {
return fmt.Sprintf(code, r.Name, syscalldot())
}
s := ""
switch {
case r.Type[0] == '*':
s = fmt.Sprintf("%s = (%s)(unsafe.Pointer(r0))", r.Name, r.Type)
case r.Type == "bool":
s = fmt.Sprintf("%s = r0 != 0", r.Name)
default:
s = fmt.Sprintf("%s = %s(r0)", r.Name, r.Type)
}
if !r.ReturnsError {
return s
}
return s + "\n\t" + r.useLongHandleErrorCode(r.Name)
}
// Fn describes syscall function.
type Fn struct {
Name string
Params []*Param
Rets *Rets
PrintTrace bool
dllname string
dllfuncname string
src string
// TODO: get rid of this field and just use parameter index instead
curTmpVarIdx int // insure tmp variables have uniq names
}
// extractParams parses s to extract function parameters.
func extractParams(s string, f *Fn) ([]*Param, error) {
s = trim(s)
if s == "" {
return nil, nil
}
a := strings.Split(s, ",")
ps := make([]*Param, len(a))
for i := range ps {
s2 := trim(a[i])
b := strings.Split(s2, " ")
if len(b) != 2 {
b = strings.Split(s2, "\t")
if len(b) != 2 {
return nil, errors.New("Could not extract function parameter from \"" + s2 + "\"")
}
}
ps[i] = &Param{
Name: trim(b[0]),
Type: trim(b[1]),
fn: f,
tmpVarIdx: -1,
}
}
return ps, nil
}
// extractSection extracts text out of string s starting after start
// and ending just before end. found return value will indicate success,
// and prefix, body and suffix will contain correspondent parts of string s.
func extractSection(s string, start, end rune) (prefix, body, suffix string, found bool) {
s = trim(s)
if strings.HasPrefix(s, string(start)) {
// no prefix
body = s[1:]
} else {
a := strings.SplitN(s, string(start), 2)
if len(a) != 2 {
return "", "", s, false
}
prefix = a[0]
body = a[1]
}
a := strings.SplitN(body, string(end), 2)
if len(a) != 2 {
return "", "", "", false
}
return prefix, a[0], a[1], true
}
// newFn parses string s and return created function Fn.
func newFn(s string) (*Fn, error) {
s = trim(s)
f := &Fn{
Rets: &Rets{},
src: s,
PrintTrace: *printTraceFlag,
}
// function name and args
prefix, body, s, found := extractSection(s, '(', ')')
if !found || prefix == "" {
return nil, errors.New("Could not extract function name and parameters from \"" + f.src + "\"")
}
f.Name = prefix
var err error
f.Params, err = extractParams(body, f)
if err != nil {
return nil, err
}
// return values
_, body, s, found = extractSection(s, '(', ')')
if found {
r, err := extractParams(body, f)
if err != nil {
return nil, err
}
switch len(r) {
case 0:
case 1:
if r[0].IsError() {
f.Rets.ReturnsError = true
} else {
f.Rets.Name = r[0].Name
f.Rets.Type = r[0].Type
}
case 2:
if !r[1].IsError() {
return nil, errors.New("Only last windows error is allowed as second return value in \"" + f.src + "\"")
}
f.Rets.ReturnsError = true
f.Rets.Name = r[0].Name
f.Rets.Type = r[0].Type
default:
return nil, errors.New("Too many return values in \"" + f.src + "\"")
}
}
// fail condition
_, body, s, found = extractSection(s, '[', ']')
if found {
f.Rets.FailCond = body
}
// dll and dll function names
s = trim(s)
if s == "" {
return f, nil
}
if !strings.HasPrefix(s, "=") {
return nil, errors.New("Could not extract dll name from \"" + f.src + "\"")
}
s = trim(s[1:])
a := strings.Split(s, ".")
switch len(a) {
case 1:
f.dllfuncname = a[0]
case 2:
f.dllname = a[0]
f.dllfuncname = a[1]
default:
return nil, errors.New("Could not extract dll name from \"" + f.src + "\"")
}
return f, nil
}
// DLLName returns DLL name for function f.
func (f *Fn) DLLName() string {
if f.dllname == "" {
return "kernel32"
}
return f.dllname
}
// DLLName returns DLL function name for function f.
func (f *Fn) DLLFuncName() string {
if f.dllfuncname == "" {
return f.Name
}
return f.dllfuncname
}
// ParamList returns source code for function f parameters.
func (f *Fn) ParamList() string {
return join(f.Params, func(p *Param) string { return p.Name + " " + p.Type }, ", ")
}
// HelperParamList returns source code for helper function f parameters.
func (f *Fn) HelperParamList() string {
return join(f.Params, func(p *Param) string { return p.Name + " " + p.HelperType() }, ", ")
}
// ParamPrintList returns source code of trace printing part correspondent
// to syscall input parameters.
func (f *Fn) ParamPrintList() string {
return join(f.Params, func(p *Param) string { return fmt.Sprintf(`"%s=", %s, `, p.Name, p.Name) }, `", ", `)
}
// ParamCount return number of syscall parameters for function f.
func (f *Fn) ParamCount() int {
n := 0
for _, p := range f.Params {
n += len(p.SyscallArgList())
}
return n
}
// SyscallParamCount determines which version of Syscall/Syscall6/Syscall9/...
// to use. It returns parameter count for correspondent SyscallX function.
func (f *Fn) SyscallParamCount() int {
n := f.ParamCount()
switch {
case n <= 3:
return 3
case n <= 6:
return 6
case n <= 9:
return 9
case n <= 12:
return 12
case n <= 15:
return 15
default:
panic("too many arguments to system call")
}
}
// Syscall determines which SyscallX function to use for function f.
func (f *Fn) Syscall() string {
c := f.SyscallParamCount()
if c == 3 {
return syscalldot() + "Syscall"
}
return syscalldot() + "Syscall" + strconv.Itoa(c)
}
// SyscallParamList returns source code for SyscallX parameters for function f.
func (f *Fn) SyscallParamList() string {
a := make([]string, 0)
for _, p := range f.Params {
a = append(a, p.SyscallArgList()...)
}
for len(a) < f.SyscallParamCount() {
a = append(a, "0")
}
return strings.Join(a, ", ")
}
// HelperCallParamList returns source code of call into function f helper.
func (f *Fn) HelperCallParamList() string {
a := make([]string, 0, len(f.Params))
for _, p := range f.Params {
s := p.Name
if p.Type == "string" {
s = p.tmpVar()
}
a = append(a, s)
}
return strings.Join(a, ", ")
}
// IsUTF16 is true, if f is W (utf16) function. It is false
// for all A (ascii) functions.
func (f *Fn) IsUTF16() bool {
return true
}
// StrconvFunc returns name of Go string to OS string function for f.
func (f *Fn) StrconvFunc() string {
if f.IsUTF16() {
return syscalldot() + "UTF16PtrFromString"
}
return syscalldot() + "BytePtrFromString"
}
// StrconvType returns Go type name used for OS string for f.
func (f *Fn) StrconvType() string {
if f.IsUTF16() {
return "*uint16"
}
return "*byte"
}
// HasStringParam is true, if f has at least one string parameter.
// Otherwise it is false.
func (f *Fn) HasStringParam() bool {
for _, p := range f.Params {
if p.Type == "string" {
return true
}
}
return false
}
// HelperName returns name of function f helper.
func (f *Fn) HelperName() string {
if !f.HasStringParam() {
return f.Name
}
return "_" + f.Name
}
// Source files and functions.
type Source struct {
Funcs []*Fn
Files []string
StdLibImports []string
ExternalImports []string
}
func (src *Source) Import(pkg string) {
src.StdLibImports = append(src.StdLibImports, pkg)
sort.Strings(src.StdLibImports)
}
func (src *Source) ExternalImport(pkg string) {
src.ExternalImports = append(src.ExternalImports, pkg)
sort.Strings(src.ExternalImports)
}
// ParseFiles parses files listed in fs and extracts all syscall
// functions listed in sys comments. It returns source files
// and functions collection *Source if successful.
func ParseFiles(fs []string) (*Source, error) {
src := &Source{
Funcs: make([]*Fn, 0),
Files: make([]string, 0),
StdLibImports: []string{
"unsafe",
},
ExternalImports: make([]string, 0),
}
for _, file := range fs {
if err := src.ParseFile(file); err != nil {
return nil, err
}
}
return src, nil
}
// DLLs return dll names for a source set src.
func (src *Source) DLLs() []string {
uniq := make(map[string]bool)
r := make([]string, 0)
for _, f := range src.Funcs {
name := f.DLLName()
if _, found := uniq[name]; !found {
uniq[name] = true
r = append(r, name)
}
}
return r
}
// ParseFile adds additional file path to a source set src.
func (src *Source) ParseFile(path string) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
s := bufio.NewScanner(file)
for s.Scan() {
t := trim(s.Text())
if len(t) < 7 {
continue
}
if !strings.HasPrefix(t, "//sys") {
continue
}
t = t[5:]
if !(t[0] == ' ' || t[0] == '\t') {
continue
}
f, err := newFn(t[1:])
if err != nil {
return err
}
src.Funcs = append(src.Funcs, f)
}
if err := s.Err(); err != nil {
return err
}
src.Files = append(src.Files, path)
// get package name
fset := token.NewFileSet()
_, err = file.Seek(0, 0)
if err != nil {
return err
}
pkg, err := parser.ParseFile(fset, "", file, parser.PackageClauseOnly)
if err != nil {
return err
}
packageName = pkg.Name.Name
return nil
}
// IsStdRepo returns true if src is part of standard library.
func (src *Source) IsStdRepo() (bool, error) {
if len(src.Files) == 0 {
return false, errors.New("no input files provided")
}
abspath, err := filepath.Abs(src.Files[0])
if err != nil {
return false, err
}
goroot := runtime.GOROOT()
if runtime.GOOS == "windows" {
abspath = strings.ToLower(abspath)
goroot = strings.ToLower(goroot)
}
sep := string(os.PathSeparator)
if !strings.HasSuffix(goroot, sep) {
goroot += sep
}
return strings.HasPrefix(abspath, goroot), nil
}
// Generate output source file from a source set src.
func (src *Source) Generate(w io.Writer) error {
const (
pkgStd = iota // any package in std library
pkgXSysWindows // x/sys/windows package
pkgOther
)
isStdRepo, err := src.IsStdRepo()
if err != nil {
return err
}
var pkgtype int
switch {
case isStdRepo:
pkgtype = pkgStd
case packageName == "windows":
// TODO: this needs better logic than just using package name
pkgtype = pkgXSysWindows
default:
pkgtype = pkgOther
}
if *systemDLL {
switch pkgtype {
case pkgStd:
src.Import("internal/syscall/windows/sysdll")
case pkgXSysWindows:
default:
src.ExternalImport("golang.org/x/sys/windows")
}
}
if packageName != "syscall" {
src.Import("syscall")
}
funcMap := template.FuncMap{
"packagename": packagename,
"syscalldot": syscalldot,
"newlazydll": func(dll string) string {
arg := "\"" + dll + ".dll\""
if !*systemDLL {
return syscalldot() + "NewLazyDLL(" + arg + ")"
}
switch pkgtype {
case pkgStd:
return syscalldot() + "NewLazyDLL(sysdll.Add(" + arg + "))"
case pkgXSysWindows:
return "NewLazySystemDLL(" + arg + ")"
default:
return "windows.NewLazySystemDLL(" + arg + ")"
}
},
}
t := template.Must(template.New("main").Funcs(funcMap).Parse(srcTemplate))
err = t.Execute(w, src)
if err != nil {
return errors.New("Failed to execute template: " + err.Error())
}
return nil
}
func usage() {
fmt.Fprintf(os.Stderr, "usage: mksyscall_windows [flags] [path ...]\n")
flag.PrintDefaults()
os.Exit(1)
}
func main() {
flag.Usage = usage
flag.Parse()
if len(flag.Args()) <= 0 {
fmt.Fprintf(os.Stderr, "no files to parse provided\n")
usage()
}
src, err := ParseFiles(flag.Args())
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
if err := src.Generate(&buf); err != nil {
log.Fatal(err)
}
data, err := format.Source(buf.Bytes())
if err != nil {
log.Fatal(err)
}
if *filename == "" {
_, err = os.Stdout.Write(data)
} else {
err = ioutil.WriteFile(*filename, data, 0644)
}
if err != nil {
log.Fatal(err)
}
}
// TODO: use println instead to print in the following template
const srcTemplate = `
{{define "main"}}// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT
package {{packagename}}
import (
{{range .StdLibImports}}"{{.}}"
{{end}}
{{range .ExternalImports}}"{{.}}"
{{end}}
)
var _ unsafe.Pointer
// Do the interface allocations only once for common
// Errno values.
const (
errnoERROR_IO_PENDING = 997
)
var (
errERROR_IO_PENDING error = {{syscalldot}}Errno(errnoERROR_IO_PENDING)
)
// errnoErr returns common boxed Errno values, to prevent
// allocations at runtime.
func errnoErr(e {{syscalldot}}Errno) error {
switch e {
case 0:
return nil
case errnoERROR_IO_PENDING:
return errERROR_IO_PENDING
}
// TODO: add more here, after collecting data on the common
// error values see on Windows. (perhaps when running
// all.bat?)
return e
}
var (
{{template "dlls" .}}
{{template "funcnames" .}})
{{range .Funcs}}{{if .HasStringParam}}{{template "helperbody" .}}{{end}}{{template "funcbody" .}}{{end}}
{{end}}
{{/* help functions */}}
{{define "dlls"}}{{range .DLLs}} mod{{.}} = {{newlazydll .}}
{{end}}{{end}}
{{define "funcnames"}}{{range .Funcs}} proc{{.DLLFuncName}} = mod{{.DLLName}}.NewProc("{{.DLLFuncName}}")
{{end}}{{end}}
{{define "helperbody"}}
func {{.Name}}({{.ParamList}}) {{template "results" .}}{
{{template "helpertmpvars" .}} return {{.HelperName}}({{.HelperCallParamList}})
}
{{end}}
{{define "funcbody"}}
func {{.HelperName}}({{.HelperParamList}}) {{template "results" .}}{
{{template "tmpvars" .}} {{template "syscall" .}}
{{template "seterror" .}}{{template "printtrace" .}} return
}
{{end}}
{{define "helpertmpvars"}}{{range .Params}}{{if .TmpVarHelperCode}} {{.TmpVarHelperCode}}
{{end}}{{end}}{{end}}
{{define "tmpvars"}}{{range .Params}}{{if .TmpVarCode}} {{.TmpVarCode}}
{{end}}{{end}}{{end}}
{{define "results"}}{{if .Rets.List}}{{.Rets.List}} {{end}}{{end}}
{{define "syscall"}}{{.Rets.SetReturnValuesCode}}{{.Syscall}}(proc{{.DLLFuncName}}.Addr(), {{.ParamCount}}, {{.SyscallParamList}}){{end}}
{{define "seterror"}}{{if .Rets.SetErrorCode}} {{.Rets.SetErrorCode}}
{{end}}{{end}}
{{define "printtrace"}}{{if .PrintTrace}} print("SYSCALL: {{.Name}}(", {{.ParamPrintList}}") (", {{.Rets.PrintList}}")\n")
{{end}}{{end}}
`

82
vendor/github.com/Microsoft/go-winio/vhd/vhd.go generated vendored Normal file
View File

@@ -0,0 +1,82 @@
// +build windows
package vhd
import "syscall"
//go:generate go run mksyscall_windows.go -output zvhd.go vhd.go
//sys createVirtualDisk(virtualStorageType *virtualStorageType, path string, virtualDiskAccessMask uint32, securityDescriptor *uintptr, flags uint32, providerSpecificFlags uint32, parameters *createVirtualDiskParameters, o *syscall.Overlapped, handle *syscall.Handle) (err error) [failretval != 0] = VirtDisk.CreateVirtualDisk
type virtualStorageType struct {
DeviceID uint32
VendorID [16]byte
}
const virtualDiskAccessNONE uint32 = 0
const virtualDiskAccessATTACHRO uint32 = 65536
const virtualDiskAccessATTACHRW uint32 = 131072
const virtualDiskAccessDETACH uint32 = 262144
const virtualDiskAccessGETINFO uint32 = 524288
const virtualDiskAccessCREATE uint32 = 1048576
const virtualDiskAccessMETAOPS uint32 = 2097152
const virtualDiskAccessREAD uint32 = 851968
const virtualDiskAccessALL uint32 = 4128768
const virtualDiskAccessWRITABLE uint32 = 3276800
const createVirtualDiskFlagNone uint32 = 0
const createVirtualDiskFlagFullPhysicalAllocation uint32 = 1
const createVirtualDiskFlagPreventWritesToSourceDisk uint32 = 2
const createVirtualDiskFlagDoNotCopyMetadataFromParent uint32 = 4
type version2 struct {
UniqueID [16]byte // GUID
MaximumSize uint64
BlockSizeInBytes uint32
SectorSizeInBytes uint32
ParentPath *uint16 // string
SourcePath *uint16 // string
OpenFlags uint32
ParentVirtualStorageType virtualStorageType
SourceVirtualStorageType virtualStorageType
ResiliencyGUID [16]byte // GUID
}
type createVirtualDiskParameters struct {
Version uint32 // Must always be set to 2
Version2 version2
}
// CreateVhdx will create a simple vhdx file at the given path using default values.
func CreateVhdx(path string, maxSizeInGb, blockSizeInMb uint32) error {
var defaultType virtualStorageType
parameters := createVirtualDiskParameters{
Version: 2,
Version2: version2{
MaximumSize: uint64(maxSizeInGb) * 1024 * 1024 * 1024,
BlockSizeInBytes: blockSizeInMb * 1024 * 1024,
},
}
var handle syscall.Handle
if err := createVirtualDisk(
&defaultType,
path,
virtualDiskAccessNONE,
nil,
createVirtualDiskFlagNone,
0,
&parameters,
nil,
&handle); err != nil {
return err
}
if err := syscall.CloseHandle(handle); err != nil {
return err
}
return nil
}

64
vendor/github.com/Microsoft/go-winio/vhd/zvhd.go generated vendored Normal file
View File

@@ -0,0 +1,64 @@
// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT
package vhd
import (
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
var _ unsafe.Pointer
// Do the interface allocations only once for common
// Errno values.
const (
errnoERROR_IO_PENDING = 997
)
var (
errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
)
// errnoErr returns common boxed Errno values, to prevent
// allocations at runtime.
func errnoErr(e syscall.Errno) error {
switch e {
case 0:
return nil
case errnoERROR_IO_PENDING:
return errERROR_IO_PENDING
}
// TODO: add more here, after collecting data on the common
// error values see on Windows. (perhaps when running
// all.bat?)
return e
}
var (
modVirtDisk = windows.NewLazySystemDLL("VirtDisk.dll")
procCreateVirtualDisk = modVirtDisk.NewProc("CreateVirtualDisk")
)
func createVirtualDisk(virtualStorageType *virtualStorageType, path string, virtualDiskAccessMask uint32, securityDescriptor *uintptr, flags uint32, providerSpecificFlags uint32, parameters *createVirtualDiskParameters, o *syscall.Overlapped, handle *syscall.Handle) (err error) {
var _p0 *uint16
_p0, err = syscall.UTF16PtrFromString(path)
if err != nil {
return
}
return _createVirtualDisk(virtualStorageType, _p0, virtualDiskAccessMask, securityDescriptor, flags, providerSpecificFlags, parameters, o, handle)
}
func _createVirtualDisk(virtualStorageType *virtualStorageType, path *uint16, virtualDiskAccessMask uint32, securityDescriptor *uintptr, flags uint32, providerSpecificFlags uint32, parameters *createVirtualDiskParameters, o *syscall.Overlapped, handle *syscall.Handle) (err error) {
r1, _, e1 := syscall.Syscall9(procCreateVirtualDisk.Addr(), 9, uintptr(unsafe.Pointer(virtualStorageType)), uintptr(unsafe.Pointer(path)), uintptr(virtualDiskAccessMask), uintptr(unsafe.Pointer(securityDescriptor)), uintptr(flags), uintptr(providerSpecificFlags), uintptr(unsafe.Pointer(parameters)), uintptr(unsafe.Pointer(o)), uintptr(unsafe.Pointer(handle)))
if r1 != 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}

View File

@@ -50,7 +50,7 @@ RUN buildDeps=" \
/thrift \
&& cmake --build . --config Release \
&& make install \
&& curl -k -sSL "https://storage.googleapis.com/golang/go1.8.3.linux-amd64.tar.gz" -o /tmp/go.tar.gz \
&& curl -k -sSL "https://storage.googleapis.com/golang/go1.5.2.linux-amd64.tar.gz" -o /tmp/go.tar.gz \
&& tar xzf /tmp/go.tar.gz -C /tmp \
&& cp /tmp/go/bin/gofmt /usr/bin/gofmt \
&& apt-get purge -y --auto-remove $buildDeps \

View File

@@ -102,7 +102,7 @@ RUN curl -sSL http://packages.erlang-solutions.com/rpm/centos/erlang_solutions.r
erlang-tools
# Go Dependencies
RUN curl -sSL https://storage.googleapis.com/golang/go1.8.3.linux-amd64.tar.gz | tar -C /usr/local/ -xz
RUN curl -sSL https://storage.googleapis.com/golang/go1.4.3.linux-amd64.tar.gz | tar -C /usr/local/ -xz
ENV PATH /usr/local/go/bin:$PATH
# Haskell Dependencies

View File

@@ -155,7 +155,7 @@ RUN pip2 install -U ipaddress backports.ssl_match_hostname tornado
RUN pip3 install -U backports.ssl_match_hostname tornado
# Go
RUN curl -sSL https://storage.googleapis.com/golang/go1.8.3.linux-amd64.tar.gz | tar -C /usr/local/ -xz
RUN curl -sSL https://storage.googleapis.com/golang/go1.4.3.linux-amd64.tar.gz | tar -C /usr/local/ -xz
ENV PATH /usr/local/go/bin:$PATH
# Haxe

View File

@@ -177,7 +177,7 @@ RUN pip2 install -U ipaddress backports.ssl_match_hostname tornado
RUN pip3 install -U backports.ssl_match_hostname tornado
# Go
RUN curl -sSL https://storage.googleapis.com/golang/go1.8.3.linux-amd64.tar.gz | tar -C /usr/local/ -xz
RUN curl -sSL https://storage.googleapis.com/golang/go1.4.3.linux-amd64.tar.gz | tar -C /usr/local/ -xz
ENV PATH /usr/local/go/bin:$PATH
# Haxe

View File

@@ -118,6 +118,8 @@ public:
void generate_type_metadata(std::string function_name, vector<string> names);
void generate_enum_info(t_enum* tenum);
void generate_enum_metadata();
void generate_const_function(t_const* tconst, ostringstream& exports, ostringstream& functions);
void generate_const_functions();
/**
* Service-level generation functions
@@ -136,6 +138,7 @@ public:
std::string erl_imports();
std::string render_includes();
std::string type_name(t_type* ttype);
std::string render_const_list_values(t_type* type, t_const_value* value);
std::string function_signature(t_function* tfunction, std::string prefix = "");
@@ -188,7 +191,6 @@ private:
void export_function(t_function* tfunction, std::string prefix = "");
void export_string(std::string name, int num);
void export_types_function(t_function* tfunction, std::string prefix = "");
void export_types_string(std::string name, int num);
/**
@@ -218,7 +220,9 @@ private:
std::ofstream f_types_file_;
std::ofstream f_types_hrl_file_;
std::ofstream f_consts_;
std::ofstream f_consts_file_;
std::ofstream f_consts_hrl_file_;
std::ostringstream f_service_;
std::ofstream f_service_file_;
std::ofstream f_service_hrl_;
@@ -230,6 +234,7 @@ private:
std::vector<std::string> v_enum_names_;
std::vector<std::string> v_exception_names_;
std::vector<t_enum*> v_enums_;
std::vector<t_const*> v_consts_;
};
/**
@@ -246,31 +251,41 @@ void t_erl_generator::init_generator() {
export_lines_first_ = true;
export_types_lines_first_ = true;
string program_module_name = make_safe_for_module_name(program_name_);
// types files
string f_types_name = get_out_dir() + make_safe_for_module_name(program_name_) + "_types.erl";
string f_types_hrl_name = get_out_dir() + make_safe_for_module_name(program_name_) + "_types.hrl";
string f_types_name = get_out_dir() + program_module_name + "_types.erl";
string f_types_hrl_name = get_out_dir() + program_module_name + "_types.hrl";
f_types_file_.open(f_types_name.c_str());
f_types_hrl_file_.open(f_types_hrl_name.c_str());
hrl_header(f_types_hrl_file_, make_safe_for_module_name(program_name_) + "_types");
hrl_header(f_types_hrl_file_, program_module_name + "_types");
f_types_file_ << erl_autogen_comment() << endl << "-module("
<< make_safe_for_module_name(program_name_) << "_types)." << endl << erl_imports()
f_types_file_ << erl_autogen_comment() << endl
<< "-module(" << program_module_name << "_types)." << endl
<< erl_imports() << endl;
f_types_file_ << "-include(\"" << f_types_hrl_name << "\")." << endl
<< endl;
f_types_file_ << "-include(\"" << make_safe_for_module_name(program_name_) << "_types.hrl\")."
<< endl << endl;
f_types_hrl_file_ << render_includes() << endl;
// consts file
string f_consts_name = get_out_dir() + make_safe_for_module_name(program_name_)
+ "_constants.hrl";
f_consts_.open(f_consts_name.c_str());
// consts files
string f_consts_name = get_out_dir() + program_module_name + "_constants.erl";
string f_consts_hrl_name = get_out_dir() + program_module_name + "_constants.hrl";
f_consts_ << erl_autogen_comment() << endl << erl_imports() << endl << "-include(\""
<< make_safe_for_module_name(program_name_) << "_types.hrl\")." << endl << endl;
f_consts_file_.open(f_consts_name.c_str());
f_consts_hrl_file_.open(f_consts_hrl_name.c_str());
f_consts_file_ << erl_autogen_comment() << endl
<< "-module(" << program_module_name << "_constants)." << endl
<< erl_imports() << endl
<< "-include(\"" << f_types_hrl_name << "\")." << endl
<< endl;
f_consts_hrl_file_ << erl_autogen_comment() << endl << erl_imports() << endl
<< "-include(\"" << f_types_hrl_name << "\")." << endl << endl;
}
/**
@@ -351,6 +366,8 @@ void t_erl_generator::close_generator() {
f_types_file_ << f_info_ext_.str();
f_types_file_ << "struct_info_ext(_) -> erlang:error(function_clause)." << endl << endl;
generate_const_functions();
generate_type_metadata("struct_names", v_struct_names_);
generate_enum_metadata();
generate_type_metadata("enum_names", v_enum_names_);
@@ -360,7 +377,8 @@ void t_erl_generator::close_generator() {
f_types_file_.close();
f_types_hrl_file_.close();
f_consts_.close();
f_consts_file_.close();
f_consts_hrl_file_.close();
}
void t_erl_generator::generate_type_metadata(std::string function_name, vector<string> names) {
@@ -393,6 +411,68 @@ void t_erl_generator::generate_typedef(t_typedef* ttypedef) {
(void)ttypedef;
}
void t_erl_generator::generate_const_function(t_const* tconst, ostringstream& exports, ostringstream& functions) {
t_type* type = get_true_type(tconst->get_type());
string name = tconst->get_name();
t_const_value* value = tconst->get_value();
if (type->is_map()) {
t_type* ktype = ((t_map*)type)->get_key_type();
t_type* vtype = ((t_map*)type)->get_val_type();
string const_fun_name = lowercase(name);
// Emit const function export.
if (exports.tellp() > 0) { exports << ", "; }
exports << const_fun_name << "/1, " << const_fun_name << "/2";
// Emit const function definition.
map<t_const_value*, t_const_value*>::const_iterator i, end = value->get_map().end();
// The one-argument form throws an error if the key does not exist in the map.
for (i = value->get_map().begin(); i != end;) {
functions << const_fun_name << "(" << render_const_value(ktype, i->first) << ") -> "
<< render_const_value(vtype, i->second);
++i;
functions << (i != end ? ";\n" : ".\n\n");
}
// The two-argument form returns a default value if the key does not exist in the map.
for (i = value->get_map().begin(); i != end; ++i) {
functions << const_fun_name << "(" << render_const_value(ktype, i->first) << ", _) -> "
<< render_const_value(vtype, i->second) << ";\n";
}
functions << const_fun_name << "(_, Default) -> Default.\n\n";
} else if (type->is_list()) {
string const_fun_name = lowercase(name);
if (exports.tellp() > 0) { exports << ", "; }
exports << const_fun_name << "/1, " << const_fun_name << "/2";
size_t list_size = value->get_list().size();
string rendered_list = render_const_list_values(type, value);
functions << const_fun_name << "(N) when N >= 1, N =< " << list_size << " ->\n"
<< indent_str() << "element(N, {" << rendered_list << "}).\n";
functions << const_fun_name << "(N, _) when N >= 1, N =< " << list_size << " ->\n"
<< indent_str() << "element(N, {" << rendered_list << "});\n"
<< const_fun_name << "(_, Default) -> Default.\n\n";
indent_down();
}
}
void t_erl_generator::generate_const_functions() {
ostringstream exports;
ostringstream functions;
vector<t_const*>::iterator c_iter;
for (c_iter = v_consts_.begin(); c_iter != v_consts_.end(); ++c_iter) {
generate_const_function(*c_iter, exports, functions);
}
if (exports.tellp() > 0) {
f_consts_file_ << "-export([" << exports.str() << "]).\n\n"
<< functions.str();
}
}
/**
* Generates code for an enumerated type. Done using a class to scope
* the values.
@@ -459,8 +539,11 @@ void t_erl_generator::generate_const(t_const* tconst) {
string name = tconst->get_name();
t_const_value* value = tconst->get_value();
f_consts_ << "-define(" << constify(make_safe_for_module_name(program_name_)) << "_"
<< constify(name) << ", " << render_const_value(type, value) << ")." << endl << endl;
// Save the tconst so that function can be emitted in generate_const_functions().
v_consts_.push_back(tconst);
f_consts_hrl_file_ << "-define(" << constify(make_safe_for_module_name(program_name_)) << "_"
<< constify(name) << ", " << render_const_value(type, value) << ")." << endl << endl;
}
/**
@@ -561,28 +644,32 @@ string t_erl_generator::render_const_value(t_type* type, t_const_value* value) {
}
out << "])";
} else if (type->is_list()) {
t_type* etype;
etype = ((t_list*)type)->get_elem_type();
out << "[";
bool first = true;
const vector<t_const_value*>& val = value->get_list();
vector<t_const_value*>::const_iterator v_iter;
for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
if (first) {
first = false;
} else {
out << ",";
}
out << render_const_value(etype, *v_iter);
}
out << "]";
out << "[" << render_const_list_values(type, value) << "]";
} else {
throw "CANNOT GENERATE CONSTANT FOR TYPE: " + type->get_name();
}
return out.str();
}
string t_erl_generator::render_const_list_values(t_type* type, t_const_value* value) {
std::ostringstream out;
t_type* etype = ((t_list*)type)->get_elem_type();
bool first = true;
const vector<t_const_value*>& val = value->get_list();
vector<t_const_value*>::const_iterator v_iter;
for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
if (first) {
first = false;
} else {
out << ",";
}
out << render_const_value(etype, *v_iter);
}
return out.str();
}
string t_erl_generator::render_default_value(t_field* field) {
t_type* type = field->get_type();
if (type->is_struct() || type->is_xception()) {
@@ -968,16 +1055,6 @@ void t_erl_generator::export_string(string name, int num) {
export_lines_ << name << "/" << num;
}
void t_erl_generator::export_types_function(t_function* tfunction, string prefix) {
t_struct::members_type::size_type num = tfunction->get_arglist()->get_members().size();
if (num > static_cast<t_struct::members_type::size_type>(std::numeric_limits<int>().max())) {
throw "integer overflow in t_erl_generator::export_types_function, name " + tfunction->get_name();
}
export_types_string(prefix + tfunction->get_name(),
1 // This
+ static_cast<int>(num));
}
void t_erl_generator::export_types_string(string name, int num) {
if (export_types_lines_first_) {
export_types_lines_first_ = false;
@@ -1019,19 +1096,14 @@ string t_erl_generator::argument_list(t_struct* tstruct) {
}
string t_erl_generator::type_name(t_type* ttype) {
string prefix = "";
string erl_namespace = ttype->get_program()->get_namespace("erl");
if (erl_namespace.length() > 0) {
prefix = erl_namespace + ".";
string prefix = ttype->get_program()->get_namespace("erl");
size_t prefix_length = prefix.length();
if (prefix_length > 0 && prefix[prefix_length - 1] != '_') {
prefix += '.';
}
string name = ttype->get_name();
if (ttype->is_struct() || ttype->is_xception() || ttype->is_service()) {
name = ttype->get_name();
}
return atomify(prefix + name);
}

View File

@@ -81,7 +81,7 @@ public:
gen_package_prefix_ = "";
package_flag = "";
read_write_private_ = false;
use_context_ = false;
legacy_context_ = false;
ignore_initialisms_ = false;
for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) {
if( iter->first.compare("package_prefix") == 0) {
@@ -92,8 +92,8 @@ public:
package_flag = (iter->second);
} else if( iter->first.compare("read_write_private") == 0) {
read_write_private_ = true;
} else if( iter->first.compare("use_context") == 0) {
use_context_ = true;
} else if( iter->first.compare("legacy_context") == 0) {
legacy_context_ = true;
} else if( iter->first.compare("ignore_initialisms") == 0) {
ignore_initialisms_ = true;
} else {
@@ -261,8 +261,7 @@ public:
std::string function_signature(t_function* tfunction, std::string prefix = "");
std::string function_signature_if(t_function* tfunction,
std::string prefix = "",
bool addError = false,
bool enableContext = false);
bool addError = false);
std::string argument_list(t_struct* tstruct);
std::string type_to_enum(t_type* ttype);
std::string type_to_go_type(t_type* ttype);
@@ -288,7 +287,7 @@ private:
std::string gen_package_prefix_;
std::string gen_thrift_import_;
bool read_write_private_;
bool use_context_;
bool legacy_context_;
bool ignore_initialisms_;
/**
@@ -884,7 +883,10 @@ string t_go_generator::go_imports_begin(bool consts) {
"\t\"database/sql/driver\"\n"
"\t\"errors\"\n";
}
if (use_context_) {
if (legacy_context_) {
extra +=
"\t\"golang.org/x/net/context\"\n";
} else {
extra +=
"\t\"context\"\n";
}
@@ -904,20 +906,13 @@ string t_go_generator::go_imports_begin(bool consts) {
* This will have to do in lieu of more intelligent import statement construction
*/
string t_go_generator::go_imports_end() {
string extra;
if (use_context_) {
extra +=
"var _ = context.Background\n";
}
return string(
")\n\n"
"// (needed to ensure safety because of naive import list construction.)\n"
"var _ = thrift.ZERO\n"
"var _ = fmt.Printf\n"
"var _ = context.Background\n"
"var _ = reflect.DeepEqual\n"
+ extra +
"var _ = bytes.Equal\n\n");
}
@@ -1842,7 +1837,7 @@ void t_go_generator::generate_service_interface(t_service* tservice) {
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
generate_go_docstring(f_types_, (*f_iter));
f_types_ << indent() << function_signature_if(*f_iter, "", true, use_context_) << endl;
f_types_ << indent() << function_signature_if(*f_iter, "", true) << endl;
}
}
@@ -1956,7 +1951,7 @@ void t_go_generator::generate_service_client(t_service* tservice) {
// Open function
generate_go_docstring(f_types_, (*f_iter));
f_types_ << indent() << "func (p *" << serviceName << "Client) "
<< function_signature_if(*f_iter, "", true, false) << " {" << endl;
<< function_signature_if(*f_iter, "", true) << " {" << endl;
indent_up();
/*
f_types_ <<
@@ -2164,9 +2159,15 @@ void t_go_generator::generate_service_remote(t_service* tservice) {
string unused_protection;
string ctxPackage = "context";
if (legacy_context_) {
ctxPackage = "golang.org/x/net/context";
}
f_remote << go_autogen_comment();
f_remote << indent() << "package main" << endl << endl;
f_remote << indent() << "import (" << endl;
f_remote << indent() << " \"" << ctxPackage << "\"" << endl;
f_remote << indent() << " \"flag\"" << endl;
f_remote << indent() << " \"fmt\"" << endl;
f_remote << indent() << " \"math\"" << endl;
@@ -2506,9 +2507,11 @@ void t_go_generator::generate_service_remote(t_service* tservice) {
f_remote << indent() << "fmt.Print(client." << pubName << "(";
bool argFirst = true;
f_remote << "context.Background()";
for (std::vector<t_field*>::size_type i = 0; i < num_args; ++i) {
if (argFirst) {
argFirst = false;
f_remote << ", ";
} else {
f_remote << ", ";
}
@@ -2604,36 +2607,31 @@ void t_go_generator::generate_service_server(t_service* tservice) {
// Generate the header portion
string self(tmp("self"));
string processorFunction("thrift.TProcessorFunction");
if (use_context_) {
processorFunction = "thrift.TProcessorFunction2";
}
if (extends_processor.empty()) {
f_types_ << indent() << "type " << serviceName << "Processor struct {" << endl;
f_types_ << indent() << " processorMap map[string]" << processorFunction << endl;
f_types_ << indent() << " processorMap map[string]thrift.TProcessorFunction" << endl;
f_types_ << indent() << " handler " << serviceName << endl;
f_types_ << indent() << "}" << endl << endl;
f_types_ << indent() << "func (p *" << serviceName
<< "Processor) AddToProcessorMap(key string, processor " << processorFunction << ") {"
<< "Processor) AddToProcessorMap(key string, processor thrift.TProcessorFunction) {"
<< endl;
f_types_ << indent() << " p.processorMap[key] = processor" << endl;
f_types_ << indent() << "}" << endl << endl;
f_types_ << indent() << "func (p *" << serviceName
<< "Processor) GetProcessorFunction(key string) "
"(processor "<< processorFunction << ", ok bool) {" << endl;
"(processor thrift.TProcessorFunction, ok bool) {" << endl;
f_types_ << indent() << " processor, ok = p.processorMap[key]" << endl;
f_types_ << indent() << " return processor, ok" << endl;
f_types_ << indent() << "}" << endl << endl;
f_types_ << indent() << "func (p *" << serviceName
<< "Processor) ProcessorMap() map[string]" << processorFunction << "{" << endl;
<< "Processor) ProcessorMap() map[string]thrift.TProcessorFunction {" << endl;
f_types_ << indent() << " return p.processorMap" << endl;
f_types_ << indent() << "}" << endl << endl;
f_types_ << indent() << "func New" << serviceName << "Processor(handler " << serviceName
<< ") *" << serviceName << "Processor {" << endl << endl;
f_types_
<< indent() << " " << self << " := &" << serviceName
<< "Processor{handler:handler, processorMap:make(map[string]" << processorFunction << ")}"
<< "Processor{handler:handler, processorMap:make(map[string]thrift.TProcessorFunction)}"
<< endl;
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
@@ -2643,24 +2641,16 @@ void t_go_generator::generate_service_server(t_service* tservice) {
<< "{handler:handler}" << endl;
}
string ctxParam("");
string ctxVar("");
if (use_context_) {
ctxParam = "ctx context.Context, ";
ctxVar = "ctx, ";
}
string x(tmp("x"));
f_types_ << indent() << "return " << self << endl;
f_types_ << indent() << "}" << endl << endl;
f_types_ << indent() << "func (p *" << serviceName
<< "Processor) Process(" << ctxParam
<< "iprot, oprot thrift.TProtocol) (success bool, err "
<< "Processor) Process(ctx context.Context, iprot, oprot thrift.TProtocol) (success bool, err "
"thrift.TException) {" << endl;
f_types_ << indent() << " name, _, seqId, err := iprot.ReadMessageBegin()" << endl;
f_types_ << indent() << " if err != nil { return false, err }" << endl;
f_types_ << indent() << " if processor, ok := p.GetProcessorFunction(name); ok {" << endl;
f_types_ << indent() << " return processor.Process(" << ctxVar << "seqId, iprot, oprot)" << endl;
f_types_ << indent() << " return processor.Process(ctx, seqId, iprot, oprot)" << endl;
f_types_ << indent() << " }" << endl;
f_types_ << indent() << " iprot.Skip(thrift.STRUCT)" << endl;
f_types_ << indent() << " iprot.ReadMessageEnd()" << endl;
@@ -2714,12 +2704,6 @@ void t_go_generator::generate_process_function(t_service* tservice, t_function*
string argsname = publicize(tfunction->get_name() + "_args", true);
string resultname = publicize(tfunction->get_name() + "_result", true);
string ctxParam("");
string ctxVar("");
if (use_context_) {
ctxParam = "ctx context.Context, ";
ctxVar = "ctx";
}
// t_struct* xs = tfunction->get_xceptions();
// const std::vector<t_field*>& xceptions = xs->get_members();
vector<t_field*>::const_iterator x_iter;
@@ -2727,7 +2711,7 @@ void t_go_generator::generate_process_function(t_service* tservice, t_function*
f_types_ << indent() << " handler " << publicize(tservice->get_name()) << endl;
f_types_ << indent() << "}" << endl << endl;
f_types_ << indent() << "func (p *" << processorName
<< ") Process(" << ctxParam << "seqId int32, iprot, oprot thrift.TProtocol) (success bool, err "
<< ") Process(ctx context.Context, seqId int32, iprot, oprot thrift.TProtocol) (success bool, err "
"thrift.TException) {" << endl;
indent_up();
f_types_ << indent() << "args := " << argsname << "{}" << endl;
@@ -2771,13 +2755,11 @@ void t_go_generator::generate_process_function(t_service* tservice, t_function*
f_types_ << "err2 = p.handler." << publicize(tfunction->get_name()) << "(";
bool first = true;
f_types_ << ctxVar;
f_types_ << "ctx";
for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
if (first) {
first = false;
if (use_context_) {
f_types_ << ", ";
}
f_types_ << ", ";
} else {
f_types_ << ", ";
}
@@ -3459,15 +3441,12 @@ string t_go_generator::function_signature(t_function* tfunction, string prefix)
* Renders an interface function signature of the form 'type name(args)'
*
* @param tfunction Function definition
* @param disableContext Client doesn't suppport context for now.
* @return String of rendered function definition
*/
string t_go_generator::function_signature_if(t_function* tfunction, string prefix, bool addError, bool enableContext) {
string t_go_generator::function_signature_if(t_function* tfunction, string prefix, bool addError) {
// TODO(mcslee): Nitpicky, no ',' if argument_list is empty
string signature = publicize(prefix + tfunction->get_name()) + "(";
if (enableContext) {
signature += "ctx context.Context, ";
}
signature += "ctx context.Context, ";
signature += argument_list(tfunction->get_arglist()) + ") (";
t_type* ret = tfunction->get_returntype();
t_struct* exceptions = tfunction->get_xceptions();
@@ -3745,5 +3724,5 @@ THRIFT_REGISTER_GENERATOR(go, "Go",
" Disable automatic spelling correction of initialisms (e.g. \"URL\")\n" \
" read_write_private\n"
" Make read/write methods private, default is public Read/Write\n" \
" use_context\n"
" Make service method receive a context as first argument.\n")
" legacy_context\n"
" Use legacy x/net/context instead of context in go<1.7.\n")

View File

@@ -2218,10 +2218,10 @@ std::string t_js_generator::ts_function_signature(t_function* tfunction, bool in
}
if (include_callback) {
str += "callback: Function): ";
str += "callback: (data: " + ts_get_type(tfunction->get_returntype()) + ")=>void): ";
if (gen_jquery_) {
str += "JQueryXHR;";
str += "JQueryPromise<" + ts_get_type(tfunction->get_returntype()) +">;";
} else {
str += "void;";
}

View File

@@ -397,7 +397,8 @@ if test "$with_go" = "yes"; then
AC_PATH_PROG([GO], [go])
if [[ -x "$GO" ]] ; then
AS_IF([test -n "$GO"],[
ax_go_version="1.7"
ax_go_version="1.4"
ax_go17_version="1.7"
AC_MSG_CHECKING([for Go version])
golang_version=`$GO version 2>&1 | $SED -e 's/\(go \)\(version \)\(go\)\(@<:@0-9@:>@.@<:@0-9@:>@.@<:@0-9@:>@\)\(@<:@\*@:>@*\).*/\4/'`
@@ -410,6 +411,13 @@ if test "$with_go" = "yes"; then
:
have_go="no"
])
AX_COMPARE_VERSION([$golang_version],[lt],[$ax_go17_version],[
:
go_version_lt_17="yes"
],[
:
go_version_lt_17="no"
])
],[
AC_MSG_WARN([could not find Go ])
have_go="no"
@@ -417,6 +425,7 @@ if test "$with_go" = "yes"; then
fi
fi
AM_CONDITIONAL(WITH_GO, [test "$have_go" = "yes"])
AM_CONDITIONAL([GOVERSION_LT_17], [test "$go_version_lt_17" = "yes"])
AX_THRIFT_LIB(rs, [Rust], yes)
have_rs="no"

View File

@@ -39,5 +39,5 @@ These are only required if you choose to build the libraries for the given langu
* Bit::Vector
* Class::Accessor
* Haxe 3.1.3
* Go 1.7
* Go 1.4
* Delphi 2010

View File

@@ -69,8 +69,9 @@ type
end;
function InterlockedCompareExchange64( var Target : Int64; Exchange, Comparand : Int64) : Int64; stdcall;
function InterlockedExchangeAdd64( var Addend : Int64; Value : Int64) : Int64; stdcall;
{$IFDEF Win64}
function InterlockedExchangeAdd64( var Addend : Int64; Value : Int64) : Int64;
{$ENDIF}
implementation
@@ -223,14 +224,19 @@ begin
end;
// natively available since stone age
function InterlockedCompareExchange64;
external KERNEL32 name 'InterlockedCompareExchange64';
{$IFDEF Win64}
function InterlockedCompareExchange64( var Target : Int64; Exchange, Comparand : Int64) : Int64; inline;
begin
{$IFDEF OLD_UNIT_NAMES}
result := Windows.InterlockedCompareExchange64( Target, Exchange, Comparand);
{$ELSE}
result := WinApi.Windows.InterlockedCompareExchange64( Target, Exchange, Comparand);
{$ENDIF}
end;
// natively available >= Vista
// implemented this way since there are still some people running Windows XP :-(
function InterlockedExchangeAdd64( var Addend : Int64; Value : Int64) : Int64; stdcall;
function InterlockedExchangeAdd64( var Addend : Int64; Value : Int64) : Int64;
var old : Int64;
begin
repeat
@@ -239,6 +245,7 @@ begin
result := Old;
end;
{$ENDIF}
end.

View File

@@ -39,6 +39,7 @@ uses
Thrift.Transport,
Thrift.Stream,
Thrift.Test,
Thrift.Utils,
Thrift.Collections,
Thrift.Console;
@@ -88,6 +89,9 @@ type
{$IFDEF StressTest}
procedure StressTest(const client : TThriftTest.Iface);
{$ENDIF}
{$IFDEF Win64}
procedure UseInterlockedExchangeAdd64;
{$ENDIF}
protected
procedure Execute; override;
public
@@ -1014,6 +1018,18 @@ begin
end;
{$IFDEF Win64}
procedure TClientThread.UseInterlockedExchangeAdd64;
var a,b : Int64;
begin
a := 1;
b := 2;
Thrift.Utils.InterlockedExchangeAdd64( a,b);
Expect( a = 3, 'InterlockedExchangeAdd64');
end;
{$ENDIF}
procedure TClientThread.JSONProtocolReadWriteTest;
// Tests only then read/write procedures of the JSON protocol
// All tests succeed, if we can read what we wrote before
@@ -1249,7 +1265,11 @@ var
begin
// perform all tests
try
{$IFDEF Win64}
UseInterlockedExchangeAdd64;
{$ENDIF}
JSONProtocolReadWriteTest;
for i := 0 to FNumIteration - 1 do
begin
ClientTest;

View File

@@ -19,6 +19,7 @@
THRIFT = ../../compiler/cpp/thrift
THRIFT_FILES = $(wildcard test/*.thrift) \
../../test/ConstantsDemo.thrift \
../../test/NameConflictTest.thrift \
../../test/ThriftTest.thrift

View File

@@ -103,11 +103,9 @@ read_exact(Transport = #t_transport{module = Module}, Len)
when is_integer(Len), Len >= 0 ->
case lists:keyfind(read_exact, 1, Module:module_info(exports)) of
{read_exact, 2} ->
io:fwrite("HAS EXACT"),
{NewState, Result} = Module:read_exact(Transport#t_transport.state, Len),
{Transport#t_transport{state = NewState}, Result};
_ ->
io:fwrite("~p NO EXACT", [Module]),
read(Transport, Len)
end.

View File

@@ -0,0 +1,54 @@
%%
%% Licensed to the Apache Software Foundation (ASF) under one
%% or more contributor license agreements. See the NOTICE file
%% distributed with this work for additional information
%% regarding copyright ownership. The ASF licenses this file
%% to you under the Apache License, Version 2.0 (the
%% "License"); you may not use this file except in compliance
%% with the License. You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing,
%% software distributed under the License is distributed on an
%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
-module(test_const).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-include("gen-erl/constants_demo_types.hrl").
namespace_test() ->
%% Verify that records produced by ConstantsDemo.thrift have the right namespace.
io:format(user, "in namespace_test()\n", []),
{struct, _} = constants_demo_types:struct_info('consts_thing'),
{struct, _} = constants_demo_types:struct_info('consts_Blah'),
ok.
const_map_test() ->
?assertEqual(233, constants_demo_constants:gen_map(35532)),
?assertError(function_clause, constants_demo_constants:gen_map(0)),
?assertEqual(853, constants_demo_constants:gen_map(43523, default)),
?assertEqual(default, constants_demo_constants:gen_map(10110, default)),
?assertEqual(98325, constants_demo_constants:gen_map2("lkjsdf")),
?assertError(function_clause, constants_demo_constants:gen_map2("nonexist")),
?assertEqual(233, constants_demo_constants:gen_map2("hello", 321)),
?assertEqual(321, constants_demo_constants:gen_map2("goodbye", 321)).
const_list_test() ->
?assertEqual(23598352, constants_demo_constants:gen_list(2)),
?assertError(function_clause, constants_demo_constants:gen_list(0)),
?assertEqual(3253523, constants_demo_constants:gen_list(3, default)),
?assertEqual(default, constants_demo_constants:gen_list(10, default)).
-endif. %% TEST

View File

@@ -31,10 +31,12 @@ install:
@echo '##############################################################'
check-local:
$(GO) test -race ./thrift
GOPATH=`pwd` $(GO) get golang.org/x/net/context
GOPATH=`pwd` $(GO) test -race ./thrift
all-local:
$(GO) build ./thrift
GOPATH=`pwd` $(GO) get golang.org/x/net/context
GOPATH=`pwd` $(GO) build ./thrift
EXTRA_DIST = \
thrift \

View File

@@ -17,8 +17,12 @@
# under the License.
#
if GOVERSION_LT_17
COMPILER_EXTRAFLAG=",legacy_context"
endif
THRIFT = $(top_builddir)/compiler/cpp/thrift
THRIFTARGS = -out gopath/src/ --gen go:thrift_import=thrift
THRIFTARGS = -out gopath/src/ --gen go:thrift_import=thrift$(COMPILER_EXTRAFLAG)
THRIFTTEST = $(top_srcdir)/test/ThriftTest.thrift
# Thrift for GO has problems with complex map keys: THRIFT-2063
@@ -57,6 +61,7 @@ gopath: $(THRIFT) $(THRIFTTEST) \
$(THRIFT) $(THRIFTARGS),read_write_private DontExportRWTest.thrift
$(THRIFT) $(THRIFTARGS),ignore_initialisms IgnoreInitialismsTest.thrift
GOPATH=`pwd`/gopath $(GO) get github.com/golang/mock/gomock
GOPATH=`pwd`/gopath $(GO) get golang.org/x/net/context
ln -nfs ../../../thrift gopath/src/thrift
ln -nfs ../../tests gopath/src/tests
cp -r ./dontexportrwtest gopath/src

View File

@@ -412,7 +412,7 @@ func TestClientReportTTransportErrors(t *testing.T) {
return
}
client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol)
_, retErr := client.TestStruct(thing)
_, retErr := client.TestStruct(defaultCtx, thing)
mockCtrl.Finish()
err2, ok := retErr.(thrift.TTransportException)
if !ok {
@@ -444,7 +444,7 @@ func TestClientReportTProtocolErrors(t *testing.T) {
return
}
client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol)
_, retErr := client.TestStruct(thing)
_, retErr := client.TestStruct(defaultCtx, thing)
mockCtrl.Finish()
err2, ok := retErr.(thrift.TProtocolException)
if !ok {
@@ -565,7 +565,7 @@ func TestClientCallException(t *testing.T) {
willComplete := !prepareClientCallException(protocol, i, err)
client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol)
_, retErr := client.TestString("test")
_, retErr := client.TestString(defaultCtx, "test")
mockCtrl.Finish()
if !willComplete {
@@ -608,7 +608,7 @@ func TestClientSeqIdMismatch(t *testing.T) {
)
client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol)
_, err := client.TestString("test")
_, err := client.TestString(defaultCtx, "test")
mockCtrl.Finish()
appErr, ok := err.(thrift.TApplicationException)
if !ok {
@@ -638,7 +638,7 @@ func TestClientWrongMethodName(t *testing.T) {
)
client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol)
_, err := client.TestString("test")
_, err := client.TestString(defaultCtx, "test")
mockCtrl.Finish()
appErr, ok := err.(thrift.TApplicationException)
if !ok {
@@ -668,7 +668,7 @@ func TestClientWrongMessageType(t *testing.T) {
)
client := errortest.NewErrorTestClientProtocol(transport, protocol, protocol)
_, err := client.TestString("test")
_, err := client.TestString(defaultCtx, "test")
mockCtrl.Finish()
appErr, ok := err.(thrift.TApplicationException)
if !ok {

View File

@@ -0,0 +1,47 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package tests
import (
"context"
"fmt"
)
var defaultCtx = context.Background()
type FirstImpl struct{}
func (f *FirstImpl) ReturnOne(ctx context.Context) (r int64, err error) {
return 1, nil
}
type SecondImpl struct{}
func (s *SecondImpl) ReturnTwo(ctx context.Context) (r int64, err error) {
return 2, nil
}
type impl struct{}
func (i *impl) Hi(ctx context.Context, in int64, s string) (err error) { fmt.Println("Hi!"); return }
func (i *impl) Emptyfunc(ctx context.Context) (err error) { return }
func (i *impl) EchoInt(ctx context.Context, param int64) (r int64, err error) { return param, nil }

View File

@@ -36,17 +36,6 @@ func FindAvailableTCPServerPort() net.Addr {
}
}
type FirstImpl struct{}
func (f *FirstImpl) ReturnOne() (r int64, err error) {
return 1, nil
}
type SecondImpl struct{}
func (s *SecondImpl) ReturnTwo() (r int64, err error) {
return 2, nil
}
var processor = thrift.NewTMultiplexedProcessor()
@@ -114,7 +103,7 @@ func createLegacyClient(t *testing.T) *multiplexedprotocoltest.SecondClient {
}
func TestCallFirst(t *testing.T) {
ret, err := firstClient.ReturnOne()
ret, err := firstClient.ReturnOne(defaultCtx)
if err != nil {
t.Fatal("Unable to call first server:", err)
}
@@ -124,7 +113,7 @@ func TestCallFirst(t *testing.T) {
}
func TestCallSecond(t *testing.T) {
ret, err := secondClient.ReturnTwo()
ret, err := secondClient.ReturnTwo(defaultCtx)
if err != nil {
t.Fatal("Unable to call second server:", err)
}
@@ -135,7 +124,7 @@ func TestCallSecond(t *testing.T) {
func TestCallLegacy(t *testing.T) {
legacyClient := createLegacyClient(t)
ret, err := legacyClient.ReturnTwo()
ret, err := legacyClient.ReturnTwo(defaultCtx)
//expect error since default processor is not registered
if err == nil {
t.Fatal("Expecting error")
@@ -143,7 +132,7 @@ func TestCallLegacy(t *testing.T) {
//register default processor and call again
processor.RegisterDefault(multiplexedprotocoltest.NewSecondProcessor(&SecondImpl{}))
legacyClient = createLegacyClient(t)
ret, err = legacyClient.ReturnTwo()
ret, err = legacyClient.ReturnTwo(defaultCtx)
if err != nil {
t.Fatal("Unable to call legacy server:", err)
}

View File

@@ -20,7 +20,6 @@
package tests
import (
"fmt"
"net"
"onewaytest"
"testing"
@@ -37,12 +36,6 @@ func findPort() net.Addr {
}
}
type impl struct{}
func (i *impl) Hi(in int64, s string) (err error) { fmt.Println("Hi!"); return }
func (i *impl) Emptyfunc() (err error) { return }
func (i *impl) EchoInt(param int64) (r int64, err error) { return param, nil }
const TIMEOUT = time.Second
var addr net.Addr
@@ -75,12 +68,12 @@ func TestInitOnewayClient(t *testing.T) {
func TestCallOnewayServer(t *testing.T) {
//call oneway function
err := client.Hi(1, "")
err := client.Hi(defaultCtx, 1, "")
if err != nil {
t.Fatal("Unexpected error: ", err)
}
//There is no way to detect protocol problems with single oneway call so we call it second time
i, err := client.EchoInt(42)
i, err := client.EchoInt(defaultCtx, 42)
if err != nil {
t.Fatal("Unexpected error: ", err)
}

View File

@@ -0,0 +1,48 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package tests
import (
"fmt"
"golang.org/x/net/context"
)
var defaultCtx = context.Background()
type FirstImpl struct{}
func (f *FirstImpl) ReturnOne(ctx context.Context) (r int64, err error) {
return 1, nil
}
type SecondImpl struct{}
func (s *SecondImpl) ReturnTwo(ctx context.Context) (r int64, err error) {
return 2, nil
}
type impl struct{}
func (i *impl) Hi(ctx context.Context, in int64, s string) (err error) { fmt.Println("Hi!"); return }
func (i *impl) Emptyfunc(ctx context.Context) (err error) { return }
func (i *impl) EchoInt(ctx context.Context, param int64) (r int64, err error) { return param, nil }

View File

@@ -30,7 +30,7 @@ func staticCheckStructArgsResults() {
var iface st.AServ
var err error
sa, err = iface.StructAFunc_1structA(sa)
sa, err = iface.StructAFunc_1structA(defaultCtx, sa)
_ = err
_ = sa
}

View File

@@ -38,15 +38,15 @@ func (p *ThriftTestDriver) Start() {
client := p.client
t := p.t
if client.TestVoid() != nil {
if client.TestVoid(defaultCtx) != nil {
t.Fatal("TestVoid failed")
}
if r, err := client.TestString("Test"); r != "Test" || err != nil {
if r, err := client.TestString(defaultCtx, "Test"); r != "Test" || err != nil {
t.Fatal("TestString with simple text failed")
}
if r, err := client.TestString(""); r != "" || err != nil {
if r, err := client.TestString(defaultCtx, ""); r != "" || err != nil {
t.Fatal("TestString with empty text failed")
}
@@ -76,7 +76,7 @@ func (p *ThriftTestDriver) Start() {
"Walon, Winaray, 吴语, isiXhosa, ייִדיש, Yorùbá, Zeêuws, 中文, " +
"Bân-lâm-gú, 粵語"
if r, err := client.TestString(stringTest); r != stringTest || err != nil {
if r, err := client.TestString(defaultCtx, stringTest); r != stringTest || err != nil {
t.Fatal("TestString with all languages failed")
}
@@ -86,44 +86,44 @@ func (p *ThriftTestDriver) Start() {
" now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><" +
" char-to-test-json-parsing: ]] \"]] \\\" }}}{ [[[ "
if r, err := client.TestString(specialCharacters); r != specialCharacters || err != nil {
if r, err := client.TestString(defaultCtx, specialCharacters); r != specialCharacters || err != nil {
t.Fatal("TestString with specialCharacters failed")
}
if r, err := client.TestByte(1); r != 1 || err != nil {
if r, err := client.TestByte(defaultCtx, 1); r != 1 || err != nil {
t.Fatal("TestByte(1) failed")
}
if r, err := client.TestByte(0); r != 0 || err != nil {
if r, err := client.TestByte(defaultCtx, 0); r != 0 || err != nil {
t.Fatal("TestByte(0) failed")
}
if r, err := client.TestByte(-1); r != -1 || err != nil {
if r, err := client.TestByte(defaultCtx, -1); r != -1 || err != nil {
t.Fatal("TestByte(-1) failed")
}
if r, err := client.TestByte(-127); r != -127 || err != nil {
if r, err := client.TestByte(defaultCtx, -127); r != -127 || err != nil {
t.Fatal("TestByte(-127) failed")
}
if r, err := client.TestI32(-1); r != -1 || err != nil {
if r, err := client.TestI32(defaultCtx, -1); r != -1 || err != nil {
t.Fatal("TestI32(-1) failed")
}
if r, err := client.TestI32(1); r != 1 || err != nil {
if r, err := client.TestI32(defaultCtx, 1); r != 1 || err != nil {
t.Fatal("TestI32(1) failed")
}
if r, err := client.TestI64(-5); r != -5 || err != nil {
if r, err := client.TestI64(defaultCtx, -5); r != -5 || err != nil {
t.Fatal("TestI64(-5) failed")
}
if r, err := client.TestI64(5); r != 5 || err != nil {
if r, err := client.TestI64(defaultCtx, 5); r != 5 || err != nil {
t.Fatal("TestI64(5) failed")
}
if r, err := client.TestI64(-34359738368); r != -34359738368 || err != nil {
if r, err := client.TestI64(defaultCtx, -34359738368); r != -34359738368 || err != nil {
t.Fatal("TestI64(-34359738368) failed")
}
if r, err := client.TestDouble(-5.2098523); r != -5.2098523 || err != nil {
if r, err := client.TestDouble(defaultCtx, -5.2098523); r != -5.2098523 || err != nil {
t.Fatal("TestDouble(-5.2098523) failed")
}
if r, err := client.TestDouble(-7.012052175215044); r != -7.012052175215044 || err != nil {
if r, err := client.TestDouble(defaultCtx, -7.012052175215044); r != -7.012052175215044 || err != nil {
t.Fatal("TestDouble(-7.012052175215044) failed")
}
@@ -134,7 +134,7 @@ func (p *ThriftTestDriver) Start() {
out.ByteThing = 1
out.I32Thing = -3
out.I64Thing = 1000000
if r, err := client.TestStruct(out); !reflect.DeepEqual(r, out) || err != nil {
if r, err := client.TestStruct(defaultCtx, out); !reflect.DeepEqual(r, out) || err != nil {
t.Fatal("TestStruct failed")
}
@@ -142,7 +142,7 @@ func (p *ThriftTestDriver) Start() {
out2.ByteThing = 1
out2.StructThing = out
out2.I32Thing = 5
if r, err := client.TestNest(out2); !reflect.DeepEqual(r, out2) || err != nil {
if r, err := client.TestNest(defaultCtx, out2); !reflect.DeepEqual(r, out2) || err != nil {
t.Fatal("TestNest failed")
}
@@ -150,7 +150,7 @@ func (p *ThriftTestDriver) Start() {
for i := int32(0); i < 5; i++ {
mapout[i] = i - 10
}
if r, err := client.TestMap(mapout); !reflect.DeepEqual(r, mapout) || err != nil {
if r, err := client.TestMap(defaultCtx, mapout); !reflect.DeepEqual(r, mapout) || err != nil {
t.Fatal("TestMap failed")
}
@@ -158,25 +158,25 @@ func (p *ThriftTestDriver) Start() {
"a": "123", "a b": "with spaces ", "same": "same", "0": "numeric key",
"longValue": stringTest, stringTest: "long key",
}
if r, err := client.TestStringMap(mapTestInput); !reflect.DeepEqual(r, mapTestInput) || err != nil {
if r, err := client.TestStringMap(defaultCtx, mapTestInput); !reflect.DeepEqual(r, mapTestInput) || err != nil {
t.Fatal("TestStringMap failed")
}
setTestInput := []int32{1, 2, 3}
if r, err := client.TestSet(setTestInput); !reflect.DeepEqual(r, setTestInput) || err != nil {
if r, err := client.TestSet(defaultCtx, setTestInput); !reflect.DeepEqual(r, setTestInput) || err != nil {
t.Fatal("TestSet failed")
}
listTest := []int32{1, 2, 3}
if r, err := client.TestList(listTest); !reflect.DeepEqual(r, listTest) || err != nil {
if r, err := client.TestList(defaultCtx, listTest); !reflect.DeepEqual(r, listTest) || err != nil {
t.Fatal("TestList failed")
}
if r, err := client.TestEnum(thrifttest.Numberz_ONE); r != thrifttest.Numberz_ONE || err != nil {
if r, err := client.TestEnum(defaultCtx, thrifttest.Numberz_ONE); r != thrifttest.Numberz_ONE || err != nil {
t.Fatal("TestEnum failed")
}
if r, err := client.TestTypedef(69); r != 69 || err != nil {
if r, err := client.TestTypedef(defaultCtx, 69); r != 69 || err != nil {
t.Fatal("TestTypedef failed")
}
@@ -184,7 +184,7 @@ func (p *ThriftTestDriver) Start() {
4: {1: 1, 2: 2, 3: 3, 4: 4},
-4: {-4: -4, -3: -3, -2: -2, -1: -1},
}
if r, err := client.TestMapMap(1); !reflect.DeepEqual(r, mapMapTest) || err != nil {
if r, err := client.TestMapMap(defaultCtx, 1); !reflect.DeepEqual(r, mapMapTest) || err != nil {
t.Fatal("TestMapMap failed")
}
@@ -212,25 +212,25 @@ func (p *ThriftTestDriver) Start() {
1: {thrifttest.Numberz_TWO: crazy, thrifttest.Numberz_THREE: crazy},
2: {thrifttest.Numberz_SIX: crazyEmpty},
}
if r, err := client.TestInsanity(crazy); !reflect.DeepEqual(r, insanity) || err != nil {
if r, err := client.TestInsanity(defaultCtx, crazy); !reflect.DeepEqual(r, insanity) || err != nil {
t.Fatal("TestInsanity failed")
}
if err := client.TestException("TException"); err == nil {
if err := client.TestException(defaultCtx, "TException"); err == nil {
t.Fatal("TestException TException failed")
}
if err, ok := client.TestException("Xception").(*thrifttest.Xception); ok == false || err == nil {
if err, ok := client.TestException(defaultCtx, "Xception").(*thrifttest.Xception); ok == false || err == nil {
t.Fatal("TestException Xception failed")
} else if err.ErrorCode != 1001 || err.Message != "Xception" {
t.Fatal("TestException Xception failed")
}
if err := client.TestException("no Exception"); err != nil {
if err := client.TestException(defaultCtx, "no Exception"); err != nil {
t.Fatal("TestException no Exception failed")
}
if err := client.TestOneway(0); err != nil {
if err := client.TestOneway(defaultCtx, 0); err != nil {
t.Fatal("TestOneway failed")
}
}

View File

@@ -1,3 +1,5 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -24,6 +26,8 @@ import (
"thrift"
"thrifttest"
"time"
"golang.org/x/net/context"
)
type SecondServiceHandler struct {
@@ -33,11 +37,11 @@ func NewSecondServiceHandler() *SecondServiceHandler {
return &SecondServiceHandler{}
}
func (p *SecondServiceHandler) BlahBlah() (err error) {
func (p *SecondServiceHandler) BlahBlah(ctx context.Context) (err error) {
return nil
}
func (p *SecondServiceHandler) SecondtestString(thing string) (r string, err error) {
func (p *SecondServiceHandler) SecondtestString(ctx context.Context, thing string) (r string, err error) {
return thing, nil
}
@@ -48,71 +52,71 @@ func NewThriftTestHandler() *ThriftTestHandler {
return &ThriftTestHandler{}
}
func (p *ThriftTestHandler) TestVoid() (err error) {
func (p *ThriftTestHandler) TestVoid(ctx context.Context) (err error) {
return nil
}
func (p *ThriftTestHandler) TestString(thing string) (r string, err error) {
func (p *ThriftTestHandler) TestString(ctx context.Context, thing string) (r string, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestBool(thing bool) (r bool, err error) {
func (p *ThriftTestHandler) TestBool(ctx context.Context, thing bool) (r bool, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestByte(thing int8) (r int8, err error) {
func (p *ThriftTestHandler) TestByte(ctx context.Context, thing int8) (r int8, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestI32(thing int32) (r int32, err error) {
func (p *ThriftTestHandler) TestI32(ctx context.Context, thing int32) (r int32, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestI64(thing int64) (r int64, err error) {
func (p *ThriftTestHandler) TestI64(ctx context.Context, thing int64) (r int64, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestDouble(thing float64) (r float64, err error) {
func (p *ThriftTestHandler) TestDouble(ctx context.Context, thing float64) (r float64, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestBinary(thing []byte) (r []byte, err error) {
func (p *ThriftTestHandler) TestBinary(ctx context.Context, thing []byte) (r []byte, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestStruct(thing *thrifttest.Xtruct) (r *thrifttest.Xtruct, err error) {
func (p *ThriftTestHandler) TestStruct(ctx context.Context, thing *thrifttest.Xtruct) (r *thrifttest.Xtruct, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestNest(thing *thrifttest.Xtruct2) (r *thrifttest.Xtruct2, err error) {
func (p *ThriftTestHandler) TestNest(ctx context.Context, thing *thrifttest.Xtruct2) (r *thrifttest.Xtruct2, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestMap(thing map[int32]int32) (r map[int32]int32, err error) {
func (p *ThriftTestHandler) TestMap(ctx context.Context, thing map[int32]int32) (r map[int32]int32, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestStringMap(thing map[string]string) (r map[string]string, err error) {
func (p *ThriftTestHandler) TestStringMap(ctx context.Context, thing map[string]string) (r map[string]string, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestSet(thing []int32) (r []int32, err error) {
func (p *ThriftTestHandler) TestSet(ctx context.Context, thing []int32) (r []int32, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestList(thing []int32) (r []int32, err error) {
func (p *ThriftTestHandler) TestList(ctx context.Context, thing []int32) (r []int32, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestEnum(thing thrifttest.Numberz) (r thrifttest.Numberz, err error) {
func (p *ThriftTestHandler) TestEnum(ctx context.Context, thing thrifttest.Numberz) (r thrifttest.Numberz, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestTypedef(thing thrifttest.UserId) (r thrifttest.UserId, err error) {
func (p *ThriftTestHandler) TestTypedef(ctx context.Context, thing thrifttest.UserId) (r thrifttest.UserId, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestMapMap(hello int32) (r map[int32]map[int32]int32, err error) {
func (p *ThriftTestHandler) TestMapMap(ctx context.Context, hello int32) (r map[int32]map[int32]int32, err error) {
r = make(map[int32]map[int32]int32)
pos := make(map[int32]int32)
neg := make(map[int32]int32)
@@ -127,7 +131,7 @@ func (p *ThriftTestHandler) TestMapMap(hello int32) (r map[int32]map[int32]int32
return r, nil
}
func (p *ThriftTestHandler) TestInsanity(argument *thrifttest.Insanity) (r map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity, err error) {
func (p *ThriftTestHandler) TestInsanity(ctx context.Context, argument *thrifttest.Insanity) (r map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity, err error) {
hello := thrifttest.NewXtruct()
hello.StringThing = "Hello2"
hello.ByteThing = 2
@@ -162,7 +166,7 @@ func (p *ThriftTestHandler) TestInsanity(argument *thrifttest.Insanity) (r map[t
return insane, nil
}
func (p *ThriftTestHandler) TestMulti(arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 thrifttest.Numberz, arg5 thrifttest.UserId) (r *thrifttest.Xtruct, err error) {
func (p *ThriftTestHandler) TestMulti(ctx context.Context, arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 thrifttest.Numberz, arg5 thrifttest.UserId) (r *thrifttest.Xtruct, err error) {
r = thrifttest.NewXtruct()
r.StringThing = "Hello2"
r.ByteThing = arg0
@@ -171,7 +175,7 @@ func (p *ThriftTestHandler) TestMulti(arg0 int8, arg1 int32, arg2 int64, arg3 ma
return r, nil
}
func (p *ThriftTestHandler) TestException(arg string) (err error) {
func (p *ThriftTestHandler) TestException(ctx context.Context, arg string) (err error) {
if arg == "Xception" {
x := thrifttest.NewXception()
x.ErrorCode = 1001
@@ -184,7 +188,7 @@ func (p *ThriftTestHandler) TestException(arg string) (err error) {
}
}
func (p *ThriftTestHandler) TestMultiException(arg0 string, arg1 string) (r *thrifttest.Xtruct, err error) {
func (p *ThriftTestHandler) TestMultiException(ctx context.Context, arg0 string, arg1 string) (r *thrifttest.Xtruct, err error) {
if arg0 == "Xception" {
x := thrifttest.NewXception()
x.ErrorCode = 1001
@@ -203,7 +207,7 @@ func (p *ThriftTestHandler) TestMultiException(arg0 string, arg1 string) (r *thr
return res, nil
}
func (p *ThriftTestHandler) TestOneway(secondsToSleep int32) (err error) {
func (p *ThriftTestHandler) TestOneway(ctx context.Context, secondsToSleep int32) (err error) {
time.Sleep(time.Second * time.Duration(secondsToSleep))
return nil
}

View File

@@ -0,0 +1,212 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* 'License'); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package tests
import (
"context"
"errors"
"thrift"
"thrifttest"
"time"
)
type SecondServiceHandler struct {
}
func NewSecondServiceHandler() *SecondServiceHandler {
return &SecondServiceHandler{}
}
func (p *SecondServiceHandler) BlahBlah(ctx context.Context) (err error) {
return nil
}
func (p *SecondServiceHandler) SecondtestString(ctx context.Context, thing string) (r string, err error) {
return thing, nil
}
type ThriftTestHandler struct {
}
func NewThriftTestHandler() *ThriftTestHandler {
return &ThriftTestHandler{}
}
func (p *ThriftTestHandler) TestVoid(ctx context.Context) (err error) {
return nil
}
func (p *ThriftTestHandler) TestString(ctx context.Context, thing string) (r string, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestBool(ctx context.Context, thing bool) (r bool, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestByte(ctx context.Context, thing int8) (r int8, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestI32(ctx context.Context, thing int32) (r int32, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestI64(ctx context.Context, thing int64) (r int64, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestDouble(ctx context.Context, thing float64) (r float64, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestBinary(ctx context.Context, thing []byte) (r []byte, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestStruct(ctx context.Context, thing *thrifttest.Xtruct) (r *thrifttest.Xtruct, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestNest(ctx context.Context, thing *thrifttest.Xtruct2) (r *thrifttest.Xtruct2, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestMap(ctx context.Context, thing map[int32]int32) (r map[int32]int32, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestStringMap(ctx context.Context, thing map[string]string) (r map[string]string, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestSet(ctx context.Context, thing []int32) (r []int32, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestList(ctx context.Context, thing []int32) (r []int32, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestEnum(ctx context.Context, thing thrifttest.Numberz) (r thrifttest.Numberz, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestTypedef(ctx context.Context, thing thrifttest.UserId) (r thrifttest.UserId, err error) {
return thing, nil
}
func (p *ThriftTestHandler) TestMapMap(ctx context.Context, hello int32) (r map[int32]map[int32]int32, err error) {
r = make(map[int32]map[int32]int32)
pos := make(map[int32]int32)
neg := make(map[int32]int32)
for i := int32(1); i < 5; i++ {
pos[i] = i
neg[-i] = -i
}
r[4] = pos
r[-4] = neg
return r, nil
}
func (p *ThriftTestHandler) TestInsanity(ctx context.Context, argument *thrifttest.Insanity) (r map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity, err error) {
hello := thrifttest.NewXtruct()
hello.StringThing = "Hello2"
hello.ByteThing = 2
hello.I32Thing = 2
hello.I64Thing = 2
goodbye := thrifttest.NewXtruct()
goodbye.StringThing = "Goodbye4"
goodbye.ByteThing = 4
goodbye.I32Thing = 4
goodbye.I64Thing = 4
crazy := thrifttest.NewInsanity()
crazy.UserMap = make(map[thrifttest.Numberz]thrifttest.UserId)
crazy.UserMap[thrifttest.Numberz_EIGHT] = 8
crazy.UserMap[thrifttest.Numberz_FIVE] = 5
crazy.Xtructs = []*thrifttest.Xtruct{goodbye, hello}
first_map := make(map[thrifttest.Numberz]*thrifttest.Insanity)
second_map := make(map[thrifttest.Numberz]*thrifttest.Insanity)
first_map[thrifttest.Numberz_TWO] = crazy
first_map[thrifttest.Numberz_THREE] = crazy
looney := thrifttest.NewInsanity()
second_map[thrifttest.Numberz_SIX] = looney
var insane = make(map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity)
insane[1] = first_map
insane[2] = second_map
return insane, nil
}
func (p *ThriftTestHandler) TestMulti(ctx context.Context, arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 thrifttest.Numberz, arg5 thrifttest.UserId) (r *thrifttest.Xtruct, err error) {
r = thrifttest.NewXtruct()
r.StringThing = "Hello2"
r.ByteThing = arg0
r.I32Thing = arg1
r.I64Thing = arg2
return r, nil
}
func (p *ThriftTestHandler) TestException(ctx context.Context, arg string) (err error) {
if arg == "Xception" {
x := thrifttest.NewXception()
x.ErrorCode = 1001
x.Message = arg
return x
} else if arg == "TException" {
return thrift.TException(errors.New(arg))
} else {
return nil
}
}
func (p *ThriftTestHandler) TestMultiException(ctx context.Context, arg0 string, arg1 string) (r *thrifttest.Xtruct, err error) {
if arg0 == "Xception" {
x := thrifttest.NewXception()
x.ErrorCode = 1001
x.Message = "This is an Xception"
return nil, x
} else if arg0 == "Xception2" {
x2 := thrifttest.NewXception2()
x2.ErrorCode = 2002
x2.StructThing = thrifttest.NewXtruct()
x2.StructThing.StringThing = "This is an Xception2"
return nil, x2
}
res := thrifttest.NewXtruct()
res.StringThing = arg1
return res, nil
}
func (p *ThriftTestHandler) TestOneway(ctx context.Context, secondsToSleep int32) (err error) {
time.Sleep(time.Second * time.Duration(secondsToSleep))
return nil
}

View File

@@ -0,0 +1,32 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import "context"
type mockProcessor struct {
ProcessFunc func(in, out TProtocol) (bool, TException)
}
func (m *mockProcessor) Process(ctx context.Context, in, out TProtocol) (bool, TException) {
return m.ProcessFunc(in, out)
}

View File

@@ -0,0 +1,32 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import "golang.org/x/net/context"
type mockProcessor struct {
ProcessFunc func(in, out TProtocol) (bool, TException)
}
func (m *mockProcessor) Process(ctx context.Context, in, out TProtocol) (bool, TException) {
return m.ProcessFunc(in, out)
}

26
vendor/github.com/apache/thrift/lib/go/thrift/go17.go generated vendored Normal file
View File

@@ -0,0 +1,26 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import "context"
var defaultCtx = context.Background()

View File

@@ -21,36 +21,11 @@ package thrift
import (
"compress/gzip"
"context"
"io"
"net/http"
"strings"
)
// NewThriftHandlerFunc is a function that create a ready to use Apache Thrift Handler function
func NewThriftHandlerFunc(processor TProcessor,
inPfactory, outPfactory TProtocolFactory) func(w http.ResponseWriter, r *http.Request) {
return gz(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/x-thrift")
transport := NewStreamTransport(r.Body, w)
processor.Process(inPfactory.GetProtocol(transport), outPfactory.GetProtocol(transport))
})
}
// NewThriftHandlerFunc2 is same as NewThriftHandlerFunc but requires a Context as its first param.
func NewThriftHandlerFunc2(ctx context.Context, processor TProcessor2,
inPfactory, outPfactory TProtocolFactory) func(w http.ResponseWriter, r *http.Request) {
return gz(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/x-thrift")
transport := NewStreamTransport(r.Body, w)
processor.Process(ctx, inPfactory.GetProtocol(transport), outPfactory.GetProtocol(transport))
})
}
// gz transparently compresses the HTTP response if the client supports it.
func gz(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {

View File

@@ -0,0 +1,38 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import (
"net/http"
)
// NewThriftHandlerFunc is a function that create a ready to use Apache Thrift Handler function
func NewThriftHandlerFunc(processor TProcessor,
inPfactory, outPfactory TProtocolFactory) func(w http.ResponseWriter, r *http.Request) {
return gz(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/x-thrift")
transport := NewStreamTransport(r.Body, w)
processor.Process(r.Context(), inPfactory.GetProtocol(transport), outPfactory.GetProtocol(transport))
})
}

View File

@@ -0,0 +1,40 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import (
"net/http"
"golang.org/x/net/context"
)
// NewThriftHandlerFunc is a function that create a ready to use Apache Thrift Handler function
func NewThriftHandlerFunc(processor TProcessor,
inPfactory, outPfactory TProtocolFactory) func(w http.ResponseWriter, r *http.Request) {
return gz(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/x-thrift")
transport := NewStreamTransport(r.Body, w)
processor.Process(context.Background(), inPfactory.GetProtocol(transport), outPfactory.GetProtocol(transport))
})
}

View File

@@ -1,104 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import (
"context"
"fmt"
"strings"
)
/*
TMultiplexedProcessor2 is a TProcessor allowing
a single TServer to provide multiple services with
context support in TProcessor.
To do so, you instantiate the processor and then register additional
processors with it, as shown in the following example:
var processor = thrift.NewTMultiplexedProcessor2()
firstProcessor :=
processor.RegisterProcessor("FirstService", firstProcessor)
processor.registerProcessor(
"Calculator",
Calculator.NewCalculatorProcessor(&CalculatorHandler{}),
)
processor.registerProcessor(
"WeatherReport",
WeatherReport.NewWeatherReportProcessor(&WeatherReportHandler{}),
)
serverTransport, err := thrift.NewTServerSocketTimeout(addr, TIMEOUT)
if err != nil {
t.Fatal("Unable to create server socket", err)
}
server := thrift.NewTSimpleServer2(processor, serverTransport)
server.Serve();
*/
type TMultiplexedProcessor2 struct {
serviceProcessorMap map[string]TProcessor2
DefaultProcessor TProcessor2
}
func NewTMultiplexedProcessor2() *TMultiplexedProcessor2 {
return &TMultiplexedProcessor2{
serviceProcessorMap: make(map[string]TProcessor2),
}
}
func (t *TMultiplexedProcessor2) RegisterDefault(processor TProcessor2) {
t.DefaultProcessor = processor
}
func (t *TMultiplexedProcessor2) RegisterProcessor(name string, processor TProcessor2) {
if t.serviceProcessorMap == nil {
t.serviceProcessorMap = make(map[string]TProcessor2)
}
t.serviceProcessorMap[name] = processor
}
func (t *TMultiplexedProcessor2) Process(ctx context.Context, in, out TProtocol) (bool, TException) {
name, typeId, seqid, err := in.ReadMessageBegin()
if err != nil {
return false, err
}
if typeId != CALL && typeId != ONEWAY {
return false, fmt.Errorf("Unexpected message type %v", typeId)
}
//extract the service name
v := strings.SplitN(name, MULTIPLEXED_SEPARATOR, 2)
if len(v) != 2 {
if t.DefaultProcessor != nil {
smb := NewStoredMessageProtocol(in, name, typeId, seqid)
return t.DefaultProcessor.Process(ctx, smb, out)
}
return false, fmt.Errorf("Service name not found in message name: %s. Did you forget to use a TMultiplexProtocol in your client?", name)
}
actualProcessor, ok := t.serviceProcessorMap[v[0]]
if !ok {
return false, fmt.Errorf("Service name not found: %s. Did you forget to call registerProcessor()?", v[0])
}
smb := NewStoredMessageProtocol(in, v[1], typeId, seqid)
return actualProcessor.Process(ctx, smb, out)
}

View File

@@ -19,11 +19,6 @@
package thrift
import (
"fmt"
"strings"
)
/*
TMultiplexedProtocol is a protocol-independent concrete decorator
that allows a Thrift client to communicate with a multiplexing Thrift server,
@@ -76,11 +71,33 @@ func (t *TMultiplexedProtocol) WriteMessageBegin(name string, typeId TMessageTyp
}
/*
This is the non-context version for TProcessor.
TMultiplexedProcessor is a TProcessor allowing
a single TServer to provide multiple services.
See description at file: multiplexed_processor.go
To do so, you instantiate the processor and then register additional
processors with it, as shown in the following example:
Deprecated: use TMultiplexedProcessor2 for strong server programming.
var processor = thrift.NewTMultiplexedProcessor()
firstProcessor :=
processor.RegisterProcessor("FirstService", firstProcessor)
processor.registerProcessor(
"Calculator",
Calculator.NewCalculatorProcessor(&CalculatorHandler{}),
)
processor.registerProcessor(
"WeatherReport",
WeatherReport.NewWeatherReportProcessor(&WeatherReportHandler{}),
)
serverTransport, err := thrift.NewTServerSocketTimeout(addr, TIMEOUT)
if err != nil {
t.Fatal("Unable to create server socket", err)
}
server := thrift.NewTSimpleServer2(processor, serverTransport)
server.Serve();
*/
type TMultiplexedProcessor struct {
@@ -105,31 +122,6 @@ func (t *TMultiplexedProcessor) RegisterProcessor(name string, processor TProces
t.serviceProcessorMap[name] = processor
}
func (t *TMultiplexedProcessor) Process(in, out TProtocol) (bool, TException) {
name, typeId, seqid, err := in.ReadMessageBegin()
if err != nil {
return false, err
}
if typeId != CALL && typeId != ONEWAY {
return false, fmt.Errorf("Unexpected message type %v", typeId)
}
//extract the service name
v := strings.SplitN(name, MULTIPLEXED_SEPARATOR, 2)
if len(v) != 2 {
if t.DefaultProcessor != nil {
smb := NewStoredMessageProtocol(in, name, typeId, seqid)
return t.DefaultProcessor.Process(smb, out)
}
return false, fmt.Errorf("Service name not found in message name: %s. Did you forget to use a TMultiplexProtocol in your client?", name)
}
actualProcessor, ok := t.serviceProcessorMap[v[0]]
if !ok {
return false, fmt.Errorf("Service name not found: %s. Did you forget to call registerProcessor()?", v[0])
}
smb := NewStoredMessageProtocol(in, v[1], typeId, seqid)
return actualProcessor.Process(smb, out)
}
//Protocol that use stored message for ReadMessageBegin
type storedMessageProtocol struct {
TProtocol

View File

@@ -0,0 +1,53 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import (
"context"
"fmt"
"strings"
)
func (t *TMultiplexedProcessor) Process(ctx context.Context, in, out TProtocol) (bool, TException) {
name, typeId, seqid, err := in.ReadMessageBegin()
if err != nil {
return false, err
}
if typeId != CALL && typeId != ONEWAY {
return false, fmt.Errorf("Unexpected message type %v", typeId)
}
//extract the service name
v := strings.SplitN(name, MULTIPLEXED_SEPARATOR, 2)
if len(v) != 2 {
if t.DefaultProcessor != nil {
smb := NewStoredMessageProtocol(in, name, typeId, seqid)
return t.DefaultProcessor.Process(ctx, smb, out)
}
return false, fmt.Errorf("Service name not found in message name: %s. Did you forget to use a TMultiplexProtocol in your client?", name)
}
actualProcessor, ok := t.serviceProcessorMap[v[0]]
if !ok {
return false, fmt.Errorf("Service name not found: %s. Did you forget to call registerProcessor()?", v[0])
}
smb := NewStoredMessageProtocol(in, v[1], typeId, seqid)
return actualProcessor.Process(ctx, smb, out)
}

View File

@@ -0,0 +1,54 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import (
"fmt"
"strings"
"golang.org/x/net/context"
)
func (t *TMultiplexedProcessor) Process(ctx context.Context, in, out TProtocol) (bool, TException) {
name, typeId, seqid, err := in.ReadMessageBegin()
if err != nil {
return false, err
}
if typeId != CALL && typeId != ONEWAY {
return false, fmt.Errorf("Unexpected message type %v", typeId)
}
//extract the service name
v := strings.SplitN(name, MULTIPLEXED_SEPARATOR, 2)
if len(v) != 2 {
if t.DefaultProcessor != nil {
smb := NewStoredMessageProtocol(in, name, typeId, seqid)
return t.DefaultProcessor.Process(ctx, smb, out)
}
return false, fmt.Errorf("Service name not found in message name: %s. Did you forget to use a TMultiplexProtocol in your client?", name)
}
actualProcessor, ok := t.serviceProcessorMap[v[0]]
if !ok {
return false, fmt.Errorf("Service name not found: %s. Did you forget to call registerProcessor()?", v[0])
}
smb := NewStoredMessageProtocol(in, v[1], typeId, seqid)
return actualProcessor.Process(ctx, smb, out)
}

View File

@@ -0,0 +1,26 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import "golang.org/x/net/context"
var defaultCtx = context.Background()

View File

@@ -1,3 +1,5 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -19,23 +21,14 @@
package thrift
import "context"
import "golang.org/x/net/context"
// A processor is a generic object which operates upon an input stream and
// writes to some output stream.
type TProcessor interface {
Process(in, out TProtocol) (bool, TException)
}
type TProcessorFunction interface {
Process(seqId int32, in, out TProtocol) (bool, TException)
}
// TProcessor2 is TProcessor with ctx as its first argument.
type TProcessor2 interface {
Process(ctx context.Context, in, out TProtocol) (bool, TException)
}
type TProcessorFunction2 interface {
type TProcessorFunction interface {
Process(ctx context.Context, seqId int32, in, out TProtocol) (bool, TException)
}

View File

@@ -1,59 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
// The default processor2 factory just returns a singleton
// instance.
// The TProcessorFactory2 is a context version of the orignal.
type TProcessorFactory2 interface {
GetProcessor(trans TTransport) TProcessor2
}
type tProcessorFactory2 struct {
processor TProcessor2
}
func NewTProcessorFactory2(p TProcessor2) TProcessorFactory2 {
return &tProcessorFactory2{processor: p}
}
func (p *tProcessorFactory2) GetProcessor(trans TTransport) TProcessor2 {
return p.processor
}
/**
* The default processor factory2 just returns a singleton
* instance.
*/
type TProcessorFunctionFactory2 interface {
GetProcessorFunction(trans TTransport) TProcessorFunction2
}
type tProcessorFunctionFactory2 struct {
processor TProcessorFunction2
}
func NewTProcessorFunctionFactory2(p TProcessorFunction2) TProcessorFunctionFactory2 {
return &tProcessorFunctionFactory2{processor: p}
}
func (p *tProcessorFunctionFactory2) GetProcessorFunction(trans TTransport) TProcessorFunction2 {
return p.processor
}

View File

@@ -0,0 +1,34 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import "context"
// A processor is a generic object which operates upon an input stream and
// writes to some output stream.
type TProcessor interface {
Process(ctx context.Context, in, out TProtocol) (bool, TException)
}
type TProcessorFunction interface {
Process(ctx context.Context, seqId int32, in, out TProtocol) (bool, TException)
}

View File

@@ -33,19 +33,3 @@ type TServer interface {
// all servers are required to be cleanly stoppable.
Stop() error
}
// Same as TServer but use TProcessorFactory2 as processor factory.
type TServer2 interface {
ProcessorFactory() TProcessorFactory2
ServerTransport() TServerTransport
InputTransportFactory() TTransportFactory
OutputTransportFactory() TTransportFactory
InputProtocolFactory() TProtocolFactory
OutputProtocolFactory() TProtocolFactory
// Starts the server
Serve() error
// Stops the server. This is optional on a per-implementation basis. Not
// all servers are required to be cleanly stoppable.
Stop() error
}

View File

@@ -198,7 +198,7 @@ func (p *TSimpleServer) processRequests(client TTransport) error {
return nil
}
ok, err := processor.Process(inputProtocol, outputProtocol)
ok, err := processor.Process(defaultCtx, inputProtocol, outputProtocol)
if err, ok := err.(TTransportException); ok && err.TypeId() == END_OF_FILE {
return nil
} else if err != nil {

View File

@@ -1,180 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package thrift
import (
"context"
"log"
"runtime/debug"
"sync"
)
/*
* This is only a simple sample same as TSimpleServer but add context
* usage support.
*/
type TSimpleServer2 struct {
quit chan struct{}
processorFactory TProcessorFactory2
serverTransport TServerTransport
inputTransportFactory TTransportFactory
outputTransportFactory TTransportFactory
inputProtocolFactory TProtocolFactory
outputProtocolFactory TProtocolFactory
sync.WaitGroup
}
func NewTSimpleServerWithContext(processor TProcessor2, serverTransport TServerTransport) *TSimpleServer2 {
return NewTSimpleServerFactoryWithContext(NewTProcessorFactory2(processor), serverTransport)
}
func NewTSimpleServerFactoryWithContext(processorFactory TProcessorFactory2, serverTransport TServerTransport) *TSimpleServer2 {
return &TSimpleServer2{
quit: make(chan struct{}, 1),
processorFactory: processorFactory,
serverTransport: serverTransport,
inputTransportFactory: NewTTransportFactory(),
outputTransportFactory: NewTTransportFactory(),
inputProtocolFactory: NewTBinaryProtocolFactoryDefault(),
outputProtocolFactory: NewTBinaryProtocolFactoryDefault(),
}
}
func (p *TSimpleServer2) ProcessorFactory() TProcessorFactory2 {
return p.processorFactory
}
func (p *TSimpleServer2) ServerTransport() TServerTransport {
return p.serverTransport
}
func (p *TSimpleServer2) InputTransportFactory() TTransportFactory {
return p.inputTransportFactory
}
func (p *TSimpleServer2) OutputTransportFactory() TTransportFactory {
return p.outputTransportFactory
}
func (p *TSimpleServer2) InputProtocolFactory() TProtocolFactory {
return p.inputProtocolFactory
}
func (p *TSimpleServer2) OutputProtocolFactory() TProtocolFactory {
return p.outputProtocolFactory
}
func (p *TSimpleServer2) Listen() error {
return p.serverTransport.Listen()
}
func (p *TSimpleServer2) AcceptLoop() error {
for {
client, err := p.serverTransport.Accept()
if err != nil {
select {
case <-p.quit:
return nil
default:
}
return err
}
if client != nil {
p.Add(1)
go func() {
if err := p.processRequests(client); err != nil {
log.Println("error processing request:", err)
}
}()
}
}
}
func (p *TSimpleServer2) Serve() error {
err := p.Listen()
if err != nil {
return err
}
p.AcceptLoop()
return nil
}
var once2 sync.Once
func (p *TSimpleServer2) Stop() error {
q := func() {
close(p.quit)
p.serverTransport.Interrupt()
p.Wait()
}
once2.Do(q)
return nil
}
func (p *TSimpleServer2) processRequests(client TTransport) error {
defer p.Done()
processor := p.processorFactory.GetProcessor(client)
inputTransport, err := p.inputTransportFactory.GetTransport(client)
if err != nil {
return err
}
outputTransport, err := p.outputTransportFactory.GetTransport(client)
if err != nil {
return err
}
inputProtocol := p.inputProtocolFactory.GetProtocol(inputTransport)
outputProtocol := p.outputProtocolFactory.GetProtocol(outputTransport)
defer func() {
if e := recover(); e != nil {
log.Printf("panic in processor: %s: %s", e, debug.Stack())
}
}()
if inputTransport != nil {
defer inputTransport.Close()
}
if outputTransport != nil {
defer outputTransport.Close()
}
for {
select {
case <-p.quit:
return nil
default:
}
ctx := context.Background()
ok, err := processor.Process(ctx, inputProtocol, outputProtocol)
if err, ok := err.(TTransportException); ok && err.TypeId() == END_OF_FILE {
return nil
} else if err != nil {
return err
}
if err, ok := err.(TApplicationException); ok && err.TypeId() == UNKNOWN_METHOD {
continue
}
if !ok {
break
}
}
return nil
}

View File

@@ -24,14 +24,6 @@ import (
"time"
)
type mockProcessor struct {
ProcessFunc func(in, out TProtocol) (bool, TException)
}
func (m *mockProcessor) Process(in, out TProtocol) (bool, TException) {
return m.ProcessFunc(in, out)
}
type mockServerTransport struct {
ListenFunc func() error
AcceptFunc func() (TTransport, error)

View File

@@ -18,6 +18,7 @@
*/
namespace cpp yozone
namespace erl consts_
struct thing {
1: i32 hello,

View File

@@ -18,9 +18,12 @@
#
BUILT_SOURCES = gopath
if GOVERSION_LT_17
COMPILER_EXTRAFLAG=",legacy_context"
endif
THRIFT = $(top_builddir)/compiler/cpp/thrift
THRIFTCMD = $(THRIFT) -out src/gen --gen go:thrift_import=thrift
THRIFTCMD = $(THRIFT) -out src/gen --gen go:thrift_import=thrift$(COMPILER_EXTRAFLAG)
THRIFTTEST = $(top_srcdir)/test/ThriftTest.thrift
precross: bin/testclient bin/testserver
@@ -35,6 +38,7 @@ gopath: $(THRIFT) ThriftTest.thrift
$(THRIFTCMD) ../StressTest.thrift
ln -nfs ../../../lib/go/thrift src/thrift
GOPATH=`pwd` $(GO) get github.com/golang/mock/gomock
GOPATH=`pwd` $(GO) get golang.org/x/net/context
touch gopath
bin/testclient: gopath
@@ -51,7 +55,7 @@ clean-local:
check_PROGRAMS: bin/testclient bin/testserver bin/stress
check: gopath
check: gopath genmock
GOPATH=`pwd` $(GO) test -v common/...
genmock: gopath

View File

@@ -0,0 +1,62 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package main
import (
"context"
"sync/atomic"
)
type handler struct{}
func (h *handler) EchoVoid(ctx context.Context) (err error) {
atomic.AddInt64(&counter, 1)
return nil
}
func (h *handler) EchoByte(ctx context.Context, arg int8) (r int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoI32(ctx context.Context, arg int32) (r int32, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoI64(ctx context.Context, arg int64) (r int64, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoString(ctx context.Context, arg string) (r string, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoList(ctx context.Context, arg []int8) (r []int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoSet(ctx context.Context, arg map[int8]struct{}) (r map[int8]struct{}, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoMap(ctx context.Context, arg map[int8]int8) (r map[int8]int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}

View File

@@ -216,38 +216,3 @@ func client(protocolFactory thrift.TProtocolFactory) {
done.Done()
}
type handler struct{}
func (h *handler) EchoVoid() (err error) {
atomic.AddInt64(&counter, 1)
return nil
}
func (h *handler) EchoByte(arg int8) (r int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoI32(arg int32) (r int32, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoI64(arg int64) (r int64, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoString(arg string) (r string, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoList(arg []int8) (r []int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoSet(arg map[int8]struct{}) (r map[int8]struct{}, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoMap(arg map[int8]int8) (r map[int8]int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}

View File

@@ -0,0 +1,63 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package main
import (
"sync/atomic"
"golang.org/x/net/context"
)
type handler struct{}
func (h *handler) EchoVoid(ctx context.Context) (err error) {
atomic.AddInt64(&counter, 1)
return nil
}
func (h *handler) EchoByte(ctx context.Context, arg int8) (r int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoI32(ctx context.Context, arg int32) (r int32, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoI64(ctx context.Context, arg int64) (r int64, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoString(ctx context.Context, arg string) (r string, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoList(ctx context.Context, arg []int8) (r []int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoSet(ctx context.Context, arg map[int8]struct{}) (r map[int8]struct{}, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}
func (h *handler) EchoMap(ctx context.Context, arg map[int8]int8) (r map[int8]int8, err error) {
atomic.AddInt64(&counter, 1)
return arg, nil
}

View File

@@ -0,0 +1,26 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package main
import "context"
var defaultCtx = context.Background()

View File

@@ -63,11 +63,11 @@ var xcept = &thrifttest.Xception{ErrorCode: 1001, Message: "Xception"}
func callEverything(client *thrifttest.ThriftTestClient) {
var err error
if err = client.TestVoid(); err != nil {
if err = client.TestVoid(defaultCtx); err != nil {
t.Fatalf("Unexpected error in TestVoid() call: ", err)
}
thing, err := client.TestString("thing")
thing, err := client.TestString(defaultCtx, "thing")
if err != nil {
t.Fatalf("Unexpected error in TestString() call: ", err)
}
@@ -75,14 +75,14 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestString() result, expected 'thing' got '%s' ", thing)
}
bl, err := client.TestBool(true)
bl, err := client.TestBool(defaultCtx, true)
if err != nil {
t.Fatalf("Unexpected error in TestBool() call: ", err)
}
if !bl {
t.Fatalf("Unexpected TestBool() result expected true, got %f ", bl)
}
bl, err = client.TestBool(false)
bl, err = client.TestBool(defaultCtx, false)
if err != nil {
t.Fatalf("Unexpected error in TestBool() call: ", err)
}
@@ -90,7 +90,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestBool() result expected false, got %f ", bl)
}
b, err := client.TestByte(42)
b, err := client.TestByte(defaultCtx, 42)
if err != nil {
t.Fatalf("Unexpected error in TestByte() call: ", err)
}
@@ -98,7 +98,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestByte() result expected 42, got %d ", b)
}
i32, err := client.TestI32(4242)
i32, err := client.TestI32(defaultCtx, 4242)
if err != nil {
t.Fatalf("Unexpected error in TestI32() call: ", err)
}
@@ -106,7 +106,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestI32() result expected 4242, got %d ", i32)
}
i64, err := client.TestI64(424242)
i64, err := client.TestI64(defaultCtx, 424242)
if err != nil {
t.Fatalf("Unexpected error in TestI64() call: ", err)
}
@@ -114,7 +114,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestI64() result expected 424242, got %d ", i64)
}
d, err := client.TestDouble(42.42)
d, err := client.TestDouble(defaultCtx, 42.42)
if err != nil {
t.Fatalf("Unexpected error in TestDouble() call: ", err)
}
@@ -126,19 +126,19 @@ func callEverything(client *thrifttest.ThriftTestClient) {
for i := 0; i < 256; i++ {
binout[i] = byte(i)
}
bin, err := client.TestBinary(binout)
bin, err := client.TestBinary(defaultCtx, binout)
for i := 0; i < 256; i++ {
if (binout[i] != bin[i]) {
t.Fatalf("Unexpected TestBinary() result expected %d, got %d ", binout[i], bin[i])
}
}
xs := thrifttest.NewXtruct()
xs.StringThing = "thing"
xs.ByteThing = 42
xs.I32Thing = 4242
xs.I64Thing = 424242
xsret, err := client.TestStruct(xs)
xsret, err := client.TestStruct(defaultCtx, xs)
if err != nil {
t.Fatalf("Unexpected error in TestStruct() call: ", err)
}
@@ -148,7 +148,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
x2 := thrifttest.NewXtruct2()
x2.StructThing = xs
x2ret, err := client.TestNest(x2)
x2ret, err := client.TestNest(defaultCtx, x2)
if err != nil {
t.Fatalf("Unexpected error in TestNest() call: ", err)
}
@@ -157,7 +157,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
}
m := map[int32]int32{1: 2, 3: 4, 5: 42}
mret, err := client.TestMap(m)
mret, err := client.TestMap(defaultCtx, m)
if err != nil {
t.Fatalf("Unexpected error in TestMap() call: ", err)
}
@@ -166,7 +166,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
}
sm := map[string]string{"a": "2", "b": "blah", "some": "thing"}
smret, err := client.TestStringMap(sm)
smret, err := client.TestStringMap(defaultCtx, sm)
if err != nil {
t.Fatalf("Unexpected error in TestStringMap() call: ", err)
}
@@ -175,7 +175,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
}
s := []int32{1, 2, 42}
sret, err := client.TestSet(s)
sret, err := client.TestSet(defaultCtx, s)
if err != nil {
t.Fatalf("Unexpected error in TestSet() call: ", err)
}
@@ -191,7 +191,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
}
l := []int32{1, 2, 42}
lret, err := client.TestList(l)
lret, err := client.TestList(defaultCtx, l)
if err != nil {
t.Fatalf("Unexpected error in TestList() call: ", err)
}
@@ -199,7 +199,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestList() result expected %#v, got %#v ", l, lret)
}
eret, err := client.TestEnum(thrifttest.Numberz_TWO)
eret, err := client.TestEnum(defaultCtx, thrifttest.Numberz_TWO)
if err != nil {
t.Fatalf("Unexpected error in TestEnum() call: ", err)
}
@@ -207,7 +207,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestEnum() result expected %#v, got %#v ", thrifttest.Numberz_TWO, eret)
}
tret, err := client.TestTypedef(thrifttest.UserId(42))
tret, err := client.TestTypedef(defaultCtx, thrifttest.UserId(42))
if err != nil {
t.Fatalf("Unexpected error in TestTypedef() call: ", err)
}
@@ -215,7 +215,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestTypedef() result expected %#v, got %#v ", thrifttest.UserId(42), tret)
}
mapmap, err := client.TestMapMap(42)
mapmap, err := client.TestMapMap(defaultCtx, 42)
if err != nil {
t.Fatalf("Unexpected error in TestMapMap() call: ", err)
}
@@ -242,7 +242,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
truck1,
truck2,
}
insanity, err := client.TestInsanity(crazy)
insanity, err := client.TestInsanity(defaultCtx, crazy)
if err != nil {
t.Fatalf("Unexpected error in TestInsanity() call: ", err)
}
@@ -261,7 +261,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
insanity[2][6])
}
xxsret, err := client.TestMulti(42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24))
xxsret, err := client.TestMulti(defaultCtx, 42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24))
if err != nil {
t.Fatalf("Unexpected error in TestMulti() call: ", err)
}
@@ -269,7 +269,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestMulti() result expected %#v, got %#v ", xxs, xxsret)
}
err = client.TestException("Xception")
err = client.TestException(defaultCtx, "Xception")
if err == nil {
t.Fatalf("Expecting exception in TestException() call")
}
@@ -277,13 +277,13 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestException() result expected %#v, got %#v ", xcept, err)
}
err = client.TestException("TException")
err = client.TestException(defaultCtx, "TException")
_, ok := err.(thrift.TApplicationException)
if err == nil || !ok {
t.Fatalf("Unexpected TestException() result expected ApplicationError, got %#v ", err)
}
ign, err := client.TestMultiException("Xception", "ignoreme")
ign, err := client.TestMultiException(defaultCtx, "Xception", "ignoreme")
if ign != nil || err == nil {
t.Fatalf("Expecting exception in TestMultiException() call")
}
@@ -291,7 +291,7 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestMultiException() %#v ", err)
}
ign, err = client.TestMultiException("Xception2", "ignoreme")
ign, err = client.TestMultiException(defaultCtx, "Xception2", "ignoreme")
if ign != nil || err == nil {
t.Fatalf("Expecting exception in TestMultiException() call")
}
@@ -301,13 +301,13 @@ func callEverything(client *thrifttest.ThriftTestClient) {
t.Fatalf("Unexpected TestMultiException() %#v ", err)
}
err = client.TestOneway(2)
err = client.TestOneway(defaultCtx, 2)
if err != nil {
t.Fatalf("Unexpected error in TestOneway() call: ", err)
}
//Make sure the connection still alive
if err = client.TestVoid(); err != nil {
if err = client.TestVoid(defaultCtx); err != nil {
t.Fatalf("Unexpected error in TestVoid() call: ", err)
}
}

View File

@@ -0,0 +1,26 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package main
import "golang.org/x/net/context"
var defaultCtx = context.Background()

View File

@@ -92,39 +92,39 @@ var xcept = &thrifttest.Xception{ErrorCode: 1001, Message: "some"}
func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, handler *MockThriftTest) {
gomock.InOrder(
handler.EXPECT().TestVoid(),
handler.EXPECT().TestString("thing").Return("thing", nil),
handler.EXPECT().TestBool(true).Return(true, nil),
handler.EXPECT().TestBool(false).Return(false, nil),
handler.EXPECT().TestByte(int8(42)).Return(int8(42), nil),
handler.EXPECT().TestI32(int32(4242)).Return(int32(4242), nil),
handler.EXPECT().TestI64(int64(424242)).Return(int64(424242), nil),
handler.EXPECT().TestVoid(gomock.Any()),
handler.EXPECT().TestString(gomock.Any(), "thing").Return("thing", nil),
handler.EXPECT().TestBool(gomock.Any(), true).Return(true, nil),
handler.EXPECT().TestBool(gomock.Any(), false).Return(false, nil),
handler.EXPECT().TestByte(gomock.Any(), int8(42)).Return(int8(42), nil),
handler.EXPECT().TestI32(gomock.Any(), int32(4242)).Return(int32(4242), nil),
handler.EXPECT().TestI64(gomock.Any(), int64(424242)).Return(int64(424242), nil),
// TODO: add TestBinary()
handler.EXPECT().TestDouble(float64(42.42)).Return(float64(42.42), nil),
handler.EXPECT().TestStruct(&thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}).Return(&thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}, nil),
handler.EXPECT().TestNest(&thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}).Return(&thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}, nil),
handler.EXPECT().TestMap(map[int32]int32{1: 2, 3: 4, 5: 42}).Return(map[int32]int32{1: 2, 3: 4, 5: 42}, nil),
handler.EXPECT().TestStringMap(map[string]string{"a": "2", "b": "blah", "some": "thing"}).Return(map[string]string{"a": "2", "b": "blah", "some": "thing"}, nil),
handler.EXPECT().TestSet([]int32{1, 2, 42}).Return([]int32{1, 2, 42}, nil),
handler.EXPECT().TestList([]int32{1, 2, 42}).Return([]int32{1, 2, 42}, nil),
handler.EXPECT().TestEnum(thrifttest.Numberz_TWO).Return(thrifttest.Numberz_TWO, nil),
handler.EXPECT().TestTypedef(thrifttest.UserId(42)).Return(thrifttest.UserId(42), nil),
handler.EXPECT().TestMapMap(int32(42)).Return(rmapmap, nil),
handler.EXPECT().TestDouble(gomock.Any(), float64(42.42)).Return(float64(42.42), nil),
handler.EXPECT().TestStruct(gomock.Any(), &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}).Return(&thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}, nil),
handler.EXPECT().TestNest(gomock.Any(), &thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}).Return(&thrifttest.Xtruct2{StructThing: &thrifttest.Xtruct{StringThing: "thing", ByteThing: 42, I32Thing: 4242, I64Thing: 424242}}, nil),
handler.EXPECT().TestMap(gomock.Any(), map[int32]int32{1: 2, 3: 4, 5: 42}).Return(map[int32]int32{1: 2, 3: 4, 5: 42}, nil),
handler.EXPECT().TestStringMap(gomock.Any(), map[string]string{"a": "2", "b": "blah", "some": "thing"}).Return(map[string]string{"a": "2", "b": "blah", "some": "thing"}, nil),
handler.EXPECT().TestSet(gomock.Any(), []int32{1, 2, 42}).Return([]int32{1, 2, 42}, nil),
handler.EXPECT().TestList(gomock.Any(), []int32{1, 2, 42}).Return([]int32{1, 2, 42}, nil),
handler.EXPECT().TestEnum(gomock.Any(), thrifttest.Numberz_TWO).Return(thrifttest.Numberz_TWO, nil),
handler.EXPECT().TestTypedef(gomock.Any(), thrifttest.UserId(42)).Return(thrifttest.UserId(42), nil),
handler.EXPECT().TestMapMap(gomock.Any(), int32(42)).Return(rmapmap, nil),
// TODO: not testing insanity
handler.EXPECT().TestMulti(int8(42), int32(4242), int64(424242), map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24)).Return(xxs, nil),
handler.EXPECT().TestException("some").Return(xcept),
handler.EXPECT().TestException("TException").Return(errors.New("Just random exception")),
handler.EXPECT().TestMultiException("Xception", "ignoreme").Return(nil, &thrifttest.Xception{ErrorCode: 1001, Message: "This is an Xception"}),
handler.EXPECT().TestMultiException("Xception2", "ignoreme").Return(nil, &thrifttest.Xception2{ErrorCode: 2002, StructThing: &thrifttest.Xtruct{StringThing: "This is an Xception2"}}),
handler.EXPECT().TestOneway(int32(2)).Return(nil),
handler.EXPECT().TestVoid(),
handler.EXPECT().TestMulti(gomock.Any(), int8(42), int32(4242), int64(424242), map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24)).Return(xxs, nil),
handler.EXPECT().TestException(gomock.Any(), "some").Return(xcept),
handler.EXPECT().TestException(gomock.Any(), "TException").Return(errors.New("Just random exception")),
handler.EXPECT().TestMultiException(gomock.Any(), "Xception", "ignoreme").Return(nil, &thrifttest.Xception{ErrorCode: 1001, Message: "This is an Xception"}),
handler.EXPECT().TestMultiException(gomock.Any(), "Xception2", "ignoreme").Return(nil, &thrifttest.Xception2{ErrorCode: 2002, StructThing: &thrifttest.Xtruct{StringThing: "This is an Xception2"}}),
handler.EXPECT().TestOneway(gomock.Any(), int32(2)).Return(nil),
handler.EXPECT().TestVoid(gomock.Any()),
)
var err error
if err = client.TestVoid(); err != nil {
if err = client.TestVoid(defaultCtx); err != nil {
t.Errorf("Unexpected error in TestVoid() call: ", err)
}
thing, err := client.TestString("thing")
thing, err := client.TestString(defaultCtx, "thing")
if err != nil {
t.Errorf("Unexpected error in TestString() call: ", err)
}
@@ -132,14 +132,14 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestString() result, expected 'thing' got '%s' ", thing)
}
bl, err := client.TestBool(true)
bl, err := client.TestBool(defaultCtx, true)
if err != nil {
t.Errorf("Unexpected error in TestBool() call: ", err)
}
if !bl {
t.Errorf("Unexpected TestBool() result expected true, got %f ", bl)
}
bl, err = client.TestBool(false)
bl, err = client.TestBool(defaultCtx, false)
if err != nil {
t.Errorf("Unexpected error in TestBool() call: ", err)
}
@@ -147,7 +147,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestBool() result expected false, got %f ", bl)
}
b, err := client.TestByte(42)
b, err := client.TestByte(defaultCtx, 42)
if err != nil {
t.Errorf("Unexpected error in TestByte() call: ", err)
}
@@ -155,7 +155,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestByte() result expected 42, got %d ", b)
}
i32, err := client.TestI32(4242)
i32, err := client.TestI32(defaultCtx, 4242)
if err != nil {
t.Errorf("Unexpected error in TestI32() call: ", err)
}
@@ -163,7 +163,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestI32() result expected 4242, got %d ", i32)
}
i64, err := client.TestI64(424242)
i64, err := client.TestI64(defaultCtx, 424242)
if err != nil {
t.Errorf("Unexpected error in TestI64() call: ", err)
}
@@ -171,7 +171,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestI64() result expected 424242, got %d ", i64)
}
d, err := client.TestDouble(42.42)
d, err := client.TestDouble(defaultCtx, 42.42)
if err != nil {
t.Errorf("Unexpected error in TestDouble() call: ", err)
}
@@ -186,7 +186,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
xs.ByteThing = 42
xs.I32Thing = 4242
xs.I64Thing = 424242
xsret, err := client.TestStruct(xs)
xsret, err := client.TestStruct(defaultCtx, xs)
if err != nil {
t.Errorf("Unexpected error in TestStruct() call: ", err)
}
@@ -196,7 +196,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
x2 := thrifttest.NewXtruct2()
x2.StructThing = xs
x2ret, err := client.TestNest(x2)
x2ret, err := client.TestNest(defaultCtx, x2)
if err != nil {
t.Errorf("Unexpected error in TestNest() call: ", err)
}
@@ -205,7 +205,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
}
m := map[int32]int32{1: 2, 3: 4, 5: 42}
mret, err := client.TestMap(m)
mret, err := client.TestMap(defaultCtx, m)
if err != nil {
t.Errorf("Unexpected error in TestMap() call: ", err)
}
@@ -214,7 +214,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
}
sm := map[string]string{"a": "2", "b": "blah", "some": "thing"}
smret, err := client.TestStringMap(sm)
smret, err := client.TestStringMap(defaultCtx, sm)
if err != nil {
t.Errorf("Unexpected error in TestStringMap() call: ", err)
}
@@ -223,7 +223,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
}
s := []int32{1, 2, 42}
sret, err := client.TestSet(s)
sret, err := client.TestSet(defaultCtx, s)
if err != nil {
t.Errorf("Unexpected error in TestSet() call: ", err)
}
@@ -239,7 +239,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
}
l := []int32{1, 2, 42}
lret, err := client.TestList(l)
lret, err := client.TestList(defaultCtx, l)
if err != nil {
t.Errorf("Unexpected error in TestList() call: ", err)
}
@@ -247,7 +247,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestList() result expected %#v, got %#v ", l, lret)
}
eret, err := client.TestEnum(thrifttest.Numberz_TWO)
eret, err := client.TestEnum(defaultCtx, thrifttest.Numberz_TWO)
if err != nil {
t.Errorf("Unexpected error in TestEnum() call: ", err)
}
@@ -255,7 +255,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestEnum() result expected %#v, got %#v ", thrifttest.Numberz_TWO, eret)
}
tret, err := client.TestTypedef(thrifttest.UserId(42))
tret, err := client.TestTypedef(defaultCtx, thrifttest.UserId(42))
if err != nil {
t.Errorf("Unexpected error in TestTypedef() call: ", err)
}
@@ -263,7 +263,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestTypedef() result expected %#v, got %#v ", thrifttest.UserId(42), tret)
}
mapmap, err := client.TestMapMap(42)
mapmap, err := client.TestMapMap(defaultCtx, 42)
if err != nil {
t.Errorf("Unexpected error in TestMapmap() call: ", err)
}
@@ -271,7 +271,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestMapmap() result expected %#v, got %#v ", rmapmap, mapmap)
}
xxsret, err := client.TestMulti(42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24))
xxsret, err := client.TestMulti(defaultCtx, 42, 4242, 424242, map[int16]string{1: "blah", 2: "thing"}, thrifttest.Numberz_EIGHT, thrifttest.UserId(24))
if err != nil {
t.Errorf("Unexpected error in TestMulti() call: ", err)
}
@@ -279,7 +279,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestMulti() result expected %#v, got %#v ", xxs, xxsret)
}
err = client.TestException("some")
err = client.TestException(defaultCtx, "some")
if err == nil {
t.Errorf("Expecting exception in TestException() call")
}
@@ -288,13 +288,13 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
}
// TODO: connection is being closed on this
err = client.TestException("TException")
err = client.TestException(defaultCtx, "TException")
tex, ok := err.(thrift.TApplicationException)
if err == nil || !ok || tex.TypeId() != thrift.INTERNAL_ERROR {
t.Errorf("Unexpected TestException() result expected ApplicationError, got %#v ", err)
}
ign, err := client.TestMultiException("Xception", "ignoreme")
ign, err := client.TestMultiException(defaultCtx, "Xception", "ignoreme")
if ign != nil || err == nil {
t.Errorf("Expecting exception in TestMultiException() call")
}
@@ -302,7 +302,7 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestMultiException() %#v ", err)
}
ign, err = client.TestMultiException("Xception2", "ignoreme")
ign, err = client.TestMultiException(defaultCtx, "Xception2", "ignoreme")
if ign != nil || err == nil {
t.Errorf("Expecting exception in TestMultiException() call")
}
@@ -312,13 +312,13 @@ func callEverythingWithMock(t *testing.T, client *thrifttest.ThriftTestClient, h
t.Errorf("Unexpected TestMultiException() %#v ", err)
}
err = client.TestOneway(2)
err = client.TestOneway(defaultCtx, 2)
if err != nil {
t.Errorf("Unexpected error in TestOneway() call: ", err)
}
//Make sure the connection still alive
if err = client.TestVoid(); err != nil {
if err = client.TestVoid(defaultCtx); err != nil {
t.Errorf("Unexpected error in TestVoid() call: ", err)
}
}

View File

@@ -0,0 +1,26 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package common
import "context"
var defaultCtx = context.Background()

View File

@@ -23,267 +23,313 @@
package common
import (
gomock "github.com/golang/mock/gomock"
thrifttest "gen/thrifttest"
gomock "github.com/golang/mock/gomock"
context "golang.org/x/net/context"
)
// Mock of ThriftTest interface
// MockThriftTest is a mock of ThriftTest interface
type MockThriftTest struct {
ctrl *gomock.Controller
recorder *_MockThriftTestRecorder
recorder *MockThriftTestMockRecorder
}
// Recorder for MockThriftTest (not exported)
type _MockThriftTestRecorder struct {
// MockThriftTestMockRecorder is the mock recorder for MockThriftTest
type MockThriftTestMockRecorder struct {
mock *MockThriftTest
}
// NewMockThriftTest creates a new mock instance
func NewMockThriftTest(ctrl *gomock.Controller) *MockThriftTest {
mock := &MockThriftTest{ctrl: ctrl}
mock.recorder = &_MockThriftTestRecorder{mock}
mock.recorder = &MockThriftTestMockRecorder{mock}
return mock
}
func (_m *MockThriftTest) EXPECT() *_MockThriftTestRecorder {
// EXPECT returns an object that allows the caller to indicate expected use
func (_m *MockThriftTest) EXPECT() *MockThriftTestMockRecorder {
return _m.recorder
}
func (_m *MockThriftTest) TestBool(_param0 bool) (bool, error) {
ret := _m.ctrl.Call(_m, "TestBool", _param0)
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestBool(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestBool", arg0)
}
func (_m *MockThriftTest) TestByte(_param0 int8) (int8, error) {
ret := _m.ctrl.Call(_m, "TestByte", _param0)
ret0, _ := ret[0].(int8)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestByte(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestByte", arg0)
}
func (_m *MockThriftTest) TestDouble(_param0 float64) (float64, error) {
ret := _m.ctrl.Call(_m, "TestDouble", _param0)
ret0, _ := ret[0].(float64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestDouble(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestDouble", arg0)
}
func (_m *MockThriftTest) TestBinary(_param0 []byte) ([]byte, error) {
ret := _m.ctrl.Call(_m, "TestBinary", _param0)
// TestBinary mocks base method
func (_m *MockThriftTest) TestBinary(_param0 context.Context, _param1 []byte) ([]byte, error) {
ret := _m.ctrl.Call(_m, "TestBinary", _param0, _param1)
ret0, _ := ret[0].([]byte)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestBinary(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestBinary", arg0)
// TestBinary indicates an expected call of TestBinary
func (_mr *MockThriftTestMockRecorder) TestBinary(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestBinary", arg0, arg1)
}
func (_m *MockThriftTest) TestEnum(_param0 thrifttest.Numberz) (thrifttest.Numberz, error) {
ret := _m.ctrl.Call(_m, "TestEnum", _param0)
// TestBool mocks base method
func (_m *MockThriftTest) TestBool(_param0 context.Context, _param1 bool) (bool, error) {
ret := _m.ctrl.Call(_m, "TestBool", _param0, _param1)
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TestBool indicates an expected call of TestBool
func (_mr *MockThriftTestMockRecorder) TestBool(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestBool", arg0, arg1)
}
// TestByte mocks base method
func (_m *MockThriftTest) TestByte(_param0 context.Context, _param1 int8) (int8, error) {
ret := _m.ctrl.Call(_m, "TestByte", _param0, _param1)
ret0, _ := ret[0].(int8)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TestByte indicates an expected call of TestByte
func (_mr *MockThriftTestMockRecorder) TestByte(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestByte", arg0, arg1)
}
// TestDouble mocks base method
func (_m *MockThriftTest) TestDouble(_param0 context.Context, _param1 float64) (float64, error) {
ret := _m.ctrl.Call(_m, "TestDouble", _param0, _param1)
ret0, _ := ret[0].(float64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TestDouble indicates an expected call of TestDouble
func (_mr *MockThriftTestMockRecorder) TestDouble(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestDouble", arg0, arg1)
}
// TestEnum mocks base method
func (_m *MockThriftTest) TestEnum(_param0 context.Context, _param1 thrifttest.Numberz) (thrifttest.Numberz, error) {
ret := _m.ctrl.Call(_m, "TestEnum", _param0, _param1)
ret0, _ := ret[0].(thrifttest.Numberz)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestEnum(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestEnum", arg0)
// TestEnum indicates an expected call of TestEnum
func (_mr *MockThriftTestMockRecorder) TestEnum(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestEnum", arg0, arg1)
}
func (_m *MockThriftTest) TestException(_param0 string) error {
ret := _m.ctrl.Call(_m, "TestException", _param0)
// TestException mocks base method
func (_m *MockThriftTest) TestException(_param0 context.Context, _param1 string) error {
ret := _m.ctrl.Call(_m, "TestException", _param0, _param1)
ret0, _ := ret[0].(error)
return ret0
}
func (_mr *_MockThriftTestRecorder) TestException(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestException", arg0)
// TestException indicates an expected call of TestException
func (_mr *MockThriftTestMockRecorder) TestException(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestException", arg0, arg1)
}
func (_m *MockThriftTest) TestI32(_param0 int32) (int32, error) {
ret := _m.ctrl.Call(_m, "TestI32", _param0)
// TestI32 mocks base method
func (_m *MockThriftTest) TestI32(_param0 context.Context, _param1 int32) (int32, error) {
ret := _m.ctrl.Call(_m, "TestI32", _param0, _param1)
ret0, _ := ret[0].(int32)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestI32(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestI32", arg0)
// TestI32 indicates an expected call of TestI32
func (_mr *MockThriftTestMockRecorder) TestI32(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestI32", arg0, arg1)
}
func (_m *MockThriftTest) TestI64(_param0 int64) (int64, error) {
ret := _m.ctrl.Call(_m, "TestI64", _param0)
// TestI64 mocks base method
func (_m *MockThriftTest) TestI64(_param0 context.Context, _param1 int64) (int64, error) {
ret := _m.ctrl.Call(_m, "TestI64", _param0, _param1)
ret0, _ := ret[0].(int64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestI64(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestI64", arg0)
// TestI64 indicates an expected call of TestI64
func (_mr *MockThriftTestMockRecorder) TestI64(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestI64", arg0, arg1)
}
func (_m *MockThriftTest) TestInsanity(_param0 *thrifttest.Insanity) (map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity, error) {
ret := _m.ctrl.Call(_m, "TestInsanity", _param0)
// TestInsanity mocks base method
func (_m *MockThriftTest) TestInsanity(_param0 context.Context, _param1 *thrifttest.Insanity) (map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity, error) {
ret := _m.ctrl.Call(_m, "TestInsanity", _param0, _param1)
ret0, _ := ret[0].(map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestInsanity(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestInsanity", arg0)
// TestInsanity indicates an expected call of TestInsanity
func (_mr *MockThriftTestMockRecorder) TestInsanity(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestInsanity", arg0, arg1)
}
func (_m *MockThriftTest) TestList(_param0 []int32) ([]int32, error) {
ret := _m.ctrl.Call(_m, "TestList", _param0)
// TestList mocks base method
func (_m *MockThriftTest) TestList(_param0 context.Context, _param1 []int32) ([]int32, error) {
ret := _m.ctrl.Call(_m, "TestList", _param0, _param1)
ret0, _ := ret[0].([]int32)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestList(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestList", arg0)
// TestList indicates an expected call of TestList
func (_mr *MockThriftTestMockRecorder) TestList(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestList", arg0, arg1)
}
func (_m *MockThriftTest) TestMap(_param0 map[int32]int32) (map[int32]int32, error) {
ret := _m.ctrl.Call(_m, "TestMap", _param0)
// TestMap mocks base method
func (_m *MockThriftTest) TestMap(_param0 context.Context, _param1 map[int32]int32) (map[int32]int32, error) {
ret := _m.ctrl.Call(_m, "TestMap", _param0, _param1)
ret0, _ := ret[0].(map[int32]int32)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestMap(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMap", arg0)
// TestMap indicates an expected call of TestMap
func (_mr *MockThriftTestMockRecorder) TestMap(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMap", arg0, arg1)
}
func (_m *MockThriftTest) TestMapMap(_param0 int32) (map[int32]map[int32]int32, error) {
ret := _m.ctrl.Call(_m, "TestMapMap", _param0)
// TestMapMap mocks base method
func (_m *MockThriftTest) TestMapMap(_param0 context.Context, _param1 int32) (map[int32]map[int32]int32, error) {
ret := _m.ctrl.Call(_m, "TestMapMap", _param0, _param1)
ret0, _ := ret[0].(map[int32]map[int32]int32)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestMapMap(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMapMap", arg0)
// TestMapMap indicates an expected call of TestMapMap
func (_mr *MockThriftTestMockRecorder) TestMapMap(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMapMap", arg0, arg1)
}
func (_m *MockThriftTest) TestMulti(_param0 int8, _param1 int32, _param2 int64, _param3 map[int16]string, _param4 thrifttest.Numberz, _param5 thrifttest.UserId) (*thrifttest.Xtruct, error) {
ret := _m.ctrl.Call(_m, "TestMulti", _param0, _param1, _param2, _param3, _param4, _param5)
// TestMulti mocks base method
func (_m *MockThriftTest) TestMulti(_param0 context.Context, _param1 int8, _param2 int32, _param3 int64, _param4 map[int16]string, _param5 thrifttest.Numberz, _param6 thrifttest.UserId) (*thrifttest.Xtruct, error) {
ret := _m.ctrl.Call(_m, "TestMulti", _param0, _param1, _param2, _param3, _param4, _param5, _param6)
ret0, _ := ret[0].(*thrifttest.Xtruct)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestMulti(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMulti", arg0, arg1, arg2, arg3, arg4, arg5)
// TestMulti indicates an expected call of TestMulti
func (_mr *MockThriftTestMockRecorder) TestMulti(arg0, arg1, arg2, arg3, arg4, arg5, arg6 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMulti", arg0, arg1, arg2, arg3, arg4, arg5, arg6)
}
func (_m *MockThriftTest) TestMultiException(_param0 string, _param1 string) (*thrifttest.Xtruct, error) {
ret := _m.ctrl.Call(_m, "TestMultiException", _param0, _param1)
// TestMultiException mocks base method
func (_m *MockThriftTest) TestMultiException(_param0 context.Context, _param1 string, _param2 string) (*thrifttest.Xtruct, error) {
ret := _m.ctrl.Call(_m, "TestMultiException", _param0, _param1, _param2)
ret0, _ := ret[0].(*thrifttest.Xtruct)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestMultiException(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMultiException", arg0, arg1)
// TestMultiException indicates an expected call of TestMultiException
func (_mr *MockThriftTestMockRecorder) TestMultiException(arg0, arg1, arg2 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMultiException", arg0, arg1, arg2)
}
func (_m *MockThriftTest) TestNest(_param0 *thrifttest.Xtruct2) (*thrifttest.Xtruct2, error) {
ret := _m.ctrl.Call(_m, "TestNest", _param0)
// TestNest mocks base method
func (_m *MockThriftTest) TestNest(_param0 context.Context, _param1 *thrifttest.Xtruct2) (*thrifttest.Xtruct2, error) {
ret := _m.ctrl.Call(_m, "TestNest", _param0, _param1)
ret0, _ := ret[0].(*thrifttest.Xtruct2)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestNest(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestNest", arg0)
// TestNest indicates an expected call of TestNest
func (_mr *MockThriftTestMockRecorder) TestNest(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestNest", arg0, arg1)
}
func (_m *MockThriftTest) TestOneway(_param0 int32) error {
ret := _m.ctrl.Call(_m, "TestOneway", _param0)
// TestOneway mocks base method
func (_m *MockThriftTest) TestOneway(_param0 context.Context, _param1 int32) error {
ret := _m.ctrl.Call(_m, "TestOneway", _param0, _param1)
ret0, _ := ret[0].(error)
return ret0
}
func (_mr *_MockThriftTestRecorder) TestOneway(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestOneway", arg0)
// TestOneway indicates an expected call of TestOneway
func (_mr *MockThriftTestMockRecorder) TestOneway(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestOneway", arg0, arg1)
}
func (_m *MockThriftTest) TestSet(_param0 []int32) ([]int32, error) {
ret := _m.ctrl.Call(_m, "TestSet", _param0)
// TestSet mocks base method
func (_m *MockThriftTest) TestSet(_param0 context.Context, _param1 []int32) ([]int32, error) {
ret := _m.ctrl.Call(_m, "TestSet", _param0, _param1)
ret0, _ := ret[0].([]int32)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestSet(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestSet", arg0)
// TestSet indicates an expected call of TestSet
func (_mr *MockThriftTestMockRecorder) TestSet(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestSet", arg0, arg1)
}
func (_m *MockThriftTest) TestString(_param0 string) (string, error) {
ret := _m.ctrl.Call(_m, "TestString", _param0)
// TestString mocks base method
func (_m *MockThriftTest) TestString(_param0 context.Context, _param1 string) (string, error) {
ret := _m.ctrl.Call(_m, "TestString", _param0, _param1)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestString(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestString", arg0)
// TestString indicates an expected call of TestString
func (_mr *MockThriftTestMockRecorder) TestString(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestString", arg0, arg1)
}
func (_m *MockThriftTest) TestStringMap(_param0 map[string]string) (map[string]string, error) {
ret := _m.ctrl.Call(_m, "TestStringMap", _param0)
// TestStringMap mocks base method
func (_m *MockThriftTest) TestStringMap(_param0 context.Context, _param1 map[string]string) (map[string]string, error) {
ret := _m.ctrl.Call(_m, "TestStringMap", _param0, _param1)
ret0, _ := ret[0].(map[string]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestStringMap(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestStringMap", arg0)
// TestStringMap indicates an expected call of TestStringMap
func (_mr *MockThriftTestMockRecorder) TestStringMap(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestStringMap", arg0, arg1)
}
func (_m *MockThriftTest) TestStruct(_param0 *thrifttest.Xtruct) (*thrifttest.Xtruct, error) {
ret := _m.ctrl.Call(_m, "TestStruct", _param0)
// TestStruct mocks base method
func (_m *MockThriftTest) TestStruct(_param0 context.Context, _param1 *thrifttest.Xtruct) (*thrifttest.Xtruct, error) {
ret := _m.ctrl.Call(_m, "TestStruct", _param0, _param1)
ret0, _ := ret[0].(*thrifttest.Xtruct)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestStruct(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestStruct", arg0)
// TestStruct indicates an expected call of TestStruct
func (_mr *MockThriftTestMockRecorder) TestStruct(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestStruct", arg0, arg1)
}
func (_m *MockThriftTest) TestTypedef(_param0 thrifttest.UserId) (thrifttest.UserId, error) {
ret := _m.ctrl.Call(_m, "TestTypedef", _param0)
// TestTypedef mocks base method
func (_m *MockThriftTest) TestTypedef(_param0 context.Context, _param1 thrifttest.UserId) (thrifttest.UserId, error) {
ret := _m.ctrl.Call(_m, "TestTypedef", _param0, _param1)
ret0, _ := ret[0].(thrifttest.UserId)
ret1, _ := ret[1].(error)
return ret0, ret1
}
func (_mr *_MockThriftTestRecorder) TestTypedef(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestTypedef", arg0)
// TestTypedef indicates an expected call of TestTypedef
func (_mr *MockThriftTestMockRecorder) TestTypedef(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestTypedef", arg0, arg1)
}
func (_m *MockThriftTest) TestVoid() error {
ret := _m.ctrl.Call(_m, "TestVoid")
// TestVoid mocks base method
func (_m *MockThriftTest) TestVoid(_param0 context.Context) error {
ret := _m.ctrl.Call(_m, "TestVoid", _param0)
ret0, _ := ret[0].(error)
return ret0
}
func (_mr *_MockThriftTestRecorder) TestVoid() *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestVoid")
// TestVoid indicates an expected call of TestVoid
func (_mr *MockThriftTestMockRecorder) TestVoid(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCall(_mr.mock, "TestVoid", arg0)
}

View File

@@ -0,0 +1,26 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package common
import "golang.org/x/net/context"
var defaultCtx = context.Background()

View File

@@ -1,3 +1,5 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -25,6 +27,8 @@ import (
"encoding/hex"
. "gen/thrifttest"
"time"
"golang.org/x/net/context"
)
var PrintingHandler = &printingHandler{}
@@ -32,7 +36,7 @@ var PrintingHandler = &printingHandler{}
type printingHandler struct{}
// Prints "testVoid()" and returns nothing.
func (p *printingHandler) TestVoid() (err error) {
func (p *printingHandler) TestVoid(ctx context.Context) (err error) {
fmt.Println("testVoid()")
return nil
}
@@ -43,7 +47,7 @@ func (p *printingHandler) TestVoid() (err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestString(thing string) (r string, err error) {
func (p *printingHandler) TestString(ctx context.Context, thing string) (r string, err error) {
fmt.Printf("testString(\"%s\")\n", thing)
return thing, nil
}
@@ -54,7 +58,7 @@ func (p *printingHandler) TestString(thing string) (r string, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestBool(thing bool) (r bool, err error) {
func (p *printingHandler) TestBool(ctx context.Context, thing bool) (r bool, err error) {
fmt.Printf("testBool(%t)\n", thing)
return thing, nil
}
@@ -65,7 +69,7 @@ func (p *printingHandler) TestBool(thing bool) (r bool, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestByte(thing int8) (r int8, err error) {
func (p *printingHandler) TestByte(ctx context.Context, thing int8) (r int8, err error) {
fmt.Printf("testByte(%d)\n", thing)
return thing, nil
}
@@ -76,7 +80,7 @@ func (p *printingHandler) TestByte(thing int8) (r int8, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestI32(thing int32) (r int32, err error) {
func (p *printingHandler) TestI32(ctx context.Context, thing int32) (r int32, err error) {
fmt.Printf("testI32(%d)\n", thing)
return thing, nil
}
@@ -87,7 +91,7 @@ func (p *printingHandler) TestI32(thing int32) (r int32, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestI64(thing int64) (r int64, err error) {
func (p *printingHandler) TestI64(ctx context.Context, thing int64) (r int64, err error) {
fmt.Printf("testI64(%d)\n", thing)
return thing, nil
}
@@ -98,7 +102,7 @@ func (p *printingHandler) TestI64(thing int64) (r int64, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestDouble(thing float64) (r float64, err error) {
func (p *printingHandler) TestDouble(ctx context.Context, thing float64) (r float64, err error) {
fmt.Printf("testDouble(%f)\n", thing)
return thing, nil
}
@@ -109,7 +113,7 @@ func (p *printingHandler) TestDouble(thing float64) (r float64, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestBinary(thing []byte) (r []byte, err error) {
func (p *printingHandler) TestBinary(ctx context.Context, thing []byte) (r []byte, err error) {
fmt.Printf("testBinary(%s)\n", hex.EncodeToString(thing))
return thing, nil
}
@@ -120,7 +124,7 @@ func (p *printingHandler) TestBinary(thing []byte) (r []byte, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestStruct(thing *Xtruct) (r *Xtruct, err error) {
func (p *printingHandler) TestStruct(ctx context.Context, thing *Xtruct) (r *Xtruct, err error) {
fmt.Printf("testStruct({\"%s\", %d, %d, %d})\n", thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing)
return thing, err
}
@@ -131,7 +135,7 @@ func (p *printingHandler) TestStruct(thing *Xtruct) (r *Xtruct, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestNest(nest *Xtruct2) (r *Xtruct2, err error) {
func (p *printingHandler) TestNest(ctx context.Context, nest *Xtruct2) (r *Xtruct2, err error) {
thing := nest.StructThing
fmt.Printf("testNest({%d, {\"%s\", %d, %d, %d}, %d})\n", nest.ByteThing, thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing, nest.I32Thing)
return nest, nil
@@ -144,7 +148,7 @@ func (p *printingHandler) TestNest(nest *Xtruct2) (r *Xtruct2, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestMap(thing map[int32]int32) (r map[int32]int32, err error) {
func (p *printingHandler) TestMap(ctx context.Context, thing map[int32]int32) (r map[int32]int32, err error) {
fmt.Printf("testMap({")
first := true
for k, v := range thing {
@@ -166,7 +170,7 @@ func (p *printingHandler) TestMap(thing map[int32]int32) (r map[int32]int32, err
//
// Parameters:
// - Thing
func (p *printingHandler) TestStringMap(thing map[string]string) (r map[string]string, err error) {
func (p *printingHandler) TestStringMap(ctx context.Context, thing map[string]string) (r map[string]string, err error) {
fmt.Printf("testStringMap({")
first := true
for k, v := range thing {
@@ -188,7 +192,7 @@ func (p *printingHandler) TestStringMap(thing map[string]string) (r map[string]s
//
// Parameters:
// - Thing
func (p *printingHandler) TestSet(thing []int32) (r []int32, err error) {
func (p *printingHandler) TestSet(ctx context.Context, thing []int32) (r []int32, err error) {
fmt.Printf("testSet({")
first := true
for k, _ := range thing {
@@ -210,7 +214,7 @@ func (p *printingHandler) TestSet(thing []int32) (r []int32, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestList(thing []int32) (r []int32, err error) {
func (p *printingHandler) TestList(ctx context.Context, thing []int32) (r []int32, err error) {
fmt.Printf("testList({")
for i, v := range thing {
if i != 0 {
@@ -228,7 +232,7 @@ func (p *printingHandler) TestList(thing []int32) (r []int32, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestEnum(thing Numberz) (r Numberz, err error) {
func (p *printingHandler) TestEnum(ctx context.Context, thing Numberz) (r Numberz, err error) {
fmt.Printf("testEnum(%d)\n", thing)
return thing, nil
}
@@ -239,7 +243,7 @@ func (p *printingHandler) TestEnum(thing Numberz) (r Numberz, err error) {
//
// Parameters:
// - Thing
func (p *printingHandler) TestTypedef(thing UserId) (r UserId, err error) {
func (p *printingHandler) TestTypedef(ctx context.Context, thing UserId) (r UserId, err error) {
fmt.Printf("testTypedef(%d)\n", thing)
return thing, nil
}
@@ -251,7 +255,7 @@ func (p *printingHandler) TestTypedef(thing UserId) (r UserId, err error) {
//
// Parameters:
// - Hello
func (p *printingHandler) TestMapMap(hello int32) (r map[int32]map[int32]int32, err error) {
func (p *printingHandler) TestMapMap(ctx context.Context, hello int32) (r map[int32]map[int32]int32, err error) {
fmt.Printf("testMapMap(%d)\n", hello)
r = map[int32]map[int32]int32{
@@ -273,7 +277,7 @@ func (p *printingHandler) TestMapMap(hello int32) (r map[int32]map[int32]int32,
//
// Parameters:
// - Argument
func (p *printingHandler) TestInsanity(argument *Insanity) (r map[UserId]map[Numberz]*Insanity, err error) {
func (p *printingHandler) TestInsanity(ctx context.Context, argument *Insanity) (r map[UserId]map[Numberz]*Insanity, err error) {
fmt.Printf("testInsanity()\n")
r = make(map[UserId]map[Numberz]*Insanity)
r[1] = map[Numberz]*Insanity {
@@ -303,7 +307,7 @@ func (p *printingHandler) TestInsanity(argument *Insanity) (r map[UserId]map[Num
// - Arg3
// - Arg4
// - Arg5
func (p *printingHandler) TestMulti(arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 Numberz, arg5 UserId) (r *Xtruct, err error) {
func (p *printingHandler) TestMulti(ctx context.Context, arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 Numberz, arg5 UserId) (r *Xtruct, err error) {
fmt.Printf("testMulti()\n")
r = NewXtruct()
@@ -322,7 +326,7 @@ func (p *printingHandler) TestMulti(arg0 int8, arg1 int32, arg2 int64, arg3 map[
//
// Parameters:
// - Arg
func (p *printingHandler) TestException(arg string) (err error) {
func (p *printingHandler) TestException(ctx context.Context, arg string) (err error) {
fmt.Printf("testException(%s)\n", arg)
switch arg {
case "Xception":
@@ -346,7 +350,7 @@ func (p *printingHandler) TestException(arg string) (err error) {
// Parameters:
// - Arg0
// - Arg1
func (p *printingHandler) TestMultiException(arg0 string, arg1 string) (r *Xtruct, err error) {
func (p *printingHandler) TestMultiException(ctx context.Context, arg0 string, arg1 string) (r *Xtruct, err error) {
fmt.Printf("testMultiException(%s, %s)\n", arg0, arg1)
switch arg0 {
@@ -375,7 +379,7 @@ func (p *printingHandler) TestMultiException(arg0 string, arg1 string) (r *Xtruc
//
// Parameters:
// - SecondsToSleep
func (p *printingHandler) TestOneway(secondsToSleep int32) (err error) {
func (p *printingHandler) TestOneway(ctx context.Context, secondsToSleep int32) (err error) {
fmt.Printf("testOneway(%d): Sleeping...\n", secondsToSleep)
time.Sleep(time.Second * time.Duration(secondsToSleep))
fmt.Printf("testOneway(%d): done sleeping!\n", secondsToSleep)

View File

@@ -0,0 +1,386 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package common
import (
"context"
"errors"
"fmt"
"encoding/hex"
. "gen/thrifttest"
"time"
)
var PrintingHandler = &printingHandler{}
type printingHandler struct{}
// Prints "testVoid()" and returns nothing.
func (p *printingHandler) TestVoid(ctx context.Context) (err error) {
fmt.Println("testVoid()")
return nil
}
// Prints 'testString("%s")' with thing as '%s'
// @param string thing - the string to print
// @return string - returns the string 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestString(ctx context.Context, thing string) (r string, err error) {
fmt.Printf("testString(\"%s\")\n", thing)
return thing, nil
}
// Prints 'testBool("%t")' with thing as 'true' or 'false'
// @param bool thing - the bool to print
// @return bool - returns the bool 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestBool(ctx context.Context, thing bool) (r bool, err error) {
fmt.Printf("testBool(%t)\n", thing)
return thing, nil
}
// Prints 'testByte("%d")' with thing as '%d'
// @param byte thing - the byte to print
// @return byte - returns the byte 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestByte(ctx context.Context, thing int8) (r int8, err error) {
fmt.Printf("testByte(%d)\n", thing)
return thing, nil
}
// Prints 'testI32("%d")' with thing as '%d'
// @param i32 thing - the i32 to print
// @return i32 - returns the i32 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestI32(ctx context.Context, thing int32) (r int32, err error) {
fmt.Printf("testI32(%d)\n", thing)
return thing, nil
}
// Prints 'testI64("%d")' with thing as '%d'
// @param i64 thing - the i64 to print
// @return i64 - returns the i64 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestI64(ctx context.Context, thing int64) (r int64, err error) {
fmt.Printf("testI64(%d)\n", thing)
return thing, nil
}
// Prints 'testDouble("%f")' with thing as '%f'
// @param double thing - the double to print
// @return double - returns the double 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestDouble(ctx context.Context, thing float64) (r float64, err error) {
fmt.Printf("testDouble(%f)\n", thing)
return thing, nil
}
// Prints 'testBinary("%s")' where '%s' is a hex-formatted string of thing's data
// @param []byte thing - the binary to print
// @return []byte - returns the binary 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestBinary(ctx context.Context, thing []byte) (r []byte, err error) {
fmt.Printf("testBinary(%s)\n", hex.EncodeToString(thing))
return thing, nil
}
// Prints 'testStruct("{%s}")' where thing has been formatted into a string of comma separated values
// @param Xtruct thing - the Xtruct to print
// @return Xtruct - returns the Xtruct 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestStruct(ctx context.Context, thing *Xtruct) (r *Xtruct, err error) {
fmt.Printf("testStruct({\"%s\", %d, %d, %d})\n", thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing)
return thing, err
}
// Prints 'testNest("{%s}")' where thing has been formatted into a string of the nested struct
// @param Xtruct2 thing - the Xtruct2 to print
// @return Xtruct2 - returns the Xtruct2 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestNest(ctx context.Context, nest *Xtruct2) (r *Xtruct2, err error) {
thing := nest.StructThing
fmt.Printf("testNest({%d, {\"%s\", %d, %d, %d}, %d})\n", nest.ByteThing, thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing, nest.I32Thing)
return nest, nil
}
// Prints 'testMap("{%s")' where thing has been formatted into a string of 'key => value' pairs
// separated by commas and new lines
// @param map<i32,i32> thing - the map<i32,i32> to print
// @return map<i32,i32> - returns the map<i32,i32> 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestMap(ctx context.Context, thing map[int32]int32) (r map[int32]int32, err error) {
fmt.Printf("testMap({")
first := true
for k, v := range thing {
if first {
first = false
} else {
fmt.Printf(", ")
}
fmt.Printf("%d => %d", k, v)
}
fmt.Printf("})\n")
return thing, nil
}
// Prints 'testStringMap("{%s}")' where thing has been formatted into a string of 'key => value' pairs
// separated by commas and new lines
// @param map<string,string> thing - the map<string,string> to print
// @return map<string,string> - returns the map<string,string> 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestStringMap(ctx context.Context, thing map[string]string) (r map[string]string, err error) {
fmt.Printf("testStringMap({")
first := true
for k, v := range thing {
if first {
first = false
} else {
fmt.Printf(", ")
}
fmt.Printf("%s => %s", k, v)
}
fmt.Printf("})\n")
return thing, nil
}
// Prints 'testSet("{%s}")' where thing has been formatted into a string of values
// separated by commas and new lines
// @param set<i32> thing - the set<i32> to print
// @return set<i32> - returns the set<i32> 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestSet(ctx context.Context, thing []int32) (r []int32, err error) {
fmt.Printf("testSet({")
first := true
for k, _ := range thing {
if first {
first = false
} else {
fmt.Printf(", ")
}
fmt.Printf("%d", k)
}
fmt.Printf("})\n")
return thing, nil
}
// Prints 'testList("{%s}")' where thing has been formatted into a string of values
// separated by commas and new lines
// @param list<i32> thing - the list<i32> to print
// @return list<i32> - returns the list<i32> 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestList(ctx context.Context, thing []int32) (r []int32, err error) {
fmt.Printf("testList({")
for i, v := range thing {
if i != 0 {
fmt.Printf(", ")
}
fmt.Printf("%d", v)
}
fmt.Printf("})\n")
return thing, nil
}
// Prints 'testEnum("%d")' where thing has been formatted into it's numeric value
// @param Numberz thing - the Numberz to print
// @return Numberz - returns the Numberz 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestEnum(ctx context.Context, thing Numberz) (r Numberz, err error) {
fmt.Printf("testEnum(%d)\n", thing)
return thing, nil
}
// Prints 'testTypedef("%d")' with thing as '%d'
// @param UserId thing - the UserId to print
// @return UserId - returns the UserId 'thing'
//
// Parameters:
// - Thing
func (p *printingHandler) TestTypedef(ctx context.Context, thing UserId) (r UserId, err error) {
fmt.Printf("testTypedef(%d)\n", thing)
return thing, nil
}
// Prints 'testMapMap("%d")' with hello as '%d'
// @param i32 hello - the i32 to print
// @return map<i32,map<i32,i32>> - returns a dictionary with these values:
// {-4 => {-4 => -4, -3 => -3, -2 => -2, -1 => -1, }, 4 => {1 => 1, 2 => 2, 3 => 3, 4 => 4, }, }
//
// Parameters:
// - Hello
func (p *printingHandler) TestMapMap(ctx context.Context, hello int32) (r map[int32]map[int32]int32, err error) {
fmt.Printf("testMapMap(%d)\n", hello)
r = map[int32]map[int32]int32{
-4: map[int32]int32{-4: -4, -3: -3, -2: -2, -1: -1},
4: map[int32]int32{4: 4, 3: 3, 2: 2, 1: 1},
}
return
}
// So you think you've got this all worked, out eh?
//
// Creates a the returned map with these values and prints it out:
// { 1 => { 2 => argument,
// 3 => argument,
// },
// 2 => { 6 => <empty Insanity struct>, },
// }
// @return map<UserId, map<Numberz,Insanity>> - a map with the above values
//
// Parameters:
// - Argument
func (p *printingHandler) TestInsanity(ctx context.Context, argument *Insanity) (r map[UserId]map[Numberz]*Insanity, err error) {
fmt.Printf("testInsanity()\n")
r = make(map[UserId]map[Numberz]*Insanity)
r[1] = map[Numberz]*Insanity {
2: argument,
3: argument,
}
r[2] = map[Numberz]*Insanity {
6: NewInsanity(),
}
return
}
// Prints 'testMulti()'
// @param byte arg0 -
// @param i32 arg1 -
// @param i64 arg2 -
// @param map<i16, string> arg3 -
// @param Numberz arg4 -
// @param UserId arg5 -
// @return Xtruct - returns an Xtruct with StringThing = "Hello2, ByteThing = arg0, I32Thing = arg1
// and I64Thing = arg2
//
// Parameters:
// - Arg0
// - Arg1
// - Arg2
// - Arg3
// - Arg4
// - Arg5
func (p *printingHandler) TestMulti(ctx context.Context, arg0 int8, arg1 int32, arg2 int64, arg3 map[int16]string, arg4 Numberz, arg5 UserId) (r *Xtruct, err error) {
fmt.Printf("testMulti()\n")
r = NewXtruct()
r.StringThing = "Hello2"
r.ByteThing = arg0
r.I32Thing = arg1
r.I64Thing = arg2
return
}
// Print 'testException(%s)' with arg as '%s'
// @param string arg - a string indication what type of exception to throw
// if arg == "Xception" throw Xception with errorCode = 1001 and message = arg
// elsen if arg == "TException" throw TException
// else do not throw anything
//
// Parameters:
// - Arg
func (p *printingHandler) TestException(ctx context.Context, arg string) (err error) {
fmt.Printf("testException(%s)\n", arg)
switch arg {
case "Xception":
e := NewXception()
e.ErrorCode = 1001
e.Message = arg
return e
case "TException":
return errors.New("Just TException")
}
return
}
// Print 'testMultiException(%s, %s)' with arg0 as '%s' and arg1 as '%s'
// @param string arg - a string indication what type of exception to throw
// if arg0 == "Xception" throw Xception with errorCode = 1001 and message = "This is an Xception"
// elsen if arg0 == "Xception2" throw Xception2 with errorCode = 2002 and message = "This is an Xception2"
// else do not throw anything
// @return Xtruct - an Xtruct with StringThing = arg1
//
// Parameters:
// - Arg0
// - Arg1
func (p *printingHandler) TestMultiException(ctx context.Context, arg0 string, arg1 string) (r *Xtruct, err error) {
fmt.Printf("testMultiException(%s, %s)\n", arg0, arg1)
switch arg0 {
case "Xception":
e := NewXception()
e.ErrorCode = 1001
e.Message = "This is an Xception"
return nil, e
case "Xception2":
e := NewXception2()
e.ErrorCode = 2002
e.StructThing = NewXtruct()
e.StructThing.StringThing = "This is an Xception2"
return nil, e
default:
r = NewXtruct()
r.StringThing = arg1
return
}
}
// Print 'testOneway(%d): Sleeping...' with secondsToSleep as '%d'
// sleep 'secondsToSleep'
// Print 'testOneway(%d): done sleeping!' with secondsToSleep as '%d'
// @param i32 secondsToSleep - the number of seconds to sleep
//
// Parameters:
// - SecondsToSleep
func (p *printingHandler) TestOneway(ctx context.Context, secondsToSleep int32) (err error) {
fmt.Printf("testOneway(%d): Sleeping...\n", secondsToSleep)
time.Sleep(time.Second * time.Duration(secondsToSleep))
fmt.Printf("testOneway(%d): done sleeping!\n", secondsToSleep)
return
}

View File

@@ -17,30 +17,37 @@
# under the License.
#
if GOVERSION_LT_17
COMPILER_EXTRAFLAG=":legacy_context"
endif
THRIFT = $(top_builddir)/compiler/cpp/thrift
gen-go/tutorial/calculator.go gen-go/shared/shared_service.go: $(top_srcdir)/tutorial/tutorial.thrift
$(THRIFT) --gen go -r $<
$(THRIFT) --gen go$(COMPILER_EXTRAFLAG) -r $<
all-local: gen-go/tutorial/calculator.go
check: src/git.apache.org/thrift.git/lib/go/thrift
$(THRIFT) -r --gen go $(top_srcdir)/tutorial/tutorial.thrift
check: src/git.apache.org/thrift.git/lib/go/thrift thirdparty-dep
$(THRIFT) -r --gen go$(COMPILER_EXTRAFLAG) $(top_srcdir)/tutorial/tutorial.thrift
cp -r gen-go/* src/
GOPATH=`pwd` $(GO) build ./...
GOPATH=`pwd` $(GO) build -o go-tutorial src/*.go
GOPATH=`pwd` $(GO) build -o go-tutorial ./src
GOPATH=`pwd` $(GO) build -o calculator-remote src/tutorial/calculator-remote/calculator-remote.go
src/git.apache.org/thrift.git/lib/go/thrift:
mkdir -p src/git.apache.org/thrift.git/lib/go
ln -sf $(realpath $(top_srcdir)/lib/go/thrift) src/git.apache.org/thrift.git/lib/go/thrift
thirdparty-dep:
mkdir -p src/golang.org/x/net
GOPATH=`pwd`/gopath $(GO) get golang.org/x/net/context
ln -sf `pwd`/gopath/src/golang.org/x/net/context src/golang.org/x/net/context
tutorialserver: all
GOPATH=`pwd` $(GO) run src/*.go -server=true
tutorialclient: all
GOPATH=`pwd` $(GO) run src/*.go
GOPATH=`pwd` $(GO) run src/*.go
tutorialsecureserver: all
GOPATH=`pwd` $(GO) run src/*.go -server=true -secure=true

View File

@@ -27,17 +27,17 @@ import (
)
func handleClient(client *tutorial.CalculatorClient) (err error) {
client.Ping()
client.Ping(defaultCtx)
fmt.Println("ping()")
sum, _ := client.Add(1, 1)
sum, _ := client.Add(defaultCtx, 1, 1)
fmt.Print("1+1=", sum, "\n")
work := tutorial.NewWork()
work.Op = tutorial.Operation_DIVIDE
work.Num1 = 1
work.Num2 = 0
quotient, err := client.Calculate(1, work)
quotient, err := client.Calculate(defaultCtx, 1, work)
if err != nil {
switch v := err.(type) {
case *tutorial.InvalidOperation:
@@ -53,7 +53,7 @@ func handleClient(client *tutorial.CalculatorClient) (err error) {
work.Op = tutorial.Operation_SUBTRACT
work.Num1 = 15
work.Num2 = 10
diff, err := client.Calculate(1, work)
diff, err := client.Calculate(defaultCtx, 1, work)
if err != nil {
switch v := err.(type) {
case *tutorial.InvalidOperation:
@@ -66,7 +66,7 @@ func handleClient(client *tutorial.CalculatorClient) (err error) {
fmt.Print("15-10=", diff, "\n")
}
log, err := client.GetStruct(1)
log, err := client.GetStruct(defaultCtx, 1)
if err != nil {
fmt.Println("Unable to get struct:", err)
return err

View File

@@ -0,0 +1,26 @@
// +build go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package main
import "context"
var defaultCtx = context.Background()

View File

@@ -1,3 +1,5 @@
// +build !go1.7
package main
/*
@@ -24,6 +26,8 @@ import (
"shared"
"strconv"
"tutorial"
"golang.org/x/net/context"
)
type CalculatorHandler struct {
@@ -34,17 +38,17 @@ func NewCalculatorHandler() *CalculatorHandler {
return &CalculatorHandler{log: make(map[int]*shared.SharedStruct)}
}
func (p *CalculatorHandler) Ping() (err error) {
func (p *CalculatorHandler) Ping(ctx context.Context) (err error) {
fmt.Print("ping()\n")
return nil
}
func (p *CalculatorHandler) Add(num1 int32, num2 int32) (retval17 int32, err error) {
func (p *CalculatorHandler) Add(ctx context.Context, num1 int32, num2 int32) (retval17 int32, err error) {
fmt.Print("add(", num1, ",", num2, ")\n")
return num1 + num2, nil
}
func (p *CalculatorHandler) Calculate(logid int32, w *tutorial.Work) (val int32, err error) {
func (p *CalculatorHandler) Calculate(ctx context.Context, logid int32, w *tutorial.Work) (val int32, err error) {
fmt.Print("calculate(", logid, ", {", w.Op, ",", w.Num1, ",", w.Num2, "})\n")
switch w.Op {
case tutorial.Operation_ADD:
@@ -89,13 +93,13 @@ func (p *CalculatorHandler) Calculate(logid int32, w *tutorial.Work) (val int32,
return val, err
}
func (p *CalculatorHandler) GetStruct(key int32) (*shared.SharedStruct, error) {
func (p *CalculatorHandler) GetStruct(ctx context.Context, key int32) (*shared.SharedStruct, error) {
fmt.Print("getStruct(", key, ")\n")
v, _ := p.log[int(key)]
return v, nil
}
func (p *CalculatorHandler) Zip() (err error) {
func (p *CalculatorHandler) Zip(ctx context.Context) (err error) {
fmt.Print("zip()\n")
return nil
}

View File

@@ -0,0 +1,104 @@
// +build go1.7
package main
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import (
"context"
"fmt"
"shared"
"strconv"
"tutorial"
)
type CalculatorHandler struct {
log map[int]*shared.SharedStruct
}
func NewCalculatorHandler() *CalculatorHandler {
return &CalculatorHandler{log: make(map[int]*shared.SharedStruct)}
}
func (p *CalculatorHandler) Ping(ctx context.Context) (err error) {
fmt.Print("ping()\n")
return nil
}
func (p *CalculatorHandler) Add(ctx context.Context, num1 int32, num2 int32) (retval17 int32, err error) {
fmt.Print("add(", num1, ",", num2, ")\n")
return num1 + num2, nil
}
func (p *CalculatorHandler) Calculate(ctx context.Context, logid int32, w *tutorial.Work) (val int32, err error) {
fmt.Print("calculate(", logid, ", {", w.Op, ",", w.Num1, ",", w.Num2, "})\n")
switch w.Op {
case tutorial.Operation_ADD:
val = w.Num1 + w.Num2
break
case tutorial.Operation_SUBTRACT:
val = w.Num1 - w.Num2
break
case tutorial.Operation_MULTIPLY:
val = w.Num1 * w.Num2
break
case tutorial.Operation_DIVIDE:
if w.Num2 == 0 {
ouch := tutorial.NewInvalidOperation()
ouch.WhatOp = int32(w.Op)
ouch.Why = "Cannot divide by 0"
err = ouch
return
}
val = w.Num1 / w.Num2
break
default:
ouch := tutorial.NewInvalidOperation()
ouch.WhatOp = int32(w.Op)
ouch.Why = "Unknown operation"
err = ouch
return
}
entry := shared.NewSharedStruct()
entry.Key = logid
entry.Value = strconv.Itoa(int(val))
k := int(logid)
/*
oldvalue, exists := p.log[k]
if exists {
fmt.Print("Replacing ", oldvalue, " with ", entry, " for key ", k, "\n")
} else {
fmt.Print("Adding ", entry, " for key ", k, "\n")
}
*/
p.log[k] = entry
return val, err
}
func (p *CalculatorHandler) GetStruct(ctx context.Context, key int32) (*shared.SharedStruct, error) {
fmt.Print("getStruct(", key, ")\n")
v, _ := p.log[int(key)]
return v, nil
}
func (p *CalculatorHandler) Zip(ctx context.Context) (err error) {
fmt.Print("zip()\n")
return nil
}

View File

@@ -0,0 +1,26 @@
// +build !go1.7
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package main
import "golang.org/x/net/context"
var defaultCtx = context.Background()

View File

@@ -134,6 +134,8 @@ func IsISBN10(str string) bool
func IsISBN13(str string) bool
func IsISO3166Alpha2(str string) bool
func IsISO3166Alpha3(str string) bool
func IsISO693Alpha2(str string) bool
func IsISO693Alpha3b(str string) bool
func IsISO4217(str string) bool
func IsIn(str string, params ...string) bool
func IsInt(str string) bool

View File

@@ -416,3 +416,198 @@ var ISO4217List = []string{
"YER",
"ZAR", "ZMW", "ZWL",
}
// ISO693Entry stores ISO language codes
type ISO693Entry struct {
Alpha3bCode string
Alpha2Code string
English string
}
//ISO693List based on http://data.okfn.org/data/core/language-codes/r/language-codes-3b2.json
var ISO693List = []ISO693Entry{
{Alpha3bCode: "aar", Alpha2Code: "aa", English: "Afar"},
{Alpha3bCode: "abk", Alpha2Code: "ab", English: "Abkhazian"},
{Alpha3bCode: "afr", Alpha2Code: "af", English: "Afrikaans"},
{Alpha3bCode: "aka", Alpha2Code: "ak", English: "Akan"},
{Alpha3bCode: "alb", Alpha2Code: "sq", English: "Albanian"},
{Alpha3bCode: "amh", Alpha2Code: "am", English: "Amharic"},
{Alpha3bCode: "ara", Alpha2Code: "ar", English: "Arabic"},
{Alpha3bCode: "arg", Alpha2Code: "an", English: "Aragonese"},
{Alpha3bCode: "arm", Alpha2Code: "hy", English: "Armenian"},
{Alpha3bCode: "asm", Alpha2Code: "as", English: "Assamese"},
{Alpha3bCode: "ava", Alpha2Code: "av", English: "Avaric"},
{Alpha3bCode: "ave", Alpha2Code: "ae", English: "Avestan"},
{Alpha3bCode: "aym", Alpha2Code: "ay", English: "Aymara"},
{Alpha3bCode: "aze", Alpha2Code: "az", English: "Azerbaijani"},
{Alpha3bCode: "bak", Alpha2Code: "ba", English: "Bashkir"},
{Alpha3bCode: "bam", Alpha2Code: "bm", English: "Bambara"},
{Alpha3bCode: "baq", Alpha2Code: "eu", English: "Basque"},
{Alpha3bCode: "bel", Alpha2Code: "be", English: "Belarusian"},
{Alpha3bCode: "ben", Alpha2Code: "bn", English: "Bengali"},
{Alpha3bCode: "bih", Alpha2Code: "bh", English: "Bihari languages"},
{Alpha3bCode: "bis", Alpha2Code: "bi", English: "Bislama"},
{Alpha3bCode: "bos", Alpha2Code: "bs", English: "Bosnian"},
{Alpha3bCode: "bre", Alpha2Code: "br", English: "Breton"},
{Alpha3bCode: "bul", Alpha2Code: "bg", English: "Bulgarian"},
{Alpha3bCode: "bur", Alpha2Code: "my", English: "Burmese"},
{Alpha3bCode: "cat", Alpha2Code: "ca", English: "Catalan; Valencian"},
{Alpha3bCode: "cha", Alpha2Code: "ch", English: "Chamorro"},
{Alpha3bCode: "che", Alpha2Code: "ce", English: "Chechen"},
{Alpha3bCode: "chi", Alpha2Code: "zh", English: "Chinese"},
{Alpha3bCode: "chu", Alpha2Code: "cu", English: "Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic"},
{Alpha3bCode: "chv", Alpha2Code: "cv", English: "Chuvash"},
{Alpha3bCode: "cor", Alpha2Code: "kw", English: "Cornish"},
{Alpha3bCode: "cos", Alpha2Code: "co", English: "Corsican"},
{Alpha3bCode: "cre", Alpha2Code: "cr", English: "Cree"},
{Alpha3bCode: "cze", Alpha2Code: "cs", English: "Czech"},
{Alpha3bCode: "dan", Alpha2Code: "da", English: "Danish"},
{Alpha3bCode: "div", Alpha2Code: "dv", English: "Divehi; Dhivehi; Maldivian"},
{Alpha3bCode: "dut", Alpha2Code: "nl", English: "Dutch; Flemish"},
{Alpha3bCode: "dzo", Alpha2Code: "dz", English: "Dzongkha"},
{Alpha3bCode: "eng", Alpha2Code: "en", English: "English"},
{Alpha3bCode: "epo", Alpha2Code: "eo", English: "Esperanto"},
{Alpha3bCode: "est", Alpha2Code: "et", English: "Estonian"},
{Alpha3bCode: "ewe", Alpha2Code: "ee", English: "Ewe"},
{Alpha3bCode: "fao", Alpha2Code: "fo", English: "Faroese"},
{Alpha3bCode: "fij", Alpha2Code: "fj", English: "Fijian"},
{Alpha3bCode: "fin", Alpha2Code: "fi", English: "Finnish"},
{Alpha3bCode: "fre", Alpha2Code: "fr", English: "French"},
{Alpha3bCode: "fry", Alpha2Code: "fy", English: "Western Frisian"},
{Alpha3bCode: "ful", Alpha2Code: "ff", English: "Fulah"},
{Alpha3bCode: "geo", Alpha2Code: "ka", English: "Georgian"},
{Alpha3bCode: "ger", Alpha2Code: "de", English: "German"},
{Alpha3bCode: "gla", Alpha2Code: "gd", English: "Gaelic; Scottish Gaelic"},
{Alpha3bCode: "gle", Alpha2Code: "ga", English: "Irish"},
{Alpha3bCode: "glg", Alpha2Code: "gl", English: "Galician"},
{Alpha3bCode: "glv", Alpha2Code: "gv", English: "Manx"},
{Alpha3bCode: "gre", Alpha2Code: "el", English: "Greek, Modern (1453-)"},
{Alpha3bCode: "grn", Alpha2Code: "gn", English: "Guarani"},
{Alpha3bCode: "guj", Alpha2Code: "gu", English: "Gujarati"},
{Alpha3bCode: "hat", Alpha2Code: "ht", English: "Haitian; Haitian Creole"},
{Alpha3bCode: "hau", Alpha2Code: "ha", English: "Hausa"},
{Alpha3bCode: "heb", Alpha2Code: "he", English: "Hebrew"},
{Alpha3bCode: "her", Alpha2Code: "hz", English: "Herero"},
{Alpha3bCode: "hin", Alpha2Code: "hi", English: "Hindi"},
{Alpha3bCode: "hmo", Alpha2Code: "ho", English: "Hiri Motu"},
{Alpha3bCode: "hrv", Alpha2Code: "hr", English: "Croatian"},
{Alpha3bCode: "hun", Alpha2Code: "hu", English: "Hungarian"},
{Alpha3bCode: "ibo", Alpha2Code: "ig", English: "Igbo"},
{Alpha3bCode: "ice", Alpha2Code: "is", English: "Icelandic"},
{Alpha3bCode: "ido", Alpha2Code: "io", English: "Ido"},
{Alpha3bCode: "iii", Alpha2Code: "ii", English: "Sichuan Yi; Nuosu"},
{Alpha3bCode: "iku", Alpha2Code: "iu", English: "Inuktitut"},
{Alpha3bCode: "ile", Alpha2Code: "ie", English: "Interlingue; Occidental"},
{Alpha3bCode: "ina", Alpha2Code: "ia", English: "Interlingua (International Auxiliary Language Association)"},
{Alpha3bCode: "ind", Alpha2Code: "id", English: "Indonesian"},
{Alpha3bCode: "ipk", Alpha2Code: "ik", English: "Inupiaq"},
{Alpha3bCode: "ita", Alpha2Code: "it", English: "Italian"},
{Alpha3bCode: "jav", Alpha2Code: "jv", English: "Javanese"},
{Alpha3bCode: "jpn", Alpha2Code: "ja", English: "Japanese"},
{Alpha3bCode: "kal", Alpha2Code: "kl", English: "Kalaallisut; Greenlandic"},
{Alpha3bCode: "kan", Alpha2Code: "kn", English: "Kannada"},
{Alpha3bCode: "kas", Alpha2Code: "ks", English: "Kashmiri"},
{Alpha3bCode: "kau", Alpha2Code: "kr", English: "Kanuri"},
{Alpha3bCode: "kaz", Alpha2Code: "kk", English: "Kazakh"},
{Alpha3bCode: "khm", Alpha2Code: "km", English: "Central Khmer"},
{Alpha3bCode: "kik", Alpha2Code: "ki", English: "Kikuyu; Gikuyu"},
{Alpha3bCode: "kin", Alpha2Code: "rw", English: "Kinyarwanda"},
{Alpha3bCode: "kir", Alpha2Code: "ky", English: "Kirghiz; Kyrgyz"},
{Alpha3bCode: "kom", Alpha2Code: "kv", English: "Komi"},
{Alpha3bCode: "kon", Alpha2Code: "kg", English: "Kongo"},
{Alpha3bCode: "kor", Alpha2Code: "ko", English: "Korean"},
{Alpha3bCode: "kua", Alpha2Code: "kj", English: "Kuanyama; Kwanyama"},
{Alpha3bCode: "kur", Alpha2Code: "ku", English: "Kurdish"},
{Alpha3bCode: "lao", Alpha2Code: "lo", English: "Lao"},
{Alpha3bCode: "lat", Alpha2Code: "la", English: "Latin"},
{Alpha3bCode: "lav", Alpha2Code: "lv", English: "Latvian"},
{Alpha3bCode: "lim", Alpha2Code: "li", English: "Limburgan; Limburger; Limburgish"},
{Alpha3bCode: "lin", Alpha2Code: "ln", English: "Lingala"},
{Alpha3bCode: "lit", Alpha2Code: "lt", English: "Lithuanian"},
{Alpha3bCode: "ltz", Alpha2Code: "lb", English: "Luxembourgish; Letzeburgesch"},
{Alpha3bCode: "lub", Alpha2Code: "lu", English: "Luba-Katanga"},
{Alpha3bCode: "lug", Alpha2Code: "lg", English: "Ganda"},
{Alpha3bCode: "mac", Alpha2Code: "mk", English: "Macedonian"},
{Alpha3bCode: "mah", Alpha2Code: "mh", English: "Marshallese"},
{Alpha3bCode: "mal", Alpha2Code: "ml", English: "Malayalam"},
{Alpha3bCode: "mao", Alpha2Code: "mi", English: "Maori"},
{Alpha3bCode: "mar", Alpha2Code: "mr", English: "Marathi"},
{Alpha3bCode: "may", Alpha2Code: "ms", English: "Malay"},
{Alpha3bCode: "mlg", Alpha2Code: "mg", English: "Malagasy"},
{Alpha3bCode: "mlt", Alpha2Code: "mt", English: "Maltese"},
{Alpha3bCode: "mon", Alpha2Code: "mn", English: "Mongolian"},
{Alpha3bCode: "nau", Alpha2Code: "na", English: "Nauru"},
{Alpha3bCode: "nav", Alpha2Code: "nv", English: "Navajo; Navaho"},
{Alpha3bCode: "nbl", Alpha2Code: "nr", English: "Ndebele, South; South Ndebele"},
{Alpha3bCode: "nde", Alpha2Code: "nd", English: "Ndebele, North; North Ndebele"},
{Alpha3bCode: "ndo", Alpha2Code: "ng", English: "Ndonga"},
{Alpha3bCode: "nep", Alpha2Code: "ne", English: "Nepali"},
{Alpha3bCode: "nno", Alpha2Code: "nn", English: "Norwegian Nynorsk; Nynorsk, Norwegian"},
{Alpha3bCode: "nob", Alpha2Code: "nb", English: "Bokmål, Norwegian; Norwegian Bokmål"},
{Alpha3bCode: "nor", Alpha2Code: "no", English: "Norwegian"},
{Alpha3bCode: "nya", Alpha2Code: "ny", English: "Chichewa; Chewa; Nyanja"},
{Alpha3bCode: "oci", Alpha2Code: "oc", English: "Occitan (post 1500); Provençal"},
{Alpha3bCode: "oji", Alpha2Code: "oj", English: "Ojibwa"},
{Alpha3bCode: "ori", Alpha2Code: "or", English: "Oriya"},
{Alpha3bCode: "orm", Alpha2Code: "om", English: "Oromo"},
{Alpha3bCode: "oss", Alpha2Code: "os", English: "Ossetian; Ossetic"},
{Alpha3bCode: "pan", Alpha2Code: "pa", English: "Panjabi; Punjabi"},
{Alpha3bCode: "per", Alpha2Code: "fa", English: "Persian"},
{Alpha3bCode: "pli", Alpha2Code: "pi", English: "Pali"},
{Alpha3bCode: "pol", Alpha2Code: "pl", English: "Polish"},
{Alpha3bCode: "por", Alpha2Code: "pt", English: "Portuguese"},
{Alpha3bCode: "pus", Alpha2Code: "ps", English: "Pushto; Pashto"},
{Alpha3bCode: "que", Alpha2Code: "qu", English: "Quechua"},
{Alpha3bCode: "roh", Alpha2Code: "rm", English: "Romansh"},
{Alpha3bCode: "rum", Alpha2Code: "ro", English: "Romanian; Moldavian; Moldovan"},
{Alpha3bCode: "run", Alpha2Code: "rn", English: "Rundi"},
{Alpha3bCode: "rus", Alpha2Code: "ru", English: "Russian"},
{Alpha3bCode: "sag", Alpha2Code: "sg", English: "Sango"},
{Alpha3bCode: "san", Alpha2Code: "sa", English: "Sanskrit"},
{Alpha3bCode: "sin", Alpha2Code: "si", English: "Sinhala; Sinhalese"},
{Alpha3bCode: "slo", Alpha2Code: "sk", English: "Slovak"},
{Alpha3bCode: "slv", Alpha2Code: "sl", English: "Slovenian"},
{Alpha3bCode: "sme", Alpha2Code: "se", English: "Northern Sami"},
{Alpha3bCode: "smo", Alpha2Code: "sm", English: "Samoan"},
{Alpha3bCode: "sna", Alpha2Code: "sn", English: "Shona"},
{Alpha3bCode: "snd", Alpha2Code: "sd", English: "Sindhi"},
{Alpha3bCode: "som", Alpha2Code: "so", English: "Somali"},
{Alpha3bCode: "sot", Alpha2Code: "st", English: "Sotho, Southern"},
{Alpha3bCode: "spa", Alpha2Code: "es", English: "Spanish; Castilian"},
{Alpha3bCode: "srd", Alpha2Code: "sc", English: "Sardinian"},
{Alpha3bCode: "srp", Alpha2Code: "sr", English: "Serbian"},
{Alpha3bCode: "ssw", Alpha2Code: "ss", English: "Swati"},
{Alpha3bCode: "sun", Alpha2Code: "su", English: "Sundanese"},
{Alpha3bCode: "swa", Alpha2Code: "sw", English: "Swahili"},
{Alpha3bCode: "swe", Alpha2Code: "sv", English: "Swedish"},
{Alpha3bCode: "tah", Alpha2Code: "ty", English: "Tahitian"},
{Alpha3bCode: "tam", Alpha2Code: "ta", English: "Tamil"},
{Alpha3bCode: "tat", Alpha2Code: "tt", English: "Tatar"},
{Alpha3bCode: "tel", Alpha2Code: "te", English: "Telugu"},
{Alpha3bCode: "tgk", Alpha2Code: "tg", English: "Tajik"},
{Alpha3bCode: "tgl", Alpha2Code: "tl", English: "Tagalog"},
{Alpha3bCode: "tha", Alpha2Code: "th", English: "Thai"},
{Alpha3bCode: "tib", Alpha2Code: "bo", English: "Tibetan"},
{Alpha3bCode: "tir", Alpha2Code: "ti", English: "Tigrinya"},
{Alpha3bCode: "ton", Alpha2Code: "to", English: "Tonga (Tonga Islands)"},
{Alpha3bCode: "tsn", Alpha2Code: "tn", English: "Tswana"},
{Alpha3bCode: "tso", Alpha2Code: "ts", English: "Tsonga"},
{Alpha3bCode: "tuk", Alpha2Code: "tk", English: "Turkmen"},
{Alpha3bCode: "tur", Alpha2Code: "tr", English: "Turkish"},
{Alpha3bCode: "twi", Alpha2Code: "tw", English: "Twi"},
{Alpha3bCode: "uig", Alpha2Code: "ug", English: "Uighur; Uyghur"},
{Alpha3bCode: "ukr", Alpha2Code: "uk", English: "Ukrainian"},
{Alpha3bCode: "urd", Alpha2Code: "ur", English: "Urdu"},
{Alpha3bCode: "uzb", Alpha2Code: "uz", English: "Uzbek"},
{Alpha3bCode: "ven", Alpha2Code: "ve", English: "Venda"},
{Alpha3bCode: "vie", Alpha2Code: "vi", English: "Vietnamese"},
{Alpha3bCode: "vol", Alpha2Code: "vo", English: "Volapük"},
{Alpha3bCode: "wel", Alpha2Code: "cy", English: "Welsh"},
{Alpha3bCode: "wln", Alpha2Code: "wa", English: "Walloon"},
{Alpha3bCode: "wol", Alpha2Code: "wo", English: "Wolof"},
{Alpha3bCode: "xho", Alpha2Code: "xh", English: "Xhosa"},
{Alpha3bCode: "yid", Alpha2Code: "yi", English: "Yiddish"},
{Alpha3bCode: "yor", Alpha2Code: "yo", English: "Yoruba"},
{Alpha3bCode: "zha", Alpha2Code: "za", English: "Zhuang; Chuang"},
{Alpha3bCode: "zul", Alpha2Code: "zu", English: "Zulu"},
}

View File

@@ -457,6 +457,26 @@ func IsISO3166Alpha3(str string) bool {
return false
}
// IsISO693Alpha2 checks if a string is valid two-letter language code
func IsISO693Alpha2(str string) bool {
for _, entry := range ISO693List {
if str == entry.Alpha2Code {
return true
}
}
return false
}
// IsISO693Alpha3b checks if a string is valid three-letter language code
func IsISO693Alpha3b(str string) bool {
for _, entry := range ISO693List {
if str == entry.Alpha3bCode {
return true
}
}
return false
}
// IsDNSName will validate the given string as a DNS name
func IsDNSName(str string) bool {
if str == "" || len(strings.Replace(str, ".", "", -1)) > 255 {

View File

@@ -1411,6 +1411,64 @@ func TestIsISO3166Alpha3(t *testing.T) {
}
}
func TestIsISO693Alpha2(t *testing.T) {
t.Parallel()
var tests = []struct {
param string
expected bool
}{
{"", false},
{"abcd", false},
{"a", false},
{"ac", false},
{"ap", false},
{"de", true},
{"DE", false},
{"mk", true},
{"mac", false},
{"sw", true},
{"SW", false},
{"ger", false},
{"deu", false},
}
for _, test := range tests {
actual := IsISO693Alpha2(test.param)
if actual != test.expected {
t.Errorf("Expected IsISO693Alpha2(%q) to be %v, got %v", test.param, test.expected, actual)
}
}
}
func TestIsISO693Alpha3b(t *testing.T) {
t.Parallel()
var tests = []struct {
param string
expected bool
}{
{"", false},
{"abcd", false},
{"a", false},
{"ac", false},
{"ap", false},
{"de", false},
{"DE", false},
{"mkd", false},
{"mac", true},
{"sw", false},
{"SW", false},
{"ger", true},
{"deu", false},
}
for _, test := range tests {
actual := IsISO693Alpha3b(test.param)
if actual != test.expected {
t.Errorf("Expected IsISO693Alpha3b(%q) to be %v, got %v", test.param, test.expected, actual)
}
}
}
func TestIsIP(t *testing.T) {
t.Parallel()

View File

@@ -1,11 +0,0 @@
dist
/doc
/doc-staging
.yardoc
Gemfile.lock
awstesting/integration/smoke/**/importmarker__.go
awstesting/integration/smoke/_test/
/vendor/bin/
/vendor/pkg/
/vendor/src/
/private/model/cli/gen-api/gen-api

View File

@@ -1,14 +0,0 @@
{
"PkgHandler": {
"Pattern": "/sdk-for-go/api/",
"StripPrefix": "/sdk-for-go/api",
"Include": ["/src/github.com/aws/aws-sdk-go/aws", "/src/github.com/aws/aws-sdk-go/service"],
"Exclude": ["/src/cmd", "/src/github.com/aws/aws-sdk-go/awstesting", "/src/github.com/aws/aws-sdk-go/awsmigrate"],
"IgnoredSuffixes": ["iface"]
},
"Github": {
"Tag": "master",
"Repo": "/aws/aws-sdk-go",
"UseGithub": true
}
}

View File

@@ -1,23 +0,0 @@
language: go
sudo: false
go:
- 1.4
- 1.5
- 1.6
- tip
# Use Go 1.5's vendoring experiment for 1.5 tests. 1.4 tests will use the tip of the dependencies repo.
env:
- GO15VENDOREXPERIMENT=1
install:
- make get-deps
script:
- make unit-with-race-cover
matrix:
allow_failures:
- go: tip

View File

@@ -1,7 +0,0 @@
--plugin go
-e doc-src/plugin/plugin.rb
-m markdown
-o doc/api
--title "AWS SDK for Go"
aws/**/*.go
service/**/*.go

View File

@@ -1,6 +0,0 @@
source 'https://rubygems.org'
gem 'yard', git: 'git://github.com/lsegal/yard', ref: '5025564a491e1b7c6192632cba2802202ca08449'
gem 'yard-go', git: 'git://github.com/jasdel/yard-go', ref: 'e78e1ef7cdf5e0f3266845b26bb4fd64f1dd6f85'
gem 'rdiscount'

View File

@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,152 +0,0 @@
LINTIGNOREDOT='awstesting/integration.+should not use dot imports'
LINTIGNOREDOC='service/[^/]+/(api|service|waiters)\.go:.+(comment on exported|should have comment or be unexported)'
LINTIGNORECONST='service/[^/]+/(api|service|waiters)\.go:.+(type|struct field|const|func) ([^ ]+) should be ([^ ]+)'
LINTIGNORESTUTTER='service/[^/]+/(api|service)\.go:.+(and that stutters)'
LINTIGNOREINFLECT='service/[^/]+/(api|service)\.go:.+method .+ should be '
LINTIGNOREINFLECTS3UPLOAD='service/s3/s3manager/upload\.go:.+struct field SSEKMSKeyId should be '
LINTIGNOREDEPS='vendor/.+\.go'
SDK_WITH_VENDOR_PKGS=$(shell go list ./... | grep -v "/vendor/src")
SDK_ONLY_PKGS=$(shell go list ./... | grep -v "/vendor/")
SDK_GO_1_4=$(shell go version | grep "go1.4")
SDK_GO_VERSION=$(shell go version | awk '''{print $$3}''' | tr -d '''\n''')
all: get-deps generate unit
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " api_info to print a list of services and versions"
@echo " docs to build SDK documentation"
@echo " build to go build the SDK"
@echo " unit to run unit tests"
@echo " integration to run integration tests"
@echo " performance to run performance tests"
@echo " verify to verify tests"
@echo " lint to lint the SDK"
@echo " vet to vet the SDK"
@echo " generate to go generate and make services"
@echo " gen-test to generate protocol tests"
@echo " gen-services to generate services"
@echo " get-deps to go get the SDK dependencies"
@echo " get-deps-tests to get the SDK's test dependencies"
@echo " get-deps-verify to get the SDK's verification dependencies"
generate: gen-test gen-endpoints gen-services
gen-test: gen-protocol-test
gen-services:
go generate ./service
gen-protocol-test:
go generate ./private/protocol/...
gen-endpoints:
go generate ./private/endpoints
build:
@echo "go build SDK and vendor packages"
@go build ${SDK_ONLY_PKGS}
unit: get-deps-tests build verify
@echo "go test SDK and vendor packages"
@go test -tags $(SDK_ONLY_PKGS)
unit-with-race-cover: get-deps-tests build verify
@echo "go test SDK and vendor packages"
@go test -tags -race -cpu=1,2,4 $(SDK_ONLY_PKGS)
integration: get-deps-tests integ-custom smoke-tests performance
integ-custom:
go test -tags "integration" ./awstesting/integration/customizations/...
smoke-tests: get-deps-tests
gucumber -go-tags "integration" ./awstesting/integration/smoke
performance: get-deps-tests
AWS_TESTING_LOG_RESULTS=${log-detailed} AWS_TESTING_REGION=$(region) AWS_TESTING_DB_TABLE=$(table) gucumber -go-tags "integration" ./awstesting/performance
sandbox-tests: sandbox-test-go14 sandbox-test-go15 sandbox-test-go15-novendorexp sandbox-test-go16 sandbox-test-go17 sandbox-test-gotip
sandbox-test-go14:
docker build -f ./awstesting/sandbox/Dockerfile.test.go1.4 -t "aws-sdk-go-1.4" .
docker run -t aws-sdk-go-1.4
sandbox-test-go15:
docker build -f ./awstesting/sandbox/Dockerfile.test.go1.5 -t "aws-sdk-go-1.5" .
docker run -t aws-sdk-go-1.5
sandbox-test-go15-novendorexp:
docker build -f ./awstesting/sandbox/Dockerfile.test.go1.5-novendorexp -t "aws-sdk-go-1.5-novendorexp" .
docker run -t aws-sdk-go-1.5-novendorexp
sandbox-test-go16:
docker build -f ./awstesting/sandbox/Dockerfile.test.go1.6 -t "aws-sdk-go-1.6" .
docker run -t aws-sdk-go-1.6
sandbox-test-go17:
docker build -f ./awstesting/sandbox/Dockerfile.test.go1.7 -t "aws-sdk-go-1.7" .
docker run -t aws-sdk-go-1.7
sandbox-test-gotip:
@echo "Run make update-aws-golang-tip, if this test fails because missing aws-golang:tip container"
docker build -f ./awstesting/sandbox/Dockerfile.test.gotip -t "aws-sdk-go-tip" .
docker run -t aws-sdk-go-tip
update-aws-golang-tip:
docker build -f ./awstesting/sandbox/Dockerfile.golang-tip -t "aws-golang:tip" .
verify: get-deps-verify lint vet
lint:
@echo "go lint SDK and vendor packages"
@lint=`if [ -z "${SDK_GO_1_4}" ]; then golint ./...; else echo "skipping golint"; fi`; \
lint=`echo "$$lint" | grep -E -v -e ${LINTIGNOREDOT} -e ${LINTIGNOREDOC} -e ${LINTIGNORECONST} -e ${LINTIGNORESTUTTER} -e ${LINTIGNOREINFLECT} -e ${LINTIGNOREDEPS} -e ${LINTIGNOREINFLECTS3UPLOAD}`; \
echo "$$lint"; \
if [ "$$lint" != "" ] && [ "$$lint" != "skipping golint" ]; then exit 1; fi
SDK_BASE_FOLDERS=$(shell ls -d */ | grep -v vendor | grep -v awsmigrate)
ifneq (,$(findstring go1.5, ${SDK_GO_VERSION}))
GO_VET_CMD=go tool vet --all -shadow
else ifneq (,$(findstring go1.6, ${SDK_GO_VERSION}))
GO_VET_CMD=go tool vet --all -shadow -example=false
else ifneq (,$(findstring devel, ${SDK_GO_VERSION}))
GO_VET_CMD=go tool vet --all -shadow -tests=false
else
GO_VET_CMD=echo skipping go vet, ${SDK_GO_VERSION}
endif
vet:
${GO_VET_CMD} ${SDK_BASE_FOLDERS}
get-deps: get-deps-tests get-deps-verify
@echo "go get SDK dependencies"
@go get -v $(SDK_ONLY_PKGS)
get-deps-tests:
@echo "go get SDK testing dependencies"
go get github.com/lsegal/gucumber/cmd/gucumber
go get github.com/stretchr/testify
go get github.com/smartystreets/goconvey
get-deps-verify:
@echo "go get SDK verification utilities"
@if [ -z "${SDK_GO_1_4}" ]; then go get github.com/golang/lint/golint; else echo "skipped getting golint"; fi
bench:
@echo "go bench SDK packages"
@go test -run NONE -bench . -benchmem -tags 'bench' $(SDK_ONLY_PKGS)
bench-protocol:
@echo "go bench SDK protocol marshallers"
@go test -run NONE -bench . -benchmem -tags 'bench' ./private/protocol/...
docs:
@echo "generate SDK docs"
rm -rf doc && bundle install && bundle exec yard
@# This env variable, DOCS, is for internal use
@if [ -n "$(AWS_DOC_GEN_TOOL)" ]; then echo "For internal use. Subject to change."; $(AWS_DOC_GEN_TOOL) `pwd`; fi
api_info:
@go run private/model/cli/api-info/api-info.go

View File

@@ -1,3 +0,0 @@
AWS SDK for Go
Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Copyright 2014-2015 Stripe, Inc.

View File

@@ -1,116 +0,0 @@
# AWS SDK for Go
<span style="display: inline-block;">
[![API Reference](http://img.shields.io/badge/api-reference-blue.svg)](http://docs.aws.amazon.com/sdk-for-go/api)
[![Join the chat at https://gitter.im/aws/aws-sdk-go](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/aws/aws-sdk-go?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://img.shields.io/travis/aws/aws-sdk-go.svg)](https://travis-ci.org/aws/aws-sdk-go)
[![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/aws/aws-sdk-go/blob/master/LICENSE.txt)
</span>
aws-sdk-go is the official AWS SDK for the Go programming language.
Checkout our [release notes](https://github.com/aws/aws-sdk-go/releases) for information about the latest bug fixes, updates, and features added to the SDK.
## Installing
If you are using Go 1.5 with the `GO15VENDOREXPERIMENT=1` vendoring flag, or 1.6 and higher you can use the following command to retrieve the SDK. The SDK's non-testing dependencies will be included and are vendored in the `vendor` folder.
go get -u github.com/aws/aws-sdk-go
Otherwise if your Go environment does not have vendoring support enabled, or you do not want to include the vendored SDK's dependencies you can use the following command to retrieve the SDK and its non-testing dependencies using `go get`.
go get -u github.com/aws/aws-sdk-go/aws/...
go get -u github.com/aws/aws-sdk-go/service/...
If you're looking to retrieve just the SDK without any dependencies use the following command.
go get -d github.com/aws/aws-sdk-go/
These two processes will still include the `vendor` folder and it should be deleted if its not going to be used by your environment.
rm -rf $GOPATH/src/github.com/aws/aws-sdk-go/vendor
## Reference Documentation
[`Getting Started Guide`](https://aws.amazon.com/sdk-for-go/) - This document is a general introduction how to configure and make requests with the SDK. If this is your first time using the SDK, this documentation and the API documentation will help you get started. This document focuses on the syntax and behavior of the SDK. The [Service Developer Guide](https://aws.amazon.com/documentation/) will help you get started using specific AWS services.
[`SDK API Reference Documentation`](https://docs.aws.amazon.com/sdk-for-go/api/) - Use this document to look up all API operation input and output parameters for AWS services supported by the SDK. The API reference also includes documentation of the SDK, and examples how to using the SDK, service client API operations, and API operation require parameters.
[`Service Developer Guide`](https://aws.amazon.com/documentation/) - Use this documentation to learn how to interface with an AWS service. These are great guides both, if you're getting started with a service, or looking for more information on a service. You should not need this document for coding, though in some cases, services may supply helpful samples that you might want to look out for.
[`SDK Examples`](https://github.com/aws/aws-sdk-go/tree/master/example) - Included in the SDK's repo are a several hand crafted examples using the SDK features and AWS services.
## Configuring Credentials
Before using the SDK, ensure that you've configured credentials. The best
way to configure credentials on a development machine is to use the
`~/.aws/credentials` file, which might look like:
```
[default]
aws_access_key_id = AKID1234567890
aws_secret_access_key = MY-SECRET-KEY
```
You can learn more about the credentials file from this
[blog post](http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs).
Alternatively, you can set the following environment variables:
```
AWS_ACCESS_KEY_ID=AKID1234567890
AWS_SECRET_ACCESS_KEY=MY-SECRET-KEY
```
### AWS CLI config file (`~/.aws/config`)
The AWS SDK for Go does not support the AWS CLI's config file. The SDK will not use any contents from this file. The SDK only supports the shared credentials file (`~/.aws/credentials`). #384 tracks this feature request discussion.
## Using the Go SDK
To use a service in the SDK, create a service variable by calling the `New()`
function. Once you have a service client, you can call API operations which each
return response data and a possible error.
To list a set of instance IDs from EC2, you could run:
```go
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func main() {
// Create an EC2 service object in the "us-west-2" region
// Note that you can also configure your region globally by
// exporting the AWS_REGION environment variable
svc := ec2.New(session.New(), &aws.Config{Region: aws.String("us-west-2")})
// Call the DescribeInstances Operation
resp, err := svc.DescribeInstances(nil)
if err != nil {
panic(err)
}
// resp has all of the response data, pull out instance IDs:
fmt.Println("> Number of reservation sets: ", len(resp.Reservations))
for idx, res := range resp.Reservations {
fmt.Println(" > Number of instances: ", len(res.Instances))
for _, inst := range resp.Reservations[idx].Instances {
fmt.Println(" - Instance ID: ", *inst.InstanceId)
}
}
}
```
You can find more information and operations in our
[API documentation](http://docs.aws.amazon.com/sdk-for-go/api/).
## License
This SDK is distributed under the
[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0),
see LICENSE.txt and NOTICE.txt for more information.

View File

@@ -1,145 +0,0 @@
// Package awserr represents API error interface accessors for the SDK.
package awserr
// An Error wraps lower level errors with code, message and an original error.
// The underlying concrete error type may also satisfy other interfaces which
// can be to used to obtain more specific information about the error.
//
// Calling Error() or String() will always include the full information about
// an error based on its underlying type.
//
// Example:
//
// output, err := s3manage.Upload(svc, input, opts)
// if err != nil {
// if awsErr, ok := err.(awserr.Error); ok {
// // Get error details
// log.Println("Error:", awsErr.Code(), awsErr.Message())
//
// // Prints out full error message, including original error if there was one.
// log.Println("Error:", awsErr.Error())
//
// // Get original error
// if origErr := awsErr.OrigErr(); origErr != nil {
// // operate on original error.
// }
// } else {
// fmt.Println(err.Error())
// }
// }
//
type Error interface {
// Satisfy the generic error interface.
error
// Returns the short phrase depicting the classification of the error.
Code() string
// Returns the error details message.
Message() string
// Returns the original error if one was set. Nil is returned if not set.
OrigErr() error
}
// BatchError is a batch of errors which also wraps lower level errors with
// code, message, and original errors. Calling Error() will include all errors
// that occured in the batch.
//
// Deprecated: Replaced with BatchedErrors. Only defined for backwards
// compatibility.
type BatchError interface {
// Satisfy the generic error interface.
error
// Returns the short phrase depicting the classification of the error.
Code() string
// Returns the error details message.
Message() string
// Returns the original error if one was set. Nil is returned if not set.
OrigErrs() []error
}
// BatchedErrors is a batch of errors which also wraps lower level errors with
// code, message, and original errors. Calling Error() will include all errors
// that occured in the batch.
//
// Replaces BatchError
type BatchedErrors interface {
// Satisfy the base Error interface.
Error
// Returns the original error if one was set. Nil is returned if not set.
OrigErrs() []error
}
// New returns an Error object described by the code, message, and origErr.
//
// If origErr satisfies the Error interface it will not be wrapped within a new
// Error object and will instead be returned.
func New(code, message string, origErr error) Error {
var errs []error
if origErr != nil {
errs = append(errs, origErr)
}
return newBaseError(code, message, errs)
}
// NewBatchError returns an BatchedErrors with a collection of errors as an
// array of errors.
func NewBatchError(code, message string, errs []error) BatchedErrors {
return newBaseError(code, message, errs)
}
// A RequestFailure is an interface to extract request failure information from
// an Error such as the request ID of the failed request returned by a service.
// RequestFailures may not always have a requestID value if the request failed
// prior to reaching the service such as a connection error.
//
// Example:
//
// output, err := s3manage.Upload(svc, input, opts)
// if err != nil {
// if reqerr, ok := err.(RequestFailure); ok {
// log.Println("Request failed", reqerr.Code(), reqerr.Message(), reqerr.RequestID())
// } else {
// log.Println("Error:", err.Error())
// }
// }
//
// Combined with awserr.Error:
//
// output, err := s3manage.Upload(svc, input, opts)
// if err != nil {
// if awsErr, ok := err.(awserr.Error); ok {
// // Generic AWS Error with Code, Message, and original error (if any)
// fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
//
// if reqErr, ok := err.(awserr.RequestFailure); ok {
// // A service error occurred
// fmt.Println(reqErr.StatusCode(), reqErr.RequestID())
// }
// } else {
// fmt.Println(err.Error())
// }
// }
//
type RequestFailure interface {
Error
// The status code of the HTTP response.
StatusCode() int
// The request ID returned by the service for a request failure. This will
// be empty if no request ID is available such as the request failed due
// to a connection error.
RequestID() string
}
// NewRequestFailure returns a new request error wrapper for the given Error
// provided.
func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure {
return newRequestError(err, statusCode, reqID)
}

Some files were not shown because too many files have changed in this diff Show More