update vendor/ dir to latest w/o heroku, moby

had to lock a lot of things in place
This commit is contained in:
Reed Allman
2017-08-03 02:38:15 -07:00
parent 780791da1c
commit 30f3c45dbc
5637 changed files with 191713 additions and 1133103 deletions

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,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)
}

View File

@@ -1,194 +0,0 @@
package awserr
import "fmt"
// SprintError returns a string of the formatted error code.
//
// Both extra and origErr are optional. If they are included their lines
// will be added, but if they are not included their lines will be ignored.
func SprintError(code, message, extra string, origErr error) string {
msg := fmt.Sprintf("%s: %s", code, message)
if extra != "" {
msg = fmt.Sprintf("%s\n\t%s", msg, extra)
}
if origErr != nil {
msg = fmt.Sprintf("%s\ncaused by: %s", msg, origErr.Error())
}
return msg
}
// A baseError wraps the code and message which defines an error. It also
// can be used to wrap an original error object.
//
// Should be used as the root for errors satisfying the awserr.Error. Also
// for any error which does not fit into a specific error wrapper type.
type baseError struct {
// Classification of error
code string
// Detailed information about error
message string
// Optional original error this error is based off of. Allows building
// chained errors.
errs []error
}
// newBaseError returns an error object for the code, message, and errors.
//
// code is a short no whitespace phrase depicting the classification of
// the error that is being created.
//
// message is the free flow string containing detailed information about the
// error.
//
// origErrs is the error objects which will be nested under the new errors to
// be returned.
func newBaseError(code, message string, origErrs []error) *baseError {
b := &baseError{
code: code,
message: message,
errs: origErrs,
}
return b
}
// Error returns the string representation of the error.
//
// See ErrorWithExtra for formatting.
//
// Satisfies the error interface.
func (b baseError) Error() string {
size := len(b.errs)
if size > 0 {
return SprintError(b.code, b.message, "", errorList(b.errs))
}
return SprintError(b.code, b.message, "", nil)
}
// String returns the string representation of the error.
// Alias for Error to satisfy the stringer interface.
func (b baseError) String() string {
return b.Error()
}
// Code returns the short phrase depicting the classification of the error.
func (b baseError) Code() string {
return b.code
}
// Message returns the error details message.
func (b baseError) Message() string {
return b.message
}
// OrigErr returns the original error if one was set. Nil is returned if no
// error was set. This only returns the first element in the list. If the full
// list is needed, use BatchedErrors.
func (b baseError) OrigErr() error {
switch len(b.errs) {
case 0:
return nil
case 1:
return b.errs[0]
default:
if err, ok := b.errs[0].(Error); ok {
return NewBatchError(err.Code(), err.Message(), b.errs[1:])
}
return NewBatchError("BatchedErrors",
"multiple errors occured", b.errs)
}
}
// OrigErrs returns the original errors if one was set. An empty slice is
// returned if no error was set.
func (b baseError) OrigErrs() []error {
return b.errs
}
// So that the Error interface type can be included as an anonymous field
// in the requestError struct and not conflict with the error.Error() method.
type awsError Error
// A requestError wraps a request or service error.
//
// Composed of baseError for code, message, and original error.
type requestError struct {
awsError
statusCode int
requestID string
}
// newRequestError returns a wrapped error with additional information for
// request status code, and service requestID.
//
// Should be used to wrap all request which involve service requests. Even if
// the request failed without a service response, but had an HTTP status code
// that may be meaningful.
//
// Also wraps original errors via the baseError.
func newRequestError(err Error, statusCode int, requestID string) *requestError {
return &requestError{
awsError: err,
statusCode: statusCode,
requestID: requestID,
}
}
// Error returns the string representation of the error.
// Satisfies the error interface.
func (r requestError) Error() string {
extra := fmt.Sprintf("status code: %d, request id: %s",
r.statusCode, r.requestID)
return SprintError(r.Code(), r.Message(), extra, r.OrigErr())
}
// String returns the string representation of the error.
// Alias for Error to satisfy the stringer interface.
func (r requestError) String() string {
return r.Error()
}
// StatusCode returns the wrapped status code for the error
func (r requestError) StatusCode() int {
return r.statusCode
}
// RequestID returns the wrapped requestID
func (r requestError) RequestID() string {
return r.requestID
}
// OrigErrs returns the original errors if one was set. An empty slice is
// returned if no error was set.
func (r requestError) OrigErrs() []error {
if b, ok := r.awsError.(BatchedErrors); ok {
return b.OrigErrs()
}
return []error{r.OrigErr()}
}
// An error list that satisfies the golang interface
type errorList []error
// Error returns the string representation of the error.
//
// Satisfies the error interface.
func (e errorList) Error() string {
msg := ""
// How do we want to handle the array size being zero
if size := len(e); size > 0 {
for i := 0; i < size; i++ {
msg += fmt.Sprintf("%s", e[i].Error())
// We check the next index to see if it is within the slice.
// If it is, then we append a newline. We do this, because unit tests
// could be broken with the additional '\n'
if i+1 < size {
msg += "\n"
}
}
}
return msg
}

View File

@@ -1,100 +0,0 @@
package awsutil
import (
"io"
"reflect"
)
// Copy deeply copies a src structure to dst. Useful for copying request and
// response structures.
//
// Can copy between structs of different type, but will only copy fields which
// are assignable, and exist in both structs. Fields which are not assignable,
// or do not exist in both structs are ignored.
func Copy(dst, src interface{}) {
dstval := reflect.ValueOf(dst)
if !dstval.IsValid() {
panic("Copy dst cannot be nil")
}
rcopy(dstval, reflect.ValueOf(src), true)
}
// CopyOf returns a copy of src while also allocating the memory for dst.
// src must be a pointer type or this operation will fail.
func CopyOf(src interface{}) (dst interface{}) {
dsti := reflect.New(reflect.TypeOf(src).Elem())
dst = dsti.Interface()
rcopy(dsti, reflect.ValueOf(src), true)
return
}
// rcopy performs a recursive copy of values from the source to destination.
//
// root is used to skip certain aspects of the copy which are not valid
// for the root node of a object.
func rcopy(dst, src reflect.Value, root bool) {
if !src.IsValid() {
return
}
switch src.Kind() {
case reflect.Ptr:
if _, ok := src.Interface().(io.Reader); ok {
if dst.Kind() == reflect.Ptr && dst.Elem().CanSet() {
dst.Elem().Set(src)
} else if dst.CanSet() {
dst.Set(src)
}
} else {
e := src.Type().Elem()
if dst.CanSet() && !src.IsNil() {
dst.Set(reflect.New(e))
}
if src.Elem().IsValid() {
// Keep the current root state since the depth hasn't changed
rcopy(dst.Elem(), src.Elem(), root)
}
}
case reflect.Struct:
t := dst.Type()
for i := 0; i < t.NumField(); i++ {
name := t.Field(i).Name
srcVal := src.FieldByName(name)
dstVal := dst.FieldByName(name)
if srcVal.IsValid() && dstVal.CanSet() {
rcopy(dstVal, srcVal, false)
}
}
case reflect.Slice:
if src.IsNil() {
break
}
s := reflect.MakeSlice(src.Type(), src.Len(), src.Cap())
dst.Set(s)
for i := 0; i < src.Len(); i++ {
rcopy(dst.Index(i), src.Index(i), false)
}
case reflect.Map:
if src.IsNil() {
break
}
s := reflect.MakeMap(src.Type())
dst.Set(s)
for _, k := range src.MapKeys() {
v := src.MapIndex(k)
v2 := reflect.New(v.Type()).Elem()
rcopy(v2, v, false)
dst.SetMapIndex(k, v2)
}
default:
// Assign the value if possible. If its not assignable, the value would
// need to be converted and the impact of that may be unexpected, or is
// not compatible with the dst type.
if src.Type().AssignableTo(dst.Type()) {
dst.Set(src)
}
}
}

View File

@@ -1,233 +0,0 @@
package awsutil_test
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"testing"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/stretchr/testify/assert"
)
func ExampleCopy() {
type Foo struct {
A int
B []*string
}
// Create the initial value
str1 := "hello"
str2 := "bye bye"
f1 := &Foo{A: 1, B: []*string{&str1, &str2}}
// Do the copy
var f2 Foo
awsutil.Copy(&f2, f1)
// Print the result
fmt.Println(awsutil.Prettify(f2))
// Output:
// {
// A: 1,
// B: ["hello","bye bye"]
// }
}
func TestCopy(t *testing.T) {
type Foo struct {
A int
B []*string
C map[string]*int
}
// Create the initial value
str1 := "hello"
str2 := "bye bye"
int1 := 1
int2 := 2
f1 := &Foo{
A: 1,
B: []*string{&str1, &str2},
C: map[string]*int{
"A": &int1,
"B": &int2,
},
}
// Do the copy
var f2 Foo
awsutil.Copy(&f2, f1)
// Values are equal
assert.Equal(t, f2.A, f1.A)
assert.Equal(t, f2.B, f1.B)
assert.Equal(t, f2.C, f1.C)
// But pointers are not!
str3 := "nothello"
int3 := 57
f2.A = 100
f2.B[0] = &str3
f2.C["B"] = &int3
assert.NotEqual(t, f2.A, f1.A)
assert.NotEqual(t, f2.B, f1.B)
assert.NotEqual(t, f2.C, f1.C)
}
func TestCopyNestedWithUnexported(t *testing.T) {
type Bar struct {
a int
B int
}
type Foo struct {
A string
B Bar
}
f1 := &Foo{A: "string", B: Bar{a: 1, B: 2}}
var f2 Foo
awsutil.Copy(&f2, f1)
// Values match
assert.Equal(t, f2.A, f1.A)
assert.NotEqual(t, f2.B, f1.B)
assert.NotEqual(t, f2.B.a, f1.B.a)
assert.Equal(t, f2.B.B, f2.B.B)
}
func TestCopyIgnoreNilMembers(t *testing.T) {
type Foo struct {
A *string
B []string
C map[string]string
}
f := &Foo{}
assert.Nil(t, f.A)
assert.Nil(t, f.B)
assert.Nil(t, f.C)
var f2 Foo
awsutil.Copy(&f2, f)
assert.Nil(t, f2.A)
assert.Nil(t, f2.B)
assert.Nil(t, f2.C)
fcopy := awsutil.CopyOf(f)
f3 := fcopy.(*Foo)
assert.Nil(t, f3.A)
assert.Nil(t, f3.B)
assert.Nil(t, f3.C)
}
func TestCopyPrimitive(t *testing.T) {
str := "hello"
var s string
awsutil.Copy(&s, &str)
assert.Equal(t, "hello", s)
}
func TestCopyNil(t *testing.T) {
var s string
awsutil.Copy(&s, nil)
assert.Equal(t, "", s)
}
func TestCopyReader(t *testing.T) {
var buf io.Reader = bytes.NewReader([]byte("hello world"))
var r io.Reader
awsutil.Copy(&r, buf)
b, err := ioutil.ReadAll(r)
assert.NoError(t, err)
assert.Equal(t, []byte("hello world"), b)
// empty bytes because this is not a deep copy
b, err = ioutil.ReadAll(buf)
assert.NoError(t, err)
assert.Equal(t, []byte(""), b)
}
func TestCopyDifferentStructs(t *testing.T) {
type SrcFoo struct {
A int
B []*string
C map[string]*int
SrcUnique string
SameNameDiffType int
unexportedPtr *int
ExportedPtr *int
}
type DstFoo struct {
A int
B []*string
C map[string]*int
DstUnique int
SameNameDiffType string
unexportedPtr *int
ExportedPtr *int
}
// Create the initial value
str1 := "hello"
str2 := "bye bye"
int1 := 1
int2 := 2
f1 := &SrcFoo{
A: 1,
B: []*string{&str1, &str2},
C: map[string]*int{
"A": &int1,
"B": &int2,
},
SrcUnique: "unique",
SameNameDiffType: 1,
unexportedPtr: &int1,
ExportedPtr: &int2,
}
// Do the copy
var f2 DstFoo
awsutil.Copy(&f2, f1)
// Values are equal
assert.Equal(t, f2.A, f1.A)
assert.Equal(t, f2.B, f1.B)
assert.Equal(t, f2.C, f1.C)
assert.Equal(t, "unique", f1.SrcUnique)
assert.Equal(t, 1, f1.SameNameDiffType)
assert.Equal(t, 0, f2.DstUnique)
assert.Equal(t, "", f2.SameNameDiffType)
assert.Equal(t, int1, *f1.unexportedPtr)
assert.Nil(t, f2.unexportedPtr)
assert.Equal(t, int2, *f1.ExportedPtr)
assert.Equal(t, int2, *f2.ExportedPtr)
}
func ExampleCopyOf() {
type Foo struct {
A int
B []*string
}
// Create the initial value
str1 := "hello"
str2 := "bye bye"
f1 := &Foo{A: 1, B: []*string{&str1, &str2}}
// Do the copy
v := awsutil.CopyOf(f1)
var f2 *Foo = v.(*Foo)
// Print the result
fmt.Println(awsutil.Prettify(f2))
// Output:
// {
// A: 1,
// B: ["hello","bye bye"]
// }
}

View File

@@ -1,27 +0,0 @@
package awsutil
import (
"reflect"
)
// DeepEqual returns if the two values are deeply equal like reflect.DeepEqual.
// In addition to this, this method will also dereference the input values if
// possible so the DeepEqual performed will not fail if one parameter is a
// pointer and the other is not.
//
// DeepEqual will not perform indirection of nested values of the input parameters.
func DeepEqual(a, b interface{}) bool {
ra := reflect.Indirect(reflect.ValueOf(a))
rb := reflect.Indirect(reflect.ValueOf(b))
if raValid, rbValid := ra.IsValid(), rb.IsValid(); !raValid && !rbValid {
// If the elements are both nil, and of the same type the are equal
// If they are of different types they are not equal
return reflect.TypeOf(a) == reflect.TypeOf(b)
} else if raValid != rbValid {
// Both values must be valid to be equal
return false
}
return reflect.DeepEqual(ra.Interface(), rb.Interface())
}

View File

@@ -1,29 +0,0 @@
package awsutil_test
import (
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/stretchr/testify/assert"
)
func TestDeepEqual(t *testing.T) {
cases := []struct {
a, b interface{}
equal bool
}{
{"a", "a", true},
{"a", "b", false},
{"a", aws.String(""), false},
{"a", nil, false},
{"a", aws.String("a"), true},
{(*bool)(nil), (*bool)(nil), true},
{(*bool)(nil), (*string)(nil), false},
{nil, nil, true},
}
for i, c := range cases {
assert.Equal(t, c.equal, awsutil.DeepEqual(c.a, c.b), "%d, a:%v b:%v, %t", i, c.a, c.b, c.equal)
}
}

View File

@@ -1,222 +0,0 @@
package awsutil
import (
"reflect"
"regexp"
"strconv"
"strings"
"github.com/jmespath/go-jmespath"
)
var indexRe = regexp.MustCompile(`(.+)\[(-?\d+)?\]$`)
// rValuesAtPath returns a slice of values found in value v. The values
// in v are explored recursively so all nested values are collected.
func rValuesAtPath(v interface{}, path string, createPath, caseSensitive, nilTerm bool) []reflect.Value {
pathparts := strings.Split(path, "||")
if len(pathparts) > 1 {
for _, pathpart := range pathparts {
vals := rValuesAtPath(v, pathpart, createPath, caseSensitive, nilTerm)
if len(vals) > 0 {
return vals
}
}
return nil
}
values := []reflect.Value{reflect.Indirect(reflect.ValueOf(v))}
components := strings.Split(path, ".")
for len(values) > 0 && len(components) > 0 {
var index *int64
var indexStar bool
c := strings.TrimSpace(components[0])
if c == "" { // no actual component, illegal syntax
return nil
} else if caseSensitive && c != "*" && strings.ToLower(c[0:1]) == c[0:1] {
// TODO normalize case for user
return nil // don't support unexported fields
}
// parse this component
if m := indexRe.FindStringSubmatch(c); m != nil {
c = m[1]
if m[2] == "" {
index = nil
indexStar = true
} else {
i, _ := strconv.ParseInt(m[2], 10, 32)
index = &i
indexStar = false
}
}
nextvals := []reflect.Value{}
for _, value := range values {
// pull component name out of struct member
if value.Kind() != reflect.Struct {
continue
}
if c == "*" { // pull all members
for i := 0; i < value.NumField(); i++ {
if f := reflect.Indirect(value.Field(i)); f.IsValid() {
nextvals = append(nextvals, f)
}
}
continue
}
value = value.FieldByNameFunc(func(name string) bool {
if c == name {
return true
} else if !caseSensitive && strings.ToLower(name) == strings.ToLower(c) {
return true
}
return false
})
if nilTerm && value.Kind() == reflect.Ptr && len(components[1:]) == 0 {
if !value.IsNil() {
value.Set(reflect.Zero(value.Type()))
}
return []reflect.Value{value}
}
if createPath && value.Kind() == reflect.Ptr && value.IsNil() {
// TODO if the value is the terminus it should not be created
// if the value to be set to its position is nil.
value.Set(reflect.New(value.Type().Elem()))
value = value.Elem()
} else {
value = reflect.Indirect(value)
}
if value.Kind() == reflect.Slice || value.Kind() == reflect.Map {
if !createPath && value.IsNil() {
value = reflect.ValueOf(nil)
}
}
if value.IsValid() {
nextvals = append(nextvals, value)
}
}
values = nextvals
if indexStar || index != nil {
nextvals = []reflect.Value{}
for _, value := range values {
value := reflect.Indirect(value)
if value.Kind() != reflect.Slice {
continue
}
if indexStar { // grab all indices
for i := 0; i < value.Len(); i++ {
idx := reflect.Indirect(value.Index(i))
if idx.IsValid() {
nextvals = append(nextvals, idx)
}
}
continue
}
// pull out index
i := int(*index)
if i >= value.Len() { // check out of bounds
if createPath {
// TODO resize slice
} else {
continue
}
} else if i < 0 { // support negative indexing
i = value.Len() + i
}
value = reflect.Indirect(value.Index(i))
if value.Kind() == reflect.Slice || value.Kind() == reflect.Map {
if !createPath && value.IsNil() {
value = reflect.ValueOf(nil)
}
}
if value.IsValid() {
nextvals = append(nextvals, value)
}
}
values = nextvals
}
components = components[1:]
}
return values
}
// ValuesAtPath returns a list of values at the case insensitive lexical
// path inside of a structure.
func ValuesAtPath(i interface{}, path string) ([]interface{}, error) {
result, err := jmespath.Search(path, i)
if err != nil {
return nil, err
}
v := reflect.ValueOf(result)
if !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) {
return nil, nil
}
if s, ok := result.([]interface{}); ok {
return s, err
}
if v.Kind() == reflect.Map && v.Len() == 0 {
return nil, nil
}
if v.Kind() == reflect.Slice {
out := make([]interface{}, v.Len())
for i := 0; i < v.Len(); i++ {
out[i] = v.Index(i).Interface()
}
return out, nil
}
return []interface{}{result}, nil
}
// SetValueAtPath sets a value at the case insensitive lexical path inside
// of a structure.
func SetValueAtPath(i interface{}, path string, v interface{}) {
if rvals := rValuesAtPath(i, path, true, false, v == nil); rvals != nil {
for _, rval := range rvals {
if rval.Kind() == reflect.Ptr && rval.IsNil() {
continue
}
setValue(rval, v)
}
}
}
func setValue(dstVal reflect.Value, src interface{}) {
if dstVal.Kind() == reflect.Ptr {
dstVal = reflect.Indirect(dstVal)
}
srcVal := reflect.ValueOf(src)
if !srcVal.IsValid() { // src is literal nil
if dstVal.CanAddr() {
// Convert to pointer so that pointer's value can be nil'ed
// dstVal = dstVal.Addr()
}
dstVal.Set(reflect.Zero(dstVal.Type()))
} else if srcVal.Kind() == reflect.Ptr {
if srcVal.IsNil() {
srcVal = reflect.Zero(dstVal.Type())
} else {
srcVal = reflect.ValueOf(src).Elem()
}
dstVal.Set(srcVal)
} else {
dstVal.Set(srcVal)
}
}

View File

@@ -1,142 +0,0 @@
package awsutil_test
import (
"testing"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/stretchr/testify/assert"
)
type Struct struct {
A []Struct
z []Struct
B *Struct
D *Struct
C string
E map[string]string
}
var data = Struct{
A: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}},
z: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}},
B: &Struct{B: &Struct{C: "terminal"}, D: &Struct{C: "terminal2"}},
C: "initial",
}
var data2 = Struct{A: []Struct{
{A: []Struct{{C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}}},
{A: []Struct{{C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}}},
}}
func TestValueAtPathSuccess(t *testing.T) {
var testCases = []struct {
expect []interface{}
data interface{}
path string
}{
{[]interface{}{"initial"}, data, "C"},
{[]interface{}{"value1"}, data, "A[0].C"},
{[]interface{}{"value2"}, data, "A[1].C"},
{[]interface{}{"value3"}, data, "A[2].C"},
{[]interface{}{"value3"}, data, "a[2].c"},
{[]interface{}{"value3"}, data, "A[-1].C"},
{[]interface{}{"value1", "value2", "value3"}, data, "A[].C"},
{[]interface{}{"terminal"}, data, "B . B . C"},
{[]interface{}{"initial"}, data, "A.D.X || C"},
{[]interface{}{"initial"}, data, "A[0].B || C"},
{[]interface{}{
Struct{A: []Struct{{C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}}},
Struct{A: []Struct{{C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}}},
}, data2, "A"},
}
for i, c := range testCases {
v, err := awsutil.ValuesAtPath(c.data, c.path)
assert.NoError(t, err, "case %d, expected no error, %s", i, c.path)
assert.Equal(t, c.expect, v, "case %d, %s", i, c.path)
}
}
func TestValueAtPathFailure(t *testing.T) {
var testCases = []struct {
expect []interface{}
errContains string
data interface{}
path string
}{
{nil, "", data, "C.x"},
{nil, "SyntaxError: Invalid token: tDot", data, ".x"},
{nil, "", data, "X.Y.Z"},
{nil, "", data, "A[100].C"},
{nil, "", data, "A[3].C"},
{nil, "", data, "B.B.C.Z"},
{nil, "", data, "z[-1].C"},
{nil, "", nil, "A.B.C"},
{[]interface{}{}, "", Struct{}, "A"},
{nil, "", data, "A[0].B.C"},
{nil, "", data, "D"},
}
for i, c := range testCases {
v, err := awsutil.ValuesAtPath(c.data, c.path)
if c.errContains != "" {
assert.Contains(t, err.Error(), c.errContains, "case %d, expected error, %s", i, c.path)
continue
} else {
assert.NoError(t, err, "case %d, expected no error, %s", i, c.path)
}
assert.Equal(t, c.expect, v, "case %d, %s", i, c.path)
}
}
func TestSetValueAtPathSuccess(t *testing.T) {
var s Struct
awsutil.SetValueAtPath(&s, "C", "test1")
awsutil.SetValueAtPath(&s, "B.B.C", "test2")
awsutil.SetValueAtPath(&s, "B.D.C", "test3")
assert.Equal(t, "test1", s.C)
assert.Equal(t, "test2", s.B.B.C)
assert.Equal(t, "test3", s.B.D.C)
awsutil.SetValueAtPath(&s, "B.*.C", "test0")
assert.Equal(t, "test0", s.B.B.C)
assert.Equal(t, "test0", s.B.D.C)
var s2 Struct
awsutil.SetValueAtPath(&s2, "b.b.c", "test0")
assert.Equal(t, "test0", s2.B.B.C)
awsutil.SetValueAtPath(&s2, "A", []Struct{{}})
assert.Equal(t, []Struct{{}}, s2.A)
str := "foo"
s3 := Struct{}
awsutil.SetValueAtPath(&s3, "b.b.c", str)
assert.Equal(t, "foo", s3.B.B.C)
s3 = Struct{B: &Struct{B: &Struct{C: str}}}
awsutil.SetValueAtPath(&s3, "b.b.c", nil)
assert.Equal(t, "", s3.B.B.C)
s3 = Struct{}
awsutil.SetValueAtPath(&s3, "b.b.c", nil)
assert.Equal(t, "", s3.B.B.C)
s3 = Struct{}
awsutil.SetValueAtPath(&s3, "b.b.c", &str)
assert.Equal(t, "foo", s3.B.B.C)
var s4 struct{ Name *string }
awsutil.SetValueAtPath(&s4, "Name", str)
assert.Equal(t, str, *s4.Name)
s4 = struct{ Name *string }{}
awsutil.SetValueAtPath(&s4, "Name", nil)
assert.Equal(t, (*string)(nil), s4.Name)
s4 = struct{ Name *string }{Name: &str}
awsutil.SetValueAtPath(&s4, "Name", nil)
assert.Equal(t, (*string)(nil), s4.Name)
s4 = struct{ Name *string }{}
awsutil.SetValueAtPath(&s4, "Name", &str)
assert.Equal(t, str, *s4.Name)
}

View File

@@ -1,107 +0,0 @@
package awsutil
import (
"bytes"
"fmt"
"io"
"reflect"
"strings"
)
// Prettify returns the string representation of a value.
func Prettify(i interface{}) string {
var buf bytes.Buffer
prettify(reflect.ValueOf(i), 0, &buf)
return buf.String()
}
// prettify will recursively walk value v to build a textual
// representation of the value.
func prettify(v reflect.Value, indent int, buf *bytes.Buffer) {
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
switch v.Kind() {
case reflect.Struct:
strtype := v.Type().String()
if strtype == "time.Time" {
fmt.Fprintf(buf, "%s", v.Interface())
break
} else if strings.HasPrefix(strtype, "io.") {
buf.WriteString("<buffer>")
break
}
buf.WriteString("{\n")
names := []string{}
for i := 0; i < v.Type().NumField(); i++ {
name := v.Type().Field(i).Name
f := v.Field(i)
if name[0:1] == strings.ToLower(name[0:1]) {
continue // ignore unexported fields
}
if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice || f.Kind() == reflect.Map) && f.IsNil() {
continue // ignore unset fields
}
names = append(names, name)
}
for i, n := range names {
val := v.FieldByName(n)
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString(n + ": ")
prettify(val, indent+2, buf)
if i < len(names)-1 {
buf.WriteString(",\n")
}
}
buf.WriteString("\n" + strings.Repeat(" ", indent) + "}")
case reflect.Slice:
nl, id, id2 := "", "", ""
if v.Len() > 3 {
nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2)
}
buf.WriteString("[" + nl)
for i := 0; i < v.Len(); i++ {
buf.WriteString(id2)
prettify(v.Index(i), indent+2, buf)
if i < v.Len()-1 {
buf.WriteString("," + nl)
}
}
buf.WriteString(nl + id + "]")
case reflect.Map:
buf.WriteString("{\n")
for i, k := range v.MapKeys() {
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString(k.String() + ": ")
prettify(v.MapIndex(k), indent+2, buf)
if i < v.Len()-1 {
buf.WriteString(",\n")
}
}
buf.WriteString("\n" + strings.Repeat(" ", indent) + "}")
default:
if !v.IsValid() {
fmt.Fprint(buf, "<invalid value>")
return
}
format := "%v"
switch v.Interface().(type) {
case string:
format = "%q"
case io.ReadSeeker, io.Reader:
format = "buffer(%p)"
}
fmt.Fprintf(buf, format, v.Interface())
}
}

View File

@@ -1,89 +0,0 @@
package awsutil
import (
"bytes"
"fmt"
"reflect"
"strings"
)
// StringValue returns the string representation of a value.
func StringValue(i interface{}) string {
var buf bytes.Buffer
stringValue(reflect.ValueOf(i), 0, &buf)
return buf.String()
}
func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) {
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
switch v.Kind() {
case reflect.Struct:
buf.WriteString("{\n")
names := []string{}
for i := 0; i < v.Type().NumField(); i++ {
name := v.Type().Field(i).Name
f := v.Field(i)
if name[0:1] == strings.ToLower(name[0:1]) {
continue // ignore unexported fields
}
if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice) && f.IsNil() {
continue // ignore unset fields
}
names = append(names, name)
}
for i, n := range names {
val := v.FieldByName(n)
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString(n + ": ")
stringValue(val, indent+2, buf)
if i < len(names)-1 {
buf.WriteString(",\n")
}
}
buf.WriteString("\n" + strings.Repeat(" ", indent) + "}")
case reflect.Slice:
nl, id, id2 := "", "", ""
if v.Len() > 3 {
nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2)
}
buf.WriteString("[" + nl)
for i := 0; i < v.Len(); i++ {
buf.WriteString(id2)
stringValue(v.Index(i), indent+2, buf)
if i < v.Len()-1 {
buf.WriteString("," + nl)
}
}
buf.WriteString(nl + id + "]")
case reflect.Map:
buf.WriteString("{\n")
for i, k := range v.MapKeys() {
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString(k.String() + ": ")
stringValue(v.MapIndex(k), indent+2, buf)
if i < v.Len()-1 {
buf.WriteString(",\n")
}
}
buf.WriteString("\n" + strings.Repeat(" ", indent) + "}")
default:
format := "%v"
switch v.Interface().(type) {
case string:
format = "%q"
}
fmt.Fprintf(buf, format, v.Interface())
}
}

View File

@@ -1,120 +0,0 @@
package client
import (
"fmt"
"io/ioutil"
"net/http/httputil"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
)
// A Config provides configuration to a service client instance.
type Config struct {
Config *aws.Config
Handlers request.Handlers
Endpoint, SigningRegion string
}
// ConfigProvider provides a generic way for a service client to receive
// the ClientConfig without circular dependencies.
type ConfigProvider interface {
ClientConfig(serviceName string, cfgs ...*aws.Config) Config
}
// A Client implements the base client request and response handling
// used by all service clients.
type Client struct {
request.Retryer
metadata.ClientInfo
Config aws.Config
Handlers request.Handlers
}
// New will return a pointer to a new initialized service client.
func New(cfg aws.Config, info metadata.ClientInfo, handlers request.Handlers, options ...func(*Client)) *Client {
svc := &Client{
Config: cfg,
ClientInfo: info,
Handlers: handlers,
}
switch retryer, ok := cfg.Retryer.(request.Retryer); {
case ok:
svc.Retryer = retryer
case cfg.Retryer != nil && cfg.Logger != nil:
s := fmt.Sprintf("WARNING: %T does not implement request.Retryer; using DefaultRetryer instead", cfg.Retryer)
cfg.Logger.Log(s)
fallthrough
default:
maxRetries := aws.IntValue(cfg.MaxRetries)
if cfg.MaxRetries == nil || maxRetries == aws.UseServiceDefaultRetries {
maxRetries = 3
}
svc.Retryer = DefaultRetryer{NumMaxRetries: maxRetries}
}
svc.AddDebugHandlers()
for _, option := range options {
option(svc)
}
return svc
}
// NewRequest returns a new Request pointer for the service API
// operation and parameters.
func (c *Client) NewRequest(operation *request.Operation, params interface{}, data interface{}) *request.Request {
return request.New(c.Config, c.ClientInfo, c.Handlers, c.Retryer, operation, params, data)
}
// AddDebugHandlers injects debug logging handlers into the service to log request
// debug information.
func (c *Client) AddDebugHandlers() {
if !c.Config.LogLevel.AtLeast(aws.LogDebug) {
return
}
c.Handlers.Send.PushFront(logRequest)
c.Handlers.Send.PushBack(logResponse)
}
const logReqMsg = `DEBUG: Request %s/%s Details:
---[ REQUEST POST-SIGN ]-----------------------------
%s
-----------------------------------------------------`
func logRequest(r *request.Request) {
logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody)
dumpedBody, _ := httputil.DumpRequestOut(r.HTTPRequest, logBody)
if logBody {
// Reset the request body because dumpRequest will re-wrap the r.HTTPRequest's
// Body as a NoOpCloser and will not be reset after read by the HTTP
// client reader.
r.Body.Seek(r.BodyStart, 0)
r.HTTPRequest.Body = ioutil.NopCloser(r.Body)
}
r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.ClientInfo.ServiceName, r.Operation.Name, string(dumpedBody)))
}
const logRespMsg = `DEBUG: Response %s/%s Details:
---[ RESPONSE ]--------------------------------------
%s
-----------------------------------------------------`
func logResponse(r *request.Request) {
var msg = "no response data"
if r.HTTPResponse != nil {
logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody)
dumpedBody, _ := httputil.DumpResponse(r.HTTPResponse, logBody)
msg = string(dumpedBody)
} else if r.Error != nil {
msg = r.Error.Error()
}
r.Config.Logger.Log(fmt.Sprintf(logRespMsg, r.ClientInfo.ServiceName, r.Operation.Name, msg))
}

View File

@@ -1,90 +0,0 @@
package client
import (
"math/rand"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws/request"
)
// DefaultRetryer implements basic retry logic using exponential backoff for
// most services. If you want to implement custom retry logic, implement the
// request.Retryer interface or create a structure type that composes this
// struct and override the specific methods. For example, to override only
// the MaxRetries method:
//
// type retryer struct {
// service.DefaultRetryer
// }
//
// // This implementation always has 100 max retries
// func (d retryer) MaxRetries() uint { return 100 }
type DefaultRetryer struct {
NumMaxRetries int
}
// MaxRetries returns the number of maximum returns the service will use to make
// an individual API request.
func (d DefaultRetryer) MaxRetries() int {
return d.NumMaxRetries
}
var seededRand = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())})
// RetryRules returns the delay duration before retrying this request again
func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration {
// Set the upper limit of delay in retrying at ~five minutes
minTime := 30
throttle := d.shouldThrottle(r)
if throttle {
minTime = 500
}
retryCount := r.RetryCount
if retryCount > 13 {
retryCount = 13
} else if throttle && retryCount > 8 {
retryCount = 8
}
delay := (1 << uint(retryCount)) * (seededRand.Intn(minTime) + minTime)
return time.Duration(delay) * time.Millisecond
}
// ShouldRetry returns true if the request should be retried.
func (d DefaultRetryer) ShouldRetry(r *request.Request) bool {
if r.HTTPResponse.StatusCode >= 500 {
return true
}
return r.IsErrorRetryable() || d.shouldThrottle(r)
}
// ShouldThrottle returns true if the request should be throttled.
func (d DefaultRetryer) shouldThrottle(r *request.Request) bool {
if r.HTTPResponse.StatusCode == 502 ||
r.HTTPResponse.StatusCode == 503 ||
r.HTTPResponse.StatusCode == 504 {
return true
}
return r.IsErrorThrottle()
}
// lockedSource is a thread-safe implementation of rand.Source
type lockedSource struct {
lk sync.Mutex
src rand.Source
}
func (r *lockedSource) Int63() (n int64) {
r.lk.Lock()
n = r.src.Int63()
r.lk.Unlock()
return
}
func (r *lockedSource) Seed(seed int64) {
r.lk.Lock()
r.src.Seed(seed)
r.lk.Unlock()
}

View File

@@ -1,12 +0,0 @@
package metadata
// ClientInfo wraps immutable data from the client.Client structure.
type ClientInfo struct {
ServiceName string
APIVersion string
Endpoint string
SigningName string
SigningRegion string
JSONVersion string
TargetPrefix string
}

View File

@@ -1,363 +0,0 @@
package aws
import (
"net/http"
"time"
"github.com/aws/aws-sdk-go/aws/credentials"
)
// UseServiceDefaultRetries instructs the config to use the service's own default
// number of retries. This will be the default action if Config.MaxRetries
// is nil also.
const UseServiceDefaultRetries = -1
// RequestRetryer is an alias for a type that implements the request.Retryer interface.
type RequestRetryer interface{}
// A Config provides service configuration for service clients. By default,
// all clients will use the {defaults.DefaultConfig} structure.
type Config struct {
// Enables verbose error printing of all credential chain errors.
// Should be used when wanting to see all errors while attempting to retreive
// credentials.
CredentialsChainVerboseErrors *bool
// The credentials object to use when signing requests. Defaults to
// a chain of credential providers to search for credentials in environment
// variables, shared credential file, and EC2 Instance Roles.
Credentials *credentials.Credentials
// An optional endpoint URL (hostname only or fully qualified URI)
// that overrides the default generated endpoint for a client. Set this
// to `""` to use the default generated endpoint.
//
// @note You must still provide a `Region` value when specifying an
// endpoint for a client.
Endpoint *string
// The region to send requests to. This parameter is required and must
// be configured globally or on a per-client basis unless otherwise
// noted. A full list of regions is found in the "Regions and Endpoints"
// document.
//
// @see http://docs.aws.amazon.com/general/latest/gr/rande.html
// AWS Regions and Endpoints
Region *string
// Set this to `true` to disable SSL when sending requests. Defaults
// to `false`.
DisableSSL *bool
// The HTTP client to use when sending requests. Defaults to
// `http.DefaultClient`.
HTTPClient *http.Client
// An integer value representing the logging level. The default log level
// is zero (LogOff), which represents no logging. To enable logging set
// to a LogLevel Value.
LogLevel *LogLevelType
// The logger writer interface to write logging messages to. Defaults to
// standard out.
Logger Logger
// The maximum number of times that a request will be retried for failures.
// Defaults to -1, which defers the max retry setting to the service specific
// configuration.
MaxRetries *int
// Retryer guides how HTTP requests should be retried in case of recoverable failures.
//
// When nil or the value does not implement the request.Retryer interface,
// the request.DefaultRetryer will be used.
//
// When both Retryer and MaxRetries are non-nil, the former is used and
// the latter ignored.
//
// To set the Retryer field in a type-safe manner and with chaining, use
// the request.WithRetryer helper function:
//
// cfg := request.WithRetryer(aws.NewConfig(), myRetryer)
//
Retryer RequestRetryer
// Disables semantic parameter validation, which validates input for missing
// required fields and/or other semantic request input errors.
DisableParamValidation *bool
// Disables the computation of request and response checksums, e.g.,
// CRC32 checksums in Amazon DynamoDB.
DisableComputeChecksums *bool
// Set this to `true` to force the request to use path-style addressing,
// i.e., `http://s3.amazonaws.com/BUCKET/KEY`. By default, the S3 client will
// use virtual hosted bucket addressing when possible
// (`http://BUCKET.s3.amazonaws.com/KEY`).
//
// @note This configuration option is specific to the Amazon S3 service.
// @see http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html
// Amazon S3: Virtual Hosting of Buckets
S3ForcePathStyle *bool
// Set this to `true` to disable the SDK adding the `Expect: 100-Continue`
// header to PUT requests over 2MB of content. 100-Continue instructs the
// HTTP client not to send the body until the service responds with a
// `continue` status. This is useful to prevent sending the request body
// until after the request is authenticated, and validated.
//
// http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
//
// 100-Continue is only enabled for Go 1.6 and above. See `http.Transport`'s
// `ExpectContinueTimeout` for information on adjusting the continue wait timeout.
// https://golang.org/pkg/net/http/#Transport
//
// You should use this flag to disble 100-Continue if you experiance issues
// with proxies or thrid party S3 compatible services.
S3Disable100Continue *bool
// Set this to `true` to enable S3 Accelerate feature. For all operations compatible
// with S3 Accelerate will use the accelerate endpoint for requests. Requests not compatible
// will fall back to normal S3 requests.
//
// The bucket must be enable for accelerate to be used with S3 client with accelerate
// enabled. If the bucket is not enabled for accelerate an error will be returned.
// The bucket name must be DNS compatible to also work with accelerate.
S3UseAccelerate *bool
// Set this to `true` to disable the EC2Metadata client from overriding the
// default http.Client's Timeout. This is helpful if you do not want the EC2Metadata
// client to create a new http.Client. This options is only meaningful if you're not
// already using a custom HTTP client with the SDK. Enabled by default.
//
// Must be set and provided to the session.New() in order to disable the EC2Metadata
// overriding the timeout for default credentials chain.
//
// Example:
// sess := session.New(aws.NewConfig().WithEC2MetadataDiableTimeoutOverride(true))
// svc := s3.New(sess)
//
EC2MetadataDisableTimeoutOverride *bool
// SleepDelay is an override for the func the SDK will call when sleeping
// during the lifecycle of a request. Specifically this will be used for
// request delays. This value should only be used for testing. To adjust
// the delay of a request see the aws/client.DefaultRetryer and
// aws/request.Retryer.
SleepDelay func(time.Duration)
}
// NewConfig returns a new Config pointer that can be chained with builder methods to
// set multiple configuration values inline without using pointers.
//
// sess := session.New(aws.NewConfig().WithRegion("us-west-2").WithMaxRetries(10))
//
func NewConfig() *Config {
return &Config{}
}
// WithCredentialsChainVerboseErrors sets a config verbose errors boolean and returning
// a Config pointer.
func (c *Config) WithCredentialsChainVerboseErrors(verboseErrs bool) *Config {
c.CredentialsChainVerboseErrors = &verboseErrs
return c
}
// WithCredentials sets a config Credentials value returning a Config pointer
// for chaining.
func (c *Config) WithCredentials(creds *credentials.Credentials) *Config {
c.Credentials = creds
return c
}
// WithEndpoint sets a config Endpoint value returning a Config pointer for
// chaining.
func (c *Config) WithEndpoint(endpoint string) *Config {
c.Endpoint = &endpoint
return c
}
// WithRegion sets a config Region value returning a Config pointer for
// chaining.
func (c *Config) WithRegion(region string) *Config {
c.Region = &region
return c
}
// WithDisableSSL sets a config DisableSSL value returning a Config pointer
// for chaining.
func (c *Config) WithDisableSSL(disable bool) *Config {
c.DisableSSL = &disable
return c
}
// WithHTTPClient sets a config HTTPClient value returning a Config pointer
// for chaining.
func (c *Config) WithHTTPClient(client *http.Client) *Config {
c.HTTPClient = client
return c
}
// WithMaxRetries sets a config MaxRetries value returning a Config pointer
// for chaining.
func (c *Config) WithMaxRetries(max int) *Config {
c.MaxRetries = &max
return c
}
// WithDisableParamValidation sets a config DisableParamValidation value
// returning a Config pointer for chaining.
func (c *Config) WithDisableParamValidation(disable bool) *Config {
c.DisableParamValidation = &disable
return c
}
// WithDisableComputeChecksums sets a config DisableComputeChecksums value
// returning a Config pointer for chaining.
func (c *Config) WithDisableComputeChecksums(disable bool) *Config {
c.DisableComputeChecksums = &disable
return c
}
// WithLogLevel sets a config LogLevel value returning a Config pointer for
// chaining.
func (c *Config) WithLogLevel(level LogLevelType) *Config {
c.LogLevel = &level
return c
}
// WithLogger sets a config Logger value returning a Config pointer for
// chaining.
func (c *Config) WithLogger(logger Logger) *Config {
c.Logger = logger
return c
}
// WithS3ForcePathStyle sets a config S3ForcePathStyle value returning a Config
// pointer for chaining.
func (c *Config) WithS3ForcePathStyle(force bool) *Config {
c.S3ForcePathStyle = &force
return c
}
// WithS3Disable100Continue sets a config S3Disable100Continue value returning
// a Config pointer for chaining.
func (c *Config) WithS3Disable100Continue(disable bool) *Config {
c.S3Disable100Continue = &disable
return c
}
// WithS3UseAccelerate sets a config S3UseAccelerate value returning a Config
// pointer for chaining.
func (c *Config) WithS3UseAccelerate(enable bool) *Config {
c.S3UseAccelerate = &enable
return c
}
// WithEC2MetadataDisableTimeoutOverride sets a config EC2MetadataDisableTimeoutOverride value
// returning a Config pointer for chaining.
func (c *Config) WithEC2MetadataDisableTimeoutOverride(enable bool) *Config {
c.EC2MetadataDisableTimeoutOverride = &enable
return c
}
// WithSleepDelay overrides the function used to sleep while waiting for the
// next retry. Defaults to time.Sleep.
func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config {
c.SleepDelay = fn
return c
}
// MergeIn merges the passed in configs into the existing config object.
func (c *Config) MergeIn(cfgs ...*Config) {
for _, other := range cfgs {
mergeInConfig(c, other)
}
}
func mergeInConfig(dst *Config, other *Config) {
if other == nil {
return
}
if other.CredentialsChainVerboseErrors != nil {
dst.CredentialsChainVerboseErrors = other.CredentialsChainVerboseErrors
}
if other.Credentials != nil {
dst.Credentials = other.Credentials
}
if other.Endpoint != nil {
dst.Endpoint = other.Endpoint
}
if other.Region != nil {
dst.Region = other.Region
}
if other.DisableSSL != nil {
dst.DisableSSL = other.DisableSSL
}
if other.HTTPClient != nil {
dst.HTTPClient = other.HTTPClient
}
if other.LogLevel != nil {
dst.LogLevel = other.LogLevel
}
if other.Logger != nil {
dst.Logger = other.Logger
}
if other.MaxRetries != nil {
dst.MaxRetries = other.MaxRetries
}
if other.Retryer != nil {
dst.Retryer = other.Retryer
}
if other.DisableParamValidation != nil {
dst.DisableParamValidation = other.DisableParamValidation
}
if other.DisableComputeChecksums != nil {
dst.DisableComputeChecksums = other.DisableComputeChecksums
}
if other.S3ForcePathStyle != nil {
dst.S3ForcePathStyle = other.S3ForcePathStyle
}
if other.S3Disable100Continue != nil {
dst.S3Disable100Continue = other.S3Disable100Continue
}
if other.S3UseAccelerate != nil {
dst.S3UseAccelerate = other.S3UseAccelerate
}
if other.EC2MetadataDisableTimeoutOverride != nil {
dst.EC2MetadataDisableTimeoutOverride = other.EC2MetadataDisableTimeoutOverride
}
if other.SleepDelay != nil {
dst.SleepDelay = other.SleepDelay
}
}
// Copy will return a shallow copy of the Config object. If any additional
// configurations are provided they will be merged into the new config returned.
func (c *Config) Copy(cfgs ...*Config) *Config {
dst := &Config{}
dst.MergeIn(c)
for _, cfg := range cfgs {
dst.MergeIn(cfg)
}
return dst
}

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