Merge pull request #590 from harshavardhana/pr_out_unstruct_client_functions
This commit is contained in:
Generated
-52
@@ -5,46 +5,10 @@
|
||||
"./..."
|
||||
],
|
||||
"Deps": [
|
||||
{
|
||||
"ImportPath": "github.com/awslabs/aws-sdk-go/aws",
|
||||
"Rev": "528fdccfb1784861a4a24809328f891336449926"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/awslabs/aws-sdk-go/internal/endpoints",
|
||||
"Rev": "528fdccfb1784861a4a24809328f891336449926"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/awslabs/aws-sdk-go/internal/protocol/query",
|
||||
"Rev": "528fdccfb1784861a4a24809328f891336449926"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/awslabs/aws-sdk-go/internal/protocol/rest",
|
||||
"Rev": "528fdccfb1784861a4a24809328f891336449926"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/awslabs/aws-sdk-go/internal/protocol/restxml",
|
||||
"Rev": "528fdccfb1784861a4a24809328f891336449926"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil",
|
||||
"Rev": "528fdccfb1784861a4a24809328f891336449926"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/awslabs/aws-sdk-go/internal/signer/v4",
|
||||
"Rev": "528fdccfb1784861a4a24809328f891336449926"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/awslabs/aws-sdk-go/service/s3",
|
||||
"Rev": "528fdccfb1784861a4a24809328f891336449926"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/cheggaaa/pb",
|
||||
"Rev": "bd14546a551971ae7f460e6d6e527c5b56cd38d7"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/clbanning/mxj",
|
||||
"Rev": "da17de41d4c2e579884683ad838411fac440984d"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/dustin/go-humanize",
|
||||
"Rev": "8cc1aaa2d955ee82833337cfb10babc42be6bce6"
|
||||
@@ -77,22 +41,6 @@
|
||||
{
|
||||
"ImportPath": "github.com/shiena/ansicolor",
|
||||
"Rev": "8368d3b31cf6f2c2464c7a91675342c9a0ac6658"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/stretchr/objx",
|
||||
"Rev": "cbeaeb16a013161a98496fad62933b1d21786672"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/stretchr/testify/assert",
|
||||
"Rev": "e4ec8152c15fc46bd5056ce65997a07c7d415325"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/stretchr/testify/mock",
|
||||
"Rev": "e4ec8152c15fc46bd5056ce65997a07c7d415325"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/vaughan0/go-ini",
|
||||
"Rev": "a98ad7ee00ec53921f08832bc06ecf7fd600e6a1"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
package awsutil
|
||||
|
||||
import (
|
||||
"io"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// Copy deeply copies a src structure to dst. Useful for copying request and
|
||||
// response structures.
|
||||
func Copy(dst, src interface{}) {
|
||||
rcopy(reflect.ValueOf(dst), reflect.ValueOf(src))
|
||||
}
|
||||
|
||||
// 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))
|
||||
return
|
||||
}
|
||||
|
||||
func rcopy(dst, src reflect.Value) {
|
||||
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() {
|
||||
dst.Set(reflect.New(e))
|
||||
}
|
||||
if src.Elem().IsValid() {
|
||||
rcopy(dst.Elem(), src.Elem())
|
||||
}
|
||||
}
|
||||
case reflect.Struct:
|
||||
dst.Set(reflect.New(src.Type()).Elem())
|
||||
for i := 0; i < src.NumField(); i++ {
|
||||
rcopy(dst.Field(i), src.Field(i))
|
||||
}
|
||||
case reflect.Slice:
|
||||
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))
|
||||
}
|
||||
case reflect.Map:
|
||||
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)
|
||||
dst.SetMapIndex(k, v2)
|
||||
}
|
||||
default:
|
||||
dst.Set(src)
|
||||
}
|
||||
}
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
package awsutil_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/awslabs/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.StringValue(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 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 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.StringValue(f2))
|
||||
|
||||
// Output:
|
||||
// {
|
||||
// A: 1,
|
||||
// B: ["hello","bye bye"]
|
||||
// }
|
||||
}
|
||||
-142
@@ -1,142 +0,0 @@
|
||||
package awsutil
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var indexRe = regexp.MustCompile(`(.+)\[(-?\d+)?\]$`)
|
||||
|
||||
func rValuesAtPath(v interface{}, path string, create bool) []reflect.Value {
|
||||
pathparts := strings.Split(path, "||")
|
||||
if len(pathparts) > 1 {
|
||||
for _, pathpart := range pathparts {
|
||||
vals := rValuesAtPath(v, pathpart, create)
|
||||
if vals != nil && 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 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.FieldByName(c)
|
||||
if create && value.Kind() == reflect.Ptr && value.IsNil() {
|
||||
value.Set(reflect.New(value.Type().Elem()))
|
||||
value = value.Elem()
|
||||
} else {
|
||||
value = reflect.Indirect(value)
|
||||
}
|
||||
|
||||
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 create {
|
||||
// TODO resize slice
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
} else if i < 0 { // support negative indexing
|
||||
i = value.Len() + i
|
||||
}
|
||||
value = reflect.Indirect(value.Index(i))
|
||||
|
||||
if value.IsValid() {
|
||||
nextvals = append(nextvals, value)
|
||||
}
|
||||
}
|
||||
values = nextvals
|
||||
}
|
||||
|
||||
components = components[1:]
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
// ValuesAtPath returns a list of objects at the lexical path inside of a structure
|
||||
func ValuesAtPath(i interface{}, path string) []interface{} {
|
||||
if rvals := rValuesAtPath(i, path, false); rvals != nil {
|
||||
vals := make([]interface{}, len(rvals))
|
||||
for i, rval := range rvals {
|
||||
vals[i] = rval.Interface()
|
||||
}
|
||||
return vals
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetValueAtPath sets an object at the lexical path inside of a structure
|
||||
func SetValueAtPath(i interface{}, path string, v interface{}) {
|
||||
if rvals := rValuesAtPath(i, path, true); rvals != nil {
|
||||
for _, rval := range rvals {
|
||||
rval.Set(reflect.ValueOf(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-60
@@ -1,60 +0,0 @@
|
||||
package awsutil_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws/awsutil"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
type Struct struct {
|
||||
A []Struct
|
||||
a []Struct
|
||||
B *Struct
|
||||
D *Struct
|
||||
C string
|
||||
}
|
||||
|
||||
var data = Struct{
|
||||
A: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}},
|
||||
a: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}},
|
||||
B: &Struct{B: &Struct{C: "terminal"}, D: &Struct{C: "terminal2"}},
|
||||
C: "initial",
|
||||
}
|
||||
|
||||
func TestValueAtPathSuccess(t *testing.T) {
|
||||
assert.Equal(t, []interface{}{"initial"}, awsutil.ValuesAtPath(data, "C"))
|
||||
assert.Equal(t, []interface{}{"value1"}, awsutil.ValuesAtPath(data, "A[0].C"))
|
||||
assert.Equal(t, []interface{}{"value2"}, awsutil.ValuesAtPath(data, "A[1].C"))
|
||||
assert.Equal(t, []interface{}{"value3"}, awsutil.ValuesAtPath(data, "A[2].C"))
|
||||
assert.Equal(t, []interface{}{"value3"}, awsutil.ValuesAtPath(data, "A[-1].C"))
|
||||
assert.Equal(t, []interface{}{"value1", "value2", "value3"}, awsutil.ValuesAtPath(data, "A[].C"))
|
||||
assert.Equal(t, []interface{}{"terminal"}, awsutil.ValuesAtPath(data, "B . B . C"))
|
||||
assert.Equal(t, []interface{}{"terminal", "terminal2"}, awsutil.ValuesAtPath(data, "B.*.C"))
|
||||
assert.Equal(t, []interface{}{"initial"}, awsutil.ValuesAtPath(data, "A.D.X || C"))
|
||||
}
|
||||
|
||||
func TestValueAtPathFailure(t *testing.T) {
|
||||
assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, "C.x"))
|
||||
assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, ".x"))
|
||||
assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "X.Y.Z"))
|
||||
assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "A[100].C"))
|
||||
assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "A[3].C"))
|
||||
assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "B.B.C.Z"))
|
||||
assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, "a[-1].C"))
|
||||
assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(nil, "A.B.C"))
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
package awsutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
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:
|
||||
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.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())
|
||||
}
|
||||
}
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
const DEFAULT_RETRIES = -1
|
||||
|
||||
var DefaultConfig = &Config{
|
||||
Credentials: DefaultCreds(),
|
||||
Endpoint: "",
|
||||
Region: os.Getenv("AWS_REGION"),
|
||||
DisableSSL: false,
|
||||
ManualSend: false,
|
||||
HTTPClient: http.DefaultClient,
|
||||
LogLevel: 0,
|
||||
Logger: os.Stdout,
|
||||
MaxRetries: DEFAULT_RETRIES,
|
||||
DisableParamValidation: false,
|
||||
DisableComputeChecksums: false,
|
||||
S3ForcePathStyle: false,
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Credentials CredentialsProvider
|
||||
Endpoint string
|
||||
Region string
|
||||
DisableSSL bool
|
||||
ManualSend bool
|
||||
HTTPClient *http.Client
|
||||
LogLevel uint
|
||||
Logger io.Writer
|
||||
MaxRetries int
|
||||
DisableParamValidation bool
|
||||
DisableComputeChecksums bool
|
||||
S3ForcePathStyle bool
|
||||
}
|
||||
|
||||
func (c Config) Merge(newcfg *Config) *Config {
|
||||
cfg := Config{}
|
||||
|
||||
if newcfg != nil && newcfg.Credentials != nil {
|
||||
cfg.Credentials = newcfg.Credentials
|
||||
} else {
|
||||
cfg.Credentials = c.Credentials
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.Endpoint != "" {
|
||||
cfg.Endpoint = newcfg.Endpoint
|
||||
} else {
|
||||
cfg.Endpoint = c.Endpoint
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.Region != "" {
|
||||
cfg.Region = newcfg.Region
|
||||
} else {
|
||||
cfg.Region = c.Region
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.DisableSSL {
|
||||
cfg.DisableSSL = newcfg.DisableSSL
|
||||
} else {
|
||||
cfg.DisableSSL = c.DisableSSL
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.ManualSend {
|
||||
cfg.ManualSend = newcfg.ManualSend
|
||||
} else {
|
||||
cfg.ManualSend = c.ManualSend
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.HTTPClient != nil {
|
||||
cfg.HTTPClient = newcfg.HTTPClient
|
||||
} else {
|
||||
cfg.HTTPClient = c.HTTPClient
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.LogLevel != 0 {
|
||||
cfg.LogLevel = newcfg.LogLevel
|
||||
} else {
|
||||
cfg.LogLevel = c.LogLevel
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.Logger != nil {
|
||||
cfg.Logger = newcfg.Logger
|
||||
} else {
|
||||
cfg.Logger = c.Logger
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.MaxRetries != DEFAULT_RETRIES {
|
||||
cfg.MaxRetries = newcfg.MaxRetries
|
||||
} else {
|
||||
cfg.MaxRetries = c.MaxRetries
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.DisableParamValidation {
|
||||
cfg.DisableParamValidation = newcfg.DisableParamValidation
|
||||
} else {
|
||||
cfg.DisableParamValidation = c.DisableParamValidation
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.DisableComputeChecksums {
|
||||
cfg.DisableComputeChecksums = newcfg.DisableComputeChecksums
|
||||
} else {
|
||||
cfg.DisableComputeChecksums = c.DisableComputeChecksums
|
||||
}
|
||||
|
||||
if newcfg != nil && newcfg.S3ForcePathStyle {
|
||||
cfg.S3ForcePathStyle = newcfg.S3ForcePathStyle
|
||||
} else {
|
||||
cfg.S3ForcePathStyle = c.S3ForcePathStyle
|
||||
}
|
||||
|
||||
return &cfg
|
||||
}
|
||||
-291
@@ -1,291 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/vaughan0/go-ini"
|
||||
)
|
||||
|
||||
var currentTime = time.Now
|
||||
|
||||
// Credentials are used to authenticate and authorize calls that you make to
|
||||
// AWS.
|
||||
type Credentials struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
SessionToken string
|
||||
}
|
||||
|
||||
// A CredentialsProvider is a provider of credentials.
|
||||
type CredentialsProvider interface {
|
||||
// Credentials returns a set of credentials (or an error if no credentials
|
||||
// could be provided).
|
||||
Credentials() (*Credentials, error)
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be
|
||||
// found in the process's environment.
|
||||
ErrAccessKeyIDNotFound = fmt.Errorf("AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment")
|
||||
// ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key
|
||||
// can't be found in the process's environment.
|
||||
ErrSecretAccessKeyNotFound = fmt.Errorf("AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment")
|
||||
)
|
||||
|
||||
type DefaultCredentialsProvider struct {
|
||||
}
|
||||
|
||||
func (p *DefaultCredentialsProvider) Credentials() (*Credentials, error) {
|
||||
env, err := EnvCreds()
|
||||
if err == nil {
|
||||
return env.Credentials()
|
||||
}
|
||||
|
||||
profile, err := ProfileCreds("", "", 10*time.Minute)
|
||||
if err == nil {
|
||||
profileCreds, err := profile.Credentials()
|
||||
if err == nil {
|
||||
return profileCreds, nil
|
||||
}
|
||||
}
|
||||
|
||||
return IAMCreds().Credentials()
|
||||
}
|
||||
|
||||
func DefaultCreds() CredentialsProvider {
|
||||
return &DefaultCredentialsProvider{}
|
||||
}
|
||||
|
||||
// DetectCreds returns a CredentialsProvider based on the available information.
|
||||
//
|
||||
// If the access key ID and secret access key are provided, it returns a basic
|
||||
// provider.
|
||||
//
|
||||
// If credentials are available via environment variables, it returns an
|
||||
// environment provider.
|
||||
//
|
||||
// If a profile configuration file is available in the default location and has
|
||||
// a default profile configured, it returns a profile provider.
|
||||
//
|
||||
// Otherwise, it returns an IAM instance provider.
|
||||
func DetectCreds(accessKeyID, secretAccessKey, sessionToken string) CredentialsProvider {
|
||||
if accessKeyID != "" && secretAccessKey != "" {
|
||||
return Creds(accessKeyID, secretAccessKey, sessionToken)
|
||||
}
|
||||
|
||||
env, err := EnvCreds()
|
||||
if err == nil {
|
||||
return env
|
||||
}
|
||||
|
||||
profile, err := ProfileCreds("", "", 10*time.Minute)
|
||||
if err != nil {
|
||||
return IAMCreds()
|
||||
}
|
||||
|
||||
_, err = profile.Credentials()
|
||||
if err != nil {
|
||||
return IAMCreds()
|
||||
}
|
||||
|
||||
return profile
|
||||
}
|
||||
|
||||
// EnvCreds returns a static provider of AWS credentials from the process's
|
||||
// environment, or an error if none are found.
|
||||
func EnvCreds() (CredentialsProvider, error) {
|
||||
id := os.Getenv("AWS_ACCESS_KEY_ID")
|
||||
if id == "" {
|
||||
id = os.Getenv("AWS_ACCESS_KEY")
|
||||
}
|
||||
|
||||
secret := os.Getenv("AWS_SECRET_ACCESS_KEY")
|
||||
if secret == "" {
|
||||
secret = os.Getenv("AWS_SECRET_KEY")
|
||||
}
|
||||
|
||||
if id == "" {
|
||||
return nil, ErrAccessKeyIDNotFound
|
||||
}
|
||||
|
||||
if secret == "" {
|
||||
return nil, ErrSecretAccessKeyNotFound
|
||||
}
|
||||
|
||||
return Creds(id, secret, os.Getenv("AWS_SESSION_TOKEN")), nil
|
||||
}
|
||||
|
||||
// Creds returns a static provider of credentials.
|
||||
func Creds(accessKeyID, secretAccessKey, sessionToken string) CredentialsProvider {
|
||||
return staticCredentialsProvider{
|
||||
creds: Credentials{
|
||||
AccessKeyID: accessKeyID,
|
||||
SecretAccessKey: secretAccessKey,
|
||||
SessionToken: sessionToken,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// IAMCreds returns a provider which pulls credentials from the local EC2
|
||||
// instance's IAM roles.
|
||||
func IAMCreds() CredentialsProvider {
|
||||
return &iamProvider{}
|
||||
}
|
||||
|
||||
// ProfileCreds returns a provider which pulls credentials from the profile
|
||||
// configuration file.
|
||||
func ProfileCreds(filename, profile string, expiry time.Duration) (CredentialsProvider, error) {
|
||||
if filename == "" {
|
||||
homeDir := os.Getenv("HOME") // *nix
|
||||
if homeDir == "" { // Windows
|
||||
homeDir = os.Getenv("USERPROFILE")
|
||||
}
|
||||
if homeDir == "" {
|
||||
return nil, errors.New("User home directory not found.")
|
||||
}
|
||||
|
||||
filename = filepath.Join(homeDir, ".aws", "credentials")
|
||||
}
|
||||
|
||||
if profile == "" {
|
||||
profile = os.Getenv("AWS_PROFILE")
|
||||
}
|
||||
if profile == "" {
|
||||
profile = "default"
|
||||
}
|
||||
|
||||
return &profileProvider{
|
||||
filename: filename,
|
||||
profile: profile,
|
||||
expiry: expiry,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type profileProvider struct {
|
||||
filename string
|
||||
profile string
|
||||
expiry time.Duration
|
||||
|
||||
creds Credentials
|
||||
m sync.Mutex
|
||||
expiration time.Time
|
||||
}
|
||||
|
||||
func (p *profileProvider) Credentials() (*Credentials, error) {
|
||||
p.m.Lock()
|
||||
defer p.m.Unlock()
|
||||
|
||||
if p.expiration.After(currentTime()) {
|
||||
return &p.creds, nil
|
||||
}
|
||||
|
||||
config, err := ini.LoadFile(p.filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
profile := config.Section(p.profile)
|
||||
|
||||
accessKeyID, ok := profile["aws_access_key_id"]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("profile %s in %s did not contain aws_access_key_id", p.profile, p.filename)
|
||||
}
|
||||
|
||||
secretAccessKey, ok := profile["aws_secret_access_key"]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("profile %s in %s did not contain aws_secret_access_key", p.profile, p.filename)
|
||||
}
|
||||
|
||||
sessionToken := profile["aws_session_token"]
|
||||
|
||||
p.creds = Credentials{
|
||||
AccessKeyID: accessKeyID,
|
||||
SecretAccessKey: secretAccessKey,
|
||||
SessionToken: sessionToken,
|
||||
}
|
||||
p.expiration = currentTime().Add(p.expiry)
|
||||
|
||||
return &p.creds, nil
|
||||
}
|
||||
|
||||
type iamProvider struct {
|
||||
creds Credentials
|
||||
m sync.Mutex
|
||||
expiration time.Time
|
||||
}
|
||||
|
||||
var metadataCredentialsEndpoint = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
|
||||
|
||||
// IAMClient is the HTTP client used to query the metadata endpoint for IAM
|
||||
// credentials.
|
||||
var IAMClient = http.Client{
|
||||
Timeout: 1 * time.Second,
|
||||
}
|
||||
|
||||
func (p *iamProvider) Credentials() (*Credentials, error) {
|
||||
p.m.Lock()
|
||||
defer p.m.Unlock()
|
||||
|
||||
if p.expiration.After(currentTime()) {
|
||||
return &p.creds, nil
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Expiration time.Time
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
Token string
|
||||
}
|
||||
|
||||
resp, err := IAMClient.Get(metadataCredentialsEndpoint)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s listing IAM credentials", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
// Take the first line of the body of the metadata endpoint
|
||||
s := bufio.NewScanner(resp.Body)
|
||||
if !s.Scan() {
|
||||
return nil, fmt.Errorf("unable to find default IAM credentials")
|
||||
} else if s.Err() != nil {
|
||||
return nil, fmt.Errorf("%s listing IAM credentials", s.Err())
|
||||
}
|
||||
|
||||
resp, err = IAMClient.Get(metadataCredentialsEndpoint + s.Text())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("getting %s IAM credentials", s.Text())
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
return nil, fmt.Errorf("decoding %s IAM credentials", s.Text())
|
||||
}
|
||||
|
||||
p.creds = Credentials{
|
||||
AccessKeyID: body.AccessKeyID,
|
||||
SecretAccessKey: body.SecretAccessKey,
|
||||
SessionToken: body.Token,
|
||||
}
|
||||
p.expiration = body.Expiration
|
||||
|
||||
return &p.creds, nil
|
||||
}
|
||||
|
||||
type staticCredentialsProvider struct {
|
||||
creds Credentials
|
||||
}
|
||||
|
||||
func (p staticCredentialsProvider) Credentials() (*Credentials, error) {
|
||||
return &p.creds, nil
|
||||
}
|
||||
-265
@@ -1,265 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestEnvCreds(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("AWS_ACCESS_KEY_ID", "access")
|
||||
os.Setenv("AWS_SECRET_ACCESS_KEY", "secret")
|
||||
os.Setenv("AWS_SESSION_TOKEN", "token")
|
||||
|
||||
prov, err := EnvCreds()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
creds, err := prov.Credentials()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if v, want := creds.AccessKeyID, "access"; v != want {
|
||||
t.Errorf("Access key ID was %v, expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SecretAccessKey, "secret"; v != want {
|
||||
t.Errorf("Secret access key was %v, expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SessionToken, "token"; v != want {
|
||||
t.Errorf("Security token was %v, expected %v", v, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvCredsNoAccessKeyID(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("AWS_SECRET_ACCESS_KEY", "secret")
|
||||
|
||||
prov, err := EnvCreds()
|
||||
if err != ErrAccessKeyIDNotFound {
|
||||
t.Fatalf("ErrAccessKeyIDNotFound expected, but was %#v/%#v", prov, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvCredsNoSecretAccessKey(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("AWS_ACCESS_KEY_ID", "access")
|
||||
|
||||
prov, err := EnvCreds()
|
||||
if err != ErrSecretAccessKeyNotFound {
|
||||
t.Fatalf("ErrSecretAccessKeyNotFound expected, but was %#v/%#v", prov, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvCredsAlternateNames(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("AWS_ACCESS_KEY", "access")
|
||||
os.Setenv("AWS_SECRET_KEY", "secret")
|
||||
|
||||
prov, err := EnvCreds()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
creds, err := prov.Credentials()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if v, want := creds.AccessKeyID, "access"; v != want {
|
||||
t.Errorf("Access key ID was %v, expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SecretAccessKey, "secret"; v != want {
|
||||
t.Errorf("Secret access key was %v, expected %v", v, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMCreds(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.RequestURI == "/" {
|
||||
fmt.Fprintln(w, "/creds")
|
||||
} else {
|
||||
fmt.Fprintln(w, `{
|
||||
"AccessKeyId" : "accessKey",
|
||||
"SecretAccessKey" : "secret",
|
||||
"Token" : "token",
|
||||
"Expiration" : "2014-12-16T01:51:37Z"
|
||||
}`)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
defer func(s string) {
|
||||
metadataCredentialsEndpoint = s
|
||||
}(metadataCredentialsEndpoint)
|
||||
metadataCredentialsEndpoint = server.URL
|
||||
|
||||
defer func() {
|
||||
currentTime = time.Now
|
||||
}()
|
||||
currentTime = func() time.Time {
|
||||
return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
prov := IAMCreds()
|
||||
creds, err := prov.Credentials()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if v, want := creds.AccessKeyID, "accessKey"; v != want {
|
||||
t.Errorf("AcccessKeyID was %v, but expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SecretAccessKey, "secret"; v != want {
|
||||
t.Errorf("SecretAccessKey was %v, but expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SessionToken, "token"; v != want {
|
||||
t.Errorf("SessionToken was %v, but expected %v", v, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileCreds(t *testing.T) {
|
||||
os.Clearenv()
|
||||
prov, err := ProfileCreds("example.ini", "", 10*time.Minute)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
creds, err := prov.Credentials()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if v, want := creds.AccessKeyID, "accessKey"; v != want {
|
||||
t.Errorf("AcccessKeyID was %v, but expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SecretAccessKey, "secret"; v != want {
|
||||
t.Errorf("SecretAccessKey was %v, but expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SessionToken, "token"; v != want {
|
||||
t.Errorf("SessionToken was %v, but expected %v", v, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileCredsWithAWS_PROFILE(t *testing.T) {
|
||||
os.Clearenv()
|
||||
os.Setenv("AWS_PROFILE", "no_token")
|
||||
prov, err := ProfileCreds("example.ini", "", 10*time.Minute)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
creds, err := prov.Credentials()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if v, want := creds.AccessKeyID, "accessKey"; v != want {
|
||||
t.Errorf("AcccessKeyID was %v, but expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SecretAccessKey, "secret"; v != want {
|
||||
t.Errorf("SecretAccessKey was %v, but expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SessionToken, ""; v != want {
|
||||
t.Errorf("SessionToken was %v, but expected %v", v, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileCredsWithoutToken(t *testing.T) {
|
||||
os.Clearenv()
|
||||
prov, err := ProfileCreds("example.ini", "no_token", 10*time.Minute)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
creds, err := prov.Credentials()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if v, want := creds.AccessKeyID, "accessKey"; v != want {
|
||||
t.Errorf("AcccessKeyID was %v, but expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SecretAccessKey, "secret"; v != want {
|
||||
t.Errorf("SecretAccessKey was %v, but expected %v", v, want)
|
||||
}
|
||||
|
||||
if v, want := creds.SessionToken, ""; v != want {
|
||||
t.Errorf("SessionToken was %v, but expected %v", v, want)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkProfileCreds(b *testing.B) {
|
||||
os.Clearenv()
|
||||
prov, err := ProfileCreds("example.ini", "", 10*time.Minute)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
_, err := prov.Credentials()
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkIAMCreds(b *testing.B) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.RequestURI == "/" {
|
||||
fmt.Fprintln(w, "/creds")
|
||||
} else {
|
||||
fmt.Fprintln(w, `{
|
||||
"AccessKeyId" : "accessKey",
|
||||
"SecretAccessKey" : "secret",
|
||||
"Token" : "token",
|
||||
"Expiration" : "2014-12-16T01:51:37Z"
|
||||
}`)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
defer func(s string) {
|
||||
metadataCredentialsEndpoint = s
|
||||
}(metadataCredentialsEndpoint)
|
||||
metadataCredentialsEndpoint = server.URL
|
||||
|
||||
defer func() {
|
||||
currentTime = time.Now
|
||||
}()
|
||||
currentTime = func() time.Time {
|
||||
return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
|
||||
prov := IAMCreds()
|
||||
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
_, err := prov.Credentials()
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package aws
|
||||
|
||||
// An APIError is an error returned by an AWS API.
|
||||
type APIError struct {
|
||||
StatusCode int // HTTP status code e.g. 200
|
||||
Code string
|
||||
Message string
|
||||
RequestID string
|
||||
}
|
||||
|
||||
func (e APIError) Error() string {
|
||||
return e.Code + ": " + e.Message
|
||||
}
|
||||
|
||||
func Error(e error) *APIError {
|
||||
if err, ok := e.(*APIError); ok {
|
||||
return err
|
||||
} else if err, ok := e.(APIError); ok {
|
||||
return &err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
[default]
|
||||
aws_access_key_id = accessKey
|
||||
aws_secret_access_key = secret
|
||||
aws_session_token = token
|
||||
|
||||
[no_token]
|
||||
aws_access_key_id = accessKey
|
||||
aws_secret_access_key = secret
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
var sleepDelay = func(delay time.Duration) {
|
||||
time.Sleep(delay)
|
||||
}
|
||||
|
||||
type lener interface {
|
||||
Len() int
|
||||
}
|
||||
|
||||
func BuildContentLength(r *Request) {
|
||||
if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" {
|
||||
length, _ := strconv.ParseInt(slength, 10, 64)
|
||||
r.HTTPRequest.ContentLength = length
|
||||
return
|
||||
}
|
||||
|
||||
var length int64
|
||||
switch body := r.Body.(type) {
|
||||
case nil:
|
||||
length = 0
|
||||
case lener:
|
||||
length = int64(body.Len())
|
||||
case io.Seeker:
|
||||
cur, _ := body.Seek(0, 1)
|
||||
end, _ := body.Seek(0, 2)
|
||||
body.Seek(cur, 0) // make sure to seek back to original location
|
||||
length = end - cur
|
||||
default:
|
||||
panic("Cannot get length of body, must provide `ContentLength`")
|
||||
}
|
||||
|
||||
r.HTTPRequest.ContentLength = length
|
||||
r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length))
|
||||
}
|
||||
|
||||
func UserAgentHandler(r *Request) {
|
||||
r.HTTPRequest.Header.Set("User-Agent", SDKName+"/"+SDKVersion)
|
||||
}
|
||||
|
||||
func SendHandler(r *Request) {
|
||||
r.HTTPResponse, r.Error = r.Service.Config.HTTPClient.Do(r.HTTPRequest)
|
||||
}
|
||||
|
||||
func ValidateResponseHandler(r *Request) {
|
||||
if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 400 {
|
||||
r.Error = &APIError{
|
||||
StatusCode: r.HTTPResponse.StatusCode,
|
||||
Code: "UnknownError",
|
||||
Message: "unknown error",
|
||||
}
|
||||
}
|
||||
r.Retryable = r.Service.ShouldRetry(r)
|
||||
r.RetryDelay = r.Service.RetryRules(r)
|
||||
}
|
||||
|
||||
func AfterRetryHandler(r *Request) {
|
||||
if r.WillRetry() {
|
||||
sleepDelay(r.RetryDelay)
|
||||
|
||||
r.RetryCount++
|
||||
r.Retryable = false
|
||||
r.Error = nil
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
ErrMissingRegion = fmt.Errorf("could not find region configuration.")
|
||||
ErrMissingEndpoint = fmt.Errorf("`Endpoint' configuration is required for this service.")
|
||||
)
|
||||
|
||||
func ValidateEndpointHandler(r *Request) {
|
||||
if r.Service.SigningRegion == "" && r.Service.Config.Region == "" {
|
||||
r.Error = ErrMissingRegion
|
||||
} else if r.Service.Endpoint == "" {
|
||||
r.Error = ErrMissingEndpoint
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-33
@@ -1,33 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidateEndpointHandler(t *testing.T) {
|
||||
os.Clearenv()
|
||||
svc := NewService(&Config{Region: "us-west-2"})
|
||||
svc.Handlers.Clear()
|
||||
svc.Handlers.Validate.PushBack(ValidateEndpointHandler)
|
||||
|
||||
req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil)
|
||||
err := req.Build()
|
||||
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestValidateEndpointHandlerErrorRegion(t *testing.T) {
|
||||
os.Clearenv()
|
||||
svc := NewService(nil)
|
||||
svc.Handlers.Clear()
|
||||
svc.Handlers.Validate.PushBack(ValidateEndpointHandler)
|
||||
|
||||
req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil)
|
||||
err := req.Build()
|
||||
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, ErrMissingRegion, err)
|
||||
}
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
package aws
|
||||
|
||||
type Handlers struct {
|
||||
Validate HandlerList
|
||||
Build HandlerList
|
||||
Sign HandlerList
|
||||
Send HandlerList
|
||||
ValidateResponse HandlerList
|
||||
Unmarshal HandlerList
|
||||
UnmarshalMeta HandlerList
|
||||
UnmarshalError HandlerList
|
||||
Retry HandlerList
|
||||
AfterRetry HandlerList
|
||||
}
|
||||
|
||||
func (h *Handlers) copy() Handlers {
|
||||
return Handlers{
|
||||
Validate: h.Validate.copy(),
|
||||
Build: h.Build.copy(),
|
||||
Sign: h.Sign.copy(),
|
||||
Send: h.Send.copy(),
|
||||
ValidateResponse: h.ValidateResponse.copy(),
|
||||
Unmarshal: h.Unmarshal.copy(),
|
||||
UnmarshalError: h.UnmarshalError.copy(),
|
||||
UnmarshalMeta: h.UnmarshalMeta.copy(),
|
||||
Retry: h.Retry.copy(),
|
||||
AfterRetry: h.AfterRetry.copy(),
|
||||
}
|
||||
}
|
||||
|
||||
// Clear removes callback functions for all handlers
|
||||
func (h *Handlers) Clear() {
|
||||
h.Validate.Clear()
|
||||
h.Build.Clear()
|
||||
h.Send.Clear()
|
||||
h.Sign.Clear()
|
||||
h.Unmarshal.Clear()
|
||||
h.UnmarshalMeta.Clear()
|
||||
h.UnmarshalError.Clear()
|
||||
h.ValidateResponse.Clear()
|
||||
h.Retry.Clear()
|
||||
h.AfterRetry.Clear()
|
||||
}
|
||||
|
||||
// A handler list manages zero or more handlers in a list.
|
||||
type HandlerList struct {
|
||||
list []func(*Request)
|
||||
}
|
||||
|
||||
// copy creates a copy of the handler list.
|
||||
func (l *HandlerList) copy() HandlerList {
|
||||
var n HandlerList
|
||||
n.list = append([]func(*Request){}, l.list...)
|
||||
return n
|
||||
}
|
||||
|
||||
// Clear clears the handler list.
|
||||
func (l *HandlerList) Clear() {
|
||||
l.list = []func(*Request){}
|
||||
}
|
||||
|
||||
// Len returns the number of handlers in the list.
|
||||
func (l *HandlerList) Len() int {
|
||||
return len(l.list)
|
||||
}
|
||||
|
||||
// PushBack pushes handlers f to the back of the handler list.
|
||||
func (l *HandlerList) PushBack(f ...func(*Request)) {
|
||||
l.list = append(l.list, f...)
|
||||
}
|
||||
|
||||
// PushFront pushes handlers f to the front of the handler list.
|
||||
func (l *HandlerList) PushFront(f ...func(*Request)) {
|
||||
l.list = append(f, l.list...)
|
||||
}
|
||||
|
||||
// Run executes all handlers in the list with a given request object.
|
||||
func (l *HandlerList) Run(r *Request) {
|
||||
for _, f := range l.list {
|
||||
f(r)
|
||||
}
|
||||
}
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestHandlerList(t *testing.T) {
|
||||
s := ""
|
||||
r := &Request{}
|
||||
l := HandlerList{}
|
||||
l.PushBack(func(r *Request) {
|
||||
s += "a"
|
||||
r.Data = s
|
||||
})
|
||||
l.Run(r)
|
||||
assert.Equal(t, "a", s)
|
||||
assert.Equal(t, "a", r.Data)
|
||||
}
|
||||
|
||||
func TestMultipleHandlers(t *testing.T) {
|
||||
r := &Request{}
|
||||
l := HandlerList{}
|
||||
l.PushBack(func(r *Request) { r.Data = nil })
|
||||
l.PushFront(func(r *Request) { r.Data = Boolean(true) })
|
||||
l.Run(r)
|
||||
if r.Data != nil {
|
||||
t.Error("Expected handler to execute")
|
||||
}
|
||||
}
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func ValidateParameters(r *Request) {
|
||||
if r.ParamsFilled() {
|
||||
v := validator{errors: []string{}}
|
||||
v.validateAny(reflect.ValueOf(r.Params), "")
|
||||
|
||||
if count := len(v.errors); count > 0 {
|
||||
format := "%d validation errors:\n- %s"
|
||||
msg := fmt.Sprintf(format, count, strings.Join(v.errors, "\n- "))
|
||||
r.Error = APIError{Code: "InvalidParameter", Message: msg}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type validator struct {
|
||||
errors []string
|
||||
}
|
||||
|
||||
func (v *validator) validateAny(value reflect.Value, path string) {
|
||||
value = reflect.Indirect(value)
|
||||
if !value.IsValid() {
|
||||
return
|
||||
}
|
||||
|
||||
switch value.Kind() {
|
||||
case reflect.Struct:
|
||||
v.validateStruct(value, path)
|
||||
case reflect.Slice:
|
||||
for i := 0; i < value.Len(); i++ {
|
||||
v.validateAny(value.Index(i), path+fmt.Sprintf("[%d]", i))
|
||||
}
|
||||
case reflect.Map:
|
||||
for _, n := range value.MapKeys() {
|
||||
v.validateAny(value.MapIndex(n), path+fmt.Sprintf("[%q]", n.String()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *validator) validateStruct(value reflect.Value, path string) {
|
||||
prefix := "."
|
||||
if path == "" {
|
||||
prefix = ""
|
||||
}
|
||||
|
||||
for i := 0; i < value.Type().NumField(); i++ {
|
||||
f := value.Type().Field(i)
|
||||
if strings.ToLower(f.Name[0:1]) == f.Name[0:1] {
|
||||
continue
|
||||
}
|
||||
fvalue := value.FieldByName(f.Name)
|
||||
|
||||
notset := false
|
||||
if f.Tag.Get("required") != "" {
|
||||
switch fvalue.Kind() {
|
||||
case reflect.Ptr, reflect.Slice:
|
||||
if fvalue.IsNil() {
|
||||
notset = true
|
||||
}
|
||||
default:
|
||||
if !fvalue.IsValid() {
|
||||
notset = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if notset {
|
||||
msg := "missing required parameter: " + path + prefix + f.Name
|
||||
v.errors = append(v.errors, msg)
|
||||
} else {
|
||||
v.validateAny(fvalue, path+prefix+f.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
package aws_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var service = func() *aws.Service {
|
||||
s := &aws.Service{
|
||||
Config: &aws.Config{},
|
||||
ServiceName: "mock-service",
|
||||
APIVersion: "2015-01-01",
|
||||
}
|
||||
return s
|
||||
}()
|
||||
|
||||
type StructShape struct {
|
||||
RequiredList []*ConditionalStructShape `required:"true"`
|
||||
RequiredMap *map[string]*ConditionalStructShape `required:"true"`
|
||||
RequiredBool *bool `required:"true"`
|
||||
OptionalStruct *ConditionalStructShape
|
||||
|
||||
hiddenParameter *string
|
||||
|
||||
metadataStructureShape
|
||||
}
|
||||
|
||||
type metadataStructureShape struct {
|
||||
SDKShapeTraits bool
|
||||
}
|
||||
|
||||
type ConditionalStructShape struct {
|
||||
Name *string `required:"true"`
|
||||
SDKShapeTraits bool
|
||||
}
|
||||
|
||||
func TestNoErrors(t *testing.T) {
|
||||
input := &StructShape{
|
||||
RequiredList: []*ConditionalStructShape{},
|
||||
RequiredMap: &map[string]*ConditionalStructShape{
|
||||
"key1": {Name: aws.String("Name")},
|
||||
"key2": {Name: aws.String("Name")},
|
||||
},
|
||||
RequiredBool: aws.Boolean(true),
|
||||
OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")},
|
||||
}
|
||||
|
||||
req := aws.NewRequest(service, &aws.Operation{}, input, nil)
|
||||
aws.ValidateParameters(req)
|
||||
assert.NoError(t, req.Error)
|
||||
}
|
||||
|
||||
func TestMissingRequiredParameters(t *testing.T) {
|
||||
input := &StructShape{}
|
||||
req := aws.NewRequest(service, &aws.Operation{}, input, nil)
|
||||
aws.ValidateParameters(req)
|
||||
err := aws.Error(req.Error)
|
||||
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "InvalidParameter", err.Code)
|
||||
assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList\n- missing required parameter: RequiredMap\n- missing required parameter: RequiredBool", err.Message)
|
||||
}
|
||||
|
||||
func TestNestedMissingRequiredParameters(t *testing.T) {
|
||||
input := &StructShape{
|
||||
RequiredList: []*ConditionalStructShape{{}},
|
||||
RequiredMap: &map[string]*ConditionalStructShape{
|
||||
"key1": {Name: aws.String("Name")},
|
||||
"key2": {},
|
||||
},
|
||||
RequiredBool: aws.Boolean(true),
|
||||
OptionalStruct: &ConditionalStructShape{},
|
||||
}
|
||||
|
||||
req := aws.NewRequest(service, &aws.Operation{}, input, nil)
|
||||
aws.ValidateParameters(req)
|
||||
err := aws.Error(req.Error)
|
||||
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "InvalidParameter", err.Code)
|
||||
assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList[0].Name\n- missing required parameter: RequiredMap[\"key2\"].Name\n- missing required parameter: OptionalStruct.Name", err.Message)
|
||||
|
||||
}
|
||||
-160
@@ -1,160 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
*Service
|
||||
Handlers Handlers
|
||||
Time time.Time
|
||||
ExpireTime time.Duration
|
||||
Operation *Operation
|
||||
HTTPRequest *http.Request
|
||||
HTTPResponse *http.Response
|
||||
Body io.ReadSeeker
|
||||
Params interface{}
|
||||
Error error
|
||||
Data interface{}
|
||||
RequestID string
|
||||
RetryCount uint
|
||||
Retryable bool
|
||||
RetryDelay time.Duration
|
||||
|
||||
built bool
|
||||
}
|
||||
|
||||
type Operation struct {
|
||||
Name string
|
||||
HTTPMethod string
|
||||
HTTPPath string
|
||||
}
|
||||
|
||||
func NewRequest(service *Service, operation *Operation, params interface{}, data interface{}) *Request {
|
||||
method := operation.HTTPMethod
|
||||
if method == "" {
|
||||
method = "POST"
|
||||
}
|
||||
p := operation.HTTPPath
|
||||
if p == "" {
|
||||
p = "/"
|
||||
}
|
||||
|
||||
httpReq, _ := http.NewRequest(method, "", nil)
|
||||
httpReq.URL, _ = url.Parse(service.Endpoint + p)
|
||||
|
||||
r := &Request{
|
||||
Service: service,
|
||||
Handlers: service.Handlers.copy(),
|
||||
Time: time.Now(),
|
||||
ExpireTime: 0,
|
||||
Operation: operation,
|
||||
HTTPRequest: httpReq,
|
||||
Body: nil,
|
||||
Params: params,
|
||||
Error: nil,
|
||||
Data: data,
|
||||
}
|
||||
r.SetBufferBody([]byte{})
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *Request) WillRetry() bool {
|
||||
return r.Error != nil && r.Retryable && r.RetryCount < r.Service.MaxRetries()
|
||||
}
|
||||
|
||||
func (r *Request) ParamsFilled() bool {
|
||||
return r.Params != nil && reflect.ValueOf(r.Params).Elem().IsValid()
|
||||
}
|
||||
|
||||
func (r *Request) DataFilled() bool {
|
||||
return r.Data != nil && reflect.ValueOf(r.Data).Elem().IsValid()
|
||||
}
|
||||
|
||||
func (r *Request) SetBufferBody(buf []byte) {
|
||||
r.SetReaderBody(bytes.NewReader(buf))
|
||||
}
|
||||
|
||||
func (r *Request) SetReaderBody(reader io.ReadSeeker) {
|
||||
r.HTTPRequest.Body = ioutil.NopCloser(reader)
|
||||
r.Body = reader
|
||||
}
|
||||
|
||||
func (r *Request) Presign(expireTime time.Duration) (string, error) {
|
||||
r.ExpireTime = expireTime
|
||||
r.Sign()
|
||||
if r.Error != nil {
|
||||
return "", r.Error
|
||||
} else {
|
||||
return r.HTTPRequest.URL.String(), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Request) Build() error {
|
||||
if !r.built {
|
||||
r.Error = nil
|
||||
r.Handlers.Validate.Run(r)
|
||||
if r.Error != nil {
|
||||
return r.Error
|
||||
}
|
||||
r.Handlers.Build.Run(r)
|
||||
r.built = true
|
||||
}
|
||||
|
||||
return r.Error
|
||||
}
|
||||
|
||||
func (r *Request) Sign() error {
|
||||
r.Build()
|
||||
if r.Error != nil {
|
||||
return r.Error
|
||||
}
|
||||
|
||||
r.Handlers.Sign.Run(r)
|
||||
return r.Error
|
||||
}
|
||||
|
||||
func (r *Request) Send() error {
|
||||
r.Sign()
|
||||
if r.Error != nil {
|
||||
return r.Error
|
||||
}
|
||||
|
||||
for {
|
||||
r.Handlers.Send.Run(r)
|
||||
if r.Error != nil {
|
||||
return r.Error
|
||||
}
|
||||
|
||||
r.Handlers.UnmarshalMeta.Run(r)
|
||||
r.Handlers.ValidateResponse.Run(r)
|
||||
if r.Error != nil {
|
||||
r.Handlers.Retry.Run(r)
|
||||
r.Handlers.AfterRetry.Run(r)
|
||||
if r.Error != nil {
|
||||
r.Handlers.UnmarshalError.Run(r)
|
||||
return r.Error
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
r.Handlers.Unmarshal.Run(r)
|
||||
if r.Error != nil {
|
||||
r.Handlers.Retry.Run(r)
|
||||
r.Handlers.AfterRetry.Run(r)
|
||||
if r.Error != nil {
|
||||
return r.Error
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
type testData struct {
|
||||
Data string
|
||||
}
|
||||
|
||||
func body(str string) io.ReadCloser {
|
||||
return ioutil.NopCloser(bytes.NewReader([]byte(str)))
|
||||
}
|
||||
|
||||
func unmarshal(req *Request) {
|
||||
defer req.HTTPResponse.Body.Close()
|
||||
if req.Data != nil {
|
||||
json.NewDecoder(req.HTTPResponse.Body).Decode(req.Data)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func unmarshalError(req *Request) {
|
||||
bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body)
|
||||
if err != nil {
|
||||
req.Error = err
|
||||
return
|
||||
}
|
||||
if len(bodyBytes) == 0 {
|
||||
req.Error = APIError{
|
||||
StatusCode: req.HTTPResponse.StatusCode,
|
||||
Message: req.HTTPResponse.Status,
|
||||
}
|
||||
return
|
||||
}
|
||||
var jsonErr jsonErrorResponse
|
||||
if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil {
|
||||
req.Error = err
|
||||
return
|
||||
}
|
||||
req.Error = APIError{
|
||||
StatusCode: req.HTTPResponse.StatusCode,
|
||||
Code: jsonErr.Code,
|
||||
Message: jsonErr.Message,
|
||||
}
|
||||
}
|
||||
|
||||
type jsonErrorResponse struct {
|
||||
Code string `json:"__type"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func TestRequestRecoverRetry(t *testing.T) {
|
||||
reqNum := 0
|
||||
reqs := []http.Response{
|
||||
{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
|
||||
{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
|
||||
{StatusCode: 200, Body: body(`{"data":"valid"}`)},
|
||||
}
|
||||
|
||||
s := NewService(&Config{MaxRetries: 10})
|
||||
s.Handlers.Validate.Clear()
|
||||
s.Handlers.Unmarshal.PushBack(unmarshal)
|
||||
s.Handlers.UnmarshalError.PushBack(unmarshalError)
|
||||
s.Handlers.Send.Clear() // mock sending
|
||||
s.Handlers.Send.PushBack(func(r *Request) {
|
||||
r.HTTPResponse = &reqs[reqNum]
|
||||
reqNum++
|
||||
})
|
||||
out := &testData{}
|
||||
r := NewRequest(s, &Operation{Name: "Operation"}, nil, out)
|
||||
err := r.Send()
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 2, int(r.RetryCount))
|
||||
assert.Equal(t, "valid", out.Data)
|
||||
}
|
||||
|
||||
func TestRequestExhaustRetries(t *testing.T) {
|
||||
delays := []time.Duration{}
|
||||
sleepDelay = func(delay time.Duration) {
|
||||
delays = append(delays, delay)
|
||||
}
|
||||
|
||||
reqNum := 0
|
||||
reqs := []http.Response{
|
||||
{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
|
||||
{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
|
||||
{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
|
||||
{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
|
||||
}
|
||||
|
||||
s := NewService(&Config{MaxRetries: -1})
|
||||
s.Handlers.Validate.Clear()
|
||||
s.Handlers.Unmarshal.PushBack(unmarshal)
|
||||
s.Handlers.UnmarshalError.PushBack(unmarshalError)
|
||||
s.Handlers.Send.Clear() // mock sending
|
||||
s.Handlers.Send.PushBack(func(r *Request) {
|
||||
r.HTTPResponse = &reqs[reqNum]
|
||||
reqNum++
|
||||
})
|
||||
r := NewRequest(s, &Operation{Name: "Operation"}, nil, nil)
|
||||
err := r.Send()
|
||||
apiErr := Error(err)
|
||||
assert.NotNil(t, err)
|
||||
assert.NotNil(t, apiErr)
|
||||
assert.Equal(t, 500, apiErr.StatusCode)
|
||||
assert.Equal(t, "UnknownError", apiErr.Code)
|
||||
assert.Equal(t, "An error occurred.", apiErr.Message)
|
||||
assert.Equal(t, 3, int(r.RetryCount))
|
||||
assert.True(t, reflect.DeepEqual([]time.Duration{30 * time.Millisecond, 60 * time.Millisecond, 120 * time.Millisecond}, delays))
|
||||
}
|
||||
-143
@@ -1,143 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/internal/endpoints"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
Config *Config
|
||||
Handlers Handlers
|
||||
ManualSend bool
|
||||
ServiceName string
|
||||
APIVersion string
|
||||
Endpoint string
|
||||
SigningRegion string
|
||||
JSONVersion string
|
||||
TargetPrefix string
|
||||
RetryRules func(*Request) time.Duration
|
||||
ShouldRetry func(*Request) bool
|
||||
DefaultMaxRetries uint
|
||||
}
|
||||
|
||||
var schemeRE = regexp.MustCompile("^([^:]+)://")
|
||||
|
||||
func NewService(config *Config) *Service {
|
||||
svc := &Service{Config: config}
|
||||
svc.Initialize()
|
||||
return svc
|
||||
}
|
||||
|
||||
func (s *Service) Initialize() {
|
||||
if s.Config == nil {
|
||||
s.Config = &Config{}
|
||||
}
|
||||
if s.Config.HTTPClient == nil {
|
||||
s.Config.HTTPClient = http.DefaultClient
|
||||
}
|
||||
|
||||
if s.RetryRules == nil {
|
||||
s.RetryRules = retryRules
|
||||
}
|
||||
|
||||
if s.ShouldRetry == nil {
|
||||
s.ShouldRetry = shouldRetry
|
||||
}
|
||||
|
||||
s.DefaultMaxRetries = 3
|
||||
s.Handlers.Validate.PushBack(ValidateEndpointHandler)
|
||||
s.Handlers.Build.PushBack(UserAgentHandler)
|
||||
s.Handlers.Sign.PushBack(BuildContentLength)
|
||||
s.Handlers.Send.PushBack(SendHandler)
|
||||
s.Handlers.AfterRetry.PushBack(AfterRetryHandler)
|
||||
s.Handlers.ValidateResponse.PushBack(ValidateResponseHandler)
|
||||
s.AddDebugHandlers()
|
||||
s.buildEndpoint()
|
||||
|
||||
if !s.Config.DisableParamValidation {
|
||||
s.Handlers.Validate.PushBack(ValidateParameters)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) buildEndpoint() {
|
||||
if s.Config.Endpoint != "" {
|
||||
s.Endpoint = s.Config.Endpoint
|
||||
} else {
|
||||
s.Endpoint, s.SigningRegion =
|
||||
endpoints.EndpointForRegion(s.ServiceName, s.Config.Region)
|
||||
}
|
||||
|
||||
if s.Endpoint != "" && !schemeRE.MatchString(s.Endpoint) {
|
||||
scheme := "https"
|
||||
if s.Config.DisableSSL {
|
||||
scheme = "http"
|
||||
}
|
||||
s.Endpoint = scheme + "://" + s.Endpoint
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) AddDebugHandlers() {
|
||||
out := s.Config.Logger
|
||||
if s.Config.LogLevel == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
s.Handlers.Sign.PushBack(func(r *Request) {
|
||||
dumpedBody, _ := httputil.DumpRequest(r.HTTPRequest, true)
|
||||
|
||||
fmt.Fprintf(out, "=> [%s] %s.%s(%+v)\n", r.Time,
|
||||
r.Service.ServiceName, r.Operation.Name, r.Params)
|
||||
fmt.Fprintf(out, "---[ REQUEST PRE-SIGN ]------------------------------\n")
|
||||
fmt.Fprintf(out, "%s\n", string(dumpedBody))
|
||||
fmt.Fprintf(out, "-----------------------------------------------------\n")
|
||||
})
|
||||
s.Handlers.Send.PushFront(func(r *Request) {
|
||||
dumpedBody, _ := httputil.DumpRequestOut(r.HTTPRequest, true)
|
||||
|
||||
fmt.Fprintf(out, "---[ REQUEST POST-SIGN ]-----------------------------\n")
|
||||
fmt.Fprintf(out, "%s\n", string(dumpedBody))
|
||||
fmt.Fprintf(out, "-----------------------------------------------------\n")
|
||||
})
|
||||
s.Handlers.Send.PushBack(func(r *Request) {
|
||||
fmt.Fprintf(out, "---[ RESPONSE ]--------------------------------------\n")
|
||||
if r.HTTPResponse != nil {
|
||||
dumpedBody, _ := httputil.DumpResponse(r.HTTPResponse, true)
|
||||
fmt.Fprintf(out, "%s\n", string(dumpedBody))
|
||||
} else if r.Error != nil {
|
||||
fmt.Fprintf(out, "%s\n", r.Error)
|
||||
}
|
||||
fmt.Fprintf(out, "-----------------------------------------------------\n")
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) MaxRetries() uint {
|
||||
if s.Config.MaxRetries < 0 {
|
||||
return s.DefaultMaxRetries
|
||||
} else {
|
||||
return uint(s.Config.MaxRetries)
|
||||
}
|
||||
}
|
||||
|
||||
func retryRules(r *Request) time.Duration {
|
||||
delay := time.Duration(math.Pow(2, float64(r.RetryCount))) * 30
|
||||
return delay * time.Millisecond
|
||||
}
|
||||
|
||||
func shouldRetry(r *Request) bool {
|
||||
if r.HTTPResponse.StatusCode >= 500 {
|
||||
return true
|
||||
} else if err := Error(r.Error); err != nil {
|
||||
switch err.Code {
|
||||
case "ExpiredTokenException":
|
||||
case "ProvisionedThroughputExceededException", "Throttling":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
// String converts a Go string into a string pointer.
|
||||
func String(v string) *string {
|
||||
return &v
|
||||
}
|
||||
|
||||
// Boolean converts a Go bool into a boolean pointer.
|
||||
func Boolean(v bool) *bool {
|
||||
return &v
|
||||
}
|
||||
|
||||
// Long converts a Go int64 into a long pointer.
|
||||
func Long(v int64) *int64 {
|
||||
return &v
|
||||
}
|
||||
|
||||
// Double converts a Go float64 into a double pointer.
|
||||
func Double(v float64) *float64 {
|
||||
return &v
|
||||
}
|
||||
|
||||
// Time converts a Go Time into a Time pointer
|
||||
func Time(t time.Time) *time.Time {
|
||||
return &t
|
||||
}
|
||||
|
||||
func ReadSeekCloser(r io.Reader) ReaderSeekerCloser {
|
||||
return ReaderSeekerCloser{r}
|
||||
}
|
||||
|
||||
type ReaderSeekerCloser struct {
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
func (r ReaderSeekerCloser) Read(p []byte) (int, error) {
|
||||
switch t := r.r.(type) {
|
||||
case io.Reader:
|
||||
return t.Read(p)
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) {
|
||||
switch t := r.r.(type) {
|
||||
case io.Seeker:
|
||||
return t.Seek(offset, whence)
|
||||
}
|
||||
return int64(0), nil
|
||||
}
|
||||
|
||||
func (r ReaderSeekerCloser) Close() error {
|
||||
switch t := r.r.(type) {
|
||||
case io.Closer:
|
||||
return t.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
// Package aws provides core functionality for making requests to AWS services.
|
||||
package aws
|
||||
|
||||
const SDKName = "aws-sdk-go"
|
||||
const SDKVersion = "0.5.0"
|
||||
Generated
Vendored
-27
@@ -1,27 +0,0 @@
|
||||
package endpoints
|
||||
|
||||
//go:generate go run ../model/cli/gen-endpoints/main.go endpoints.json endpoints_map.go
|
||||
|
||||
import "strings"
|
||||
|
||||
func EndpointForRegion(svcName, region string) (endpoint, signingRegion string) {
|
||||
derivedKeys := []string{
|
||||
region + "/" + svcName,
|
||||
region + "/*",
|
||||
"*/" + svcName,
|
||||
"*/*",
|
||||
}
|
||||
|
||||
for _, key := range derivedKeys {
|
||||
if val, ok := endpointsMap.Endpoints[key]; ok {
|
||||
ep := val.Endpoint
|
||||
ep = strings.Replace(ep, "{region}", region, -1)
|
||||
ep = strings.Replace(ep, "{service}", svcName, -1)
|
||||
|
||||
endpoint = ep
|
||||
signingRegion = val.SigningRegion
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-77
@@ -1,77 +0,0 @@
|
||||
{
|
||||
"version": 2,
|
||||
"endpoints": {
|
||||
"*/*": {
|
||||
"endpoint": "{service}.{region}.amazonaws.com"
|
||||
},
|
||||
"cn-north-1/*": {
|
||||
"endpoint": "{service}.{region}.amazonaws.com.cn",
|
||||
"signatureVersion": "v4"
|
||||
},
|
||||
"us-gov-west-1/iam": {
|
||||
"endpoint": "iam.us-gov.amazonaws.com"
|
||||
},
|
||||
"us-gov-west-1/sts": {
|
||||
"endpoint": "sts.us-gov-west-1.amazonaws.com"
|
||||
},
|
||||
"us-gov-west-1/s3": {
|
||||
"endpoint": "s3-{region}.amazonaws.com"
|
||||
},
|
||||
"*/cloudfront": {
|
||||
"endpoint": "cloudfront.amazonaws.com",
|
||||
"signingRegion": "us-east-1"
|
||||
},
|
||||
"*/cloudsearchdomain": {
|
||||
"endpoint": "",
|
||||
"signingRegion": "us-east-1"
|
||||
},
|
||||
"*/iam": {
|
||||
"endpoint": "iam.amazonaws.com",
|
||||
"signingRegion": "us-east-1"
|
||||
},
|
||||
"*/importexport": {
|
||||
"endpoint": "importexport.amazonaws.com",
|
||||
"signingRegion": "us-east-1"
|
||||
},
|
||||
"*/route53": {
|
||||
"endpoint": "route53.amazonaws.com",
|
||||
"signingRegion": "us-east-1"
|
||||
},
|
||||
"*/sts": {
|
||||
"endpoint": "sts.amazonaws.com",
|
||||
"signingRegion": "us-east-1"
|
||||
},
|
||||
"us-east-1/sdb": {
|
||||
"endpoint": "sdb.amazonaws.com",
|
||||
"signingRegion": "us-east-1"
|
||||
},
|
||||
"us-east-1/s3": {
|
||||
"endpoint": "s3.amazonaws.com"
|
||||
},
|
||||
"us-west-1/s3": {
|
||||
"endpoint": "s3-{region}.amazonaws.com"
|
||||
},
|
||||
"us-west-2/s3": {
|
||||
"endpoint": "s3-{region}.amazonaws.com"
|
||||
},
|
||||
"eu-west-1/s3": {
|
||||
"endpoint": "s3-{region}.amazonaws.com"
|
||||
},
|
||||
"ap-southeast-1/s3": {
|
||||
"endpoint": "s3-{region}.amazonaws.com"
|
||||
},
|
||||
"ap-southeast-2/s3": {
|
||||
"endpoint": "s3-{region}.amazonaws.com"
|
||||
},
|
||||
"ap-northeast-1/s3": {
|
||||
"endpoint": "s3-{region}.amazonaws.com"
|
||||
},
|
||||
"sa-east-1/s3": {
|
||||
"endpoint": "s3-{region}.amazonaws.com"
|
||||
},
|
||||
"eu-central-1/s3": {
|
||||
"endpoint": "{service}.{region}.amazonaws.com",
|
||||
"signatureVersion": "v4"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-89
@@ -1,89 +0,0 @@
|
||||
package endpoints
|
||||
|
||||
// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
|
||||
|
||||
type endpointStruct struct {
|
||||
Version int
|
||||
Endpoints map[string]endpointEntry
|
||||
}
|
||||
|
||||
type endpointEntry struct {
|
||||
Endpoint string
|
||||
SigningRegion string
|
||||
}
|
||||
|
||||
var endpointsMap = endpointStruct{
|
||||
Version: 2,
|
||||
Endpoints: map[string]endpointEntry{
|
||||
"*/*": {
|
||||
Endpoint: "{service}.{region}.amazonaws.com",
|
||||
},
|
||||
"*/cloudfront": {
|
||||
Endpoint: "cloudfront.amazonaws.com",
|
||||
SigningRegion: "us-east-1",
|
||||
},
|
||||
"*/cloudsearchdomain": {
|
||||
Endpoint: "",
|
||||
SigningRegion: "us-east-1",
|
||||
},
|
||||
"*/iam": {
|
||||
Endpoint: "iam.amazonaws.com",
|
||||
SigningRegion: "us-east-1",
|
||||
},
|
||||
"*/importexport": {
|
||||
Endpoint: "importexport.amazonaws.com",
|
||||
SigningRegion: "us-east-1",
|
||||
},
|
||||
"*/route53": {
|
||||
Endpoint: "route53.amazonaws.com",
|
||||
SigningRegion: "us-east-1",
|
||||
},
|
||||
"*/sts": {
|
||||
Endpoint: "sts.amazonaws.com",
|
||||
SigningRegion: "us-east-1",
|
||||
},
|
||||
"ap-northeast-1/s3": {
|
||||
Endpoint: "s3-{region}.amazonaws.com",
|
||||
},
|
||||
"ap-southeast-1/s3": {
|
||||
Endpoint: "s3-{region}.amazonaws.com",
|
||||
},
|
||||
"ap-southeast-2/s3": {
|
||||
Endpoint: "s3-{region}.amazonaws.com",
|
||||
},
|
||||
"cn-north-1/*": {
|
||||
Endpoint: "{service}.{region}.amazonaws.com.cn",
|
||||
},
|
||||
"eu-central-1/s3": {
|
||||
Endpoint: "{service}.{region}.amazonaws.com",
|
||||
},
|
||||
"eu-west-1/s3": {
|
||||
Endpoint: "s3-{region}.amazonaws.com",
|
||||
},
|
||||
"sa-east-1/s3": {
|
||||
Endpoint: "s3-{region}.amazonaws.com",
|
||||
},
|
||||
"us-east-1/s3": {
|
||||
Endpoint: "s3.amazonaws.com",
|
||||
},
|
||||
"us-east-1/sdb": {
|
||||
Endpoint: "sdb.amazonaws.com",
|
||||
SigningRegion: "us-east-1",
|
||||
},
|
||||
"us-gov-west-1/iam": {
|
||||
Endpoint: "iam.us-gov.amazonaws.com",
|
||||
},
|
||||
"us-gov-west-1/s3": {
|
||||
Endpoint: "s3-{region}.amazonaws.com",
|
||||
},
|
||||
"us-gov-west-1/sts": {
|
||||
Endpoint: "sts.us-gov-west-1.amazonaws.com",
|
||||
},
|
||||
"us-west-1/s3": {
|
||||
Endpoint: "s3-{region}.amazonaws.com",
|
||||
},
|
||||
"us-west-2/s3": {
|
||||
Endpoint: "s3-{region}.amazonaws.com",
|
||||
},
|
||||
},
|
||||
}
|
||||
Generated
Vendored
-28
@@ -1,28 +0,0 @@
|
||||
package endpoints
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGlobalEndpoints(t *testing.T) {
|
||||
region := "mock-region-1"
|
||||
svcs := []string{"cloudfront", "iam", "importexport", "route53", "sts"}
|
||||
|
||||
for _, name := range svcs {
|
||||
ep, sr := EndpointForRegion(name, region)
|
||||
assert.Equal(t, name+".amazonaws.com", ep)
|
||||
assert.Equal(t, "us-east-1", sr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicesInCN(t *testing.T) {
|
||||
region := "cn-north-1"
|
||||
svcs := []string{"cloudfront", "iam", "importexport", "route53", "sts", "s3"}
|
||||
|
||||
for _, name := range svcs {
|
||||
ep, _ := EndpointForRegion(name, region)
|
||||
assert.Equal(t, name+"."+region+".amazonaws.com.cn", ep)
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-30
@@ -1,30 +0,0 @@
|
||||
package query
|
||||
|
||||
//go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/input/query.json build_test.go
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/internal/protocol/query/queryutil"
|
||||
)
|
||||
|
||||
func Build(r *aws.Request) {
|
||||
body := url.Values{
|
||||
"Action": {r.Operation.Name},
|
||||
"Version": {r.Service.APIVersion},
|
||||
}
|
||||
if err := queryutil.Parse(body, r.Params, false); err != nil {
|
||||
r.Error = err
|
||||
return
|
||||
}
|
||||
|
||||
if r.ExpireTime == 0 {
|
||||
r.HTTPRequest.Method = "POST"
|
||||
r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
|
||||
r.SetBufferBody([]byte(body.Encode()))
|
||||
} else { // This is a pre-signed request
|
||||
r.HTTPRequest.Method = "GET"
|
||||
r.HTTPRequest.URL.RawQuery = body.Encode()
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-1595
File diff suppressed because it is too large
Load Diff
Generated
Vendored
-221
@@ -1,221 +0,0 @@
|
||||
package queryutil
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Parse(body url.Values, i interface{}, isEC2 bool) error {
|
||||
q := queryParser{isEC2: isEC2}
|
||||
return q.parseValue(body, reflect.ValueOf(i), "", "")
|
||||
}
|
||||
|
||||
func elemOf(value reflect.Value) reflect.Value {
|
||||
for value.Kind() == reflect.Ptr {
|
||||
value = value.Elem()
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
type queryParser struct {
|
||||
isEC2 bool
|
||||
}
|
||||
|
||||
func (q *queryParser) parseValue(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error {
|
||||
value = elemOf(value)
|
||||
|
||||
// no need to handle zero values
|
||||
if !value.IsValid() {
|
||||
return nil
|
||||
}
|
||||
|
||||
t := tag.Get("type")
|
||||
if t == "" {
|
||||
switch value.Kind() {
|
||||
case reflect.Struct:
|
||||
t = "structure"
|
||||
case reflect.Slice:
|
||||
t = "list"
|
||||
case reflect.Map:
|
||||
t = "map"
|
||||
}
|
||||
}
|
||||
|
||||
switch t {
|
||||
case "structure":
|
||||
return q.parseStruct(v, value, prefix)
|
||||
case "list":
|
||||
return q.parseList(v, value, prefix, tag)
|
||||
case "map":
|
||||
return q.parseMap(v, value, prefix, tag)
|
||||
default:
|
||||
return q.parseScalar(v, value, prefix, tag)
|
||||
}
|
||||
}
|
||||
|
||||
func (q *queryParser) parseStruct(v url.Values, value reflect.Value, prefix string) error {
|
||||
if !value.IsValid() {
|
||||
return nil
|
||||
}
|
||||
|
||||
t := value.Type()
|
||||
for i := 0; i < value.NumField(); i++ {
|
||||
if c := t.Field(i).Name[0:1]; strings.ToLower(c) == c {
|
||||
continue // ignore unexported fields
|
||||
}
|
||||
|
||||
value := elemOf(value.Field(i))
|
||||
field := t.Field(i)
|
||||
var name string
|
||||
|
||||
if q.isEC2 {
|
||||
name = field.Tag.Get("queryName")
|
||||
}
|
||||
if name == "" {
|
||||
if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" {
|
||||
name = field.Tag.Get("locationNameList")
|
||||
} else if locName := field.Tag.Get("locationName"); locName != "" {
|
||||
name = locName
|
||||
}
|
||||
if name != "" && q.isEC2 {
|
||||
name = strings.ToUpper(name[0:1]) + name[1:]
|
||||
}
|
||||
}
|
||||
if name == "" {
|
||||
name = field.Name
|
||||
}
|
||||
|
||||
if prefix != "" {
|
||||
name = prefix + "." + name
|
||||
}
|
||||
|
||||
if err := q.parseValue(v, value, name, field.Tag); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error {
|
||||
// If it's empty, generate an empty value
|
||||
if !value.IsNil() && value.Len() == 0 {
|
||||
v.Set(prefix, "")
|
||||
return nil
|
||||
}
|
||||
|
||||
// check for unflattened list member
|
||||
if !q.isEC2 && tag.Get("flattened") == "" {
|
||||
prefix += ".member"
|
||||
}
|
||||
|
||||
for i := 0; i < value.Len(); i++ {
|
||||
slicePrefix := prefix
|
||||
if slicePrefix == "" {
|
||||
slicePrefix = strconv.Itoa(i + 1)
|
||||
} else {
|
||||
slicePrefix = slicePrefix + "." + strconv.Itoa(i+1)
|
||||
}
|
||||
if err := q.parseValue(v, value.Index(i), slicePrefix, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (q *queryParser) parseMap(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error {
|
||||
// If it's empty, generate an empty value
|
||||
if !value.IsNil() && value.Len() == 0 {
|
||||
v.Set(prefix, "")
|
||||
return nil
|
||||
}
|
||||
|
||||
// check for unflattened list member
|
||||
if !q.isEC2 && tag.Get("flattened") == "" {
|
||||
prefix += ".entry"
|
||||
}
|
||||
|
||||
// sort keys for improved serialization consistency.
|
||||
// this is not strictly necessary for protocol support.
|
||||
mapKeyValues := value.MapKeys()
|
||||
mapKeys := map[string]reflect.Value{}
|
||||
mapKeyNames := make([]string, len(mapKeyValues))
|
||||
for i, mapKey := range mapKeyValues {
|
||||
name := mapKey.String()
|
||||
mapKeys[name] = mapKey
|
||||
mapKeyNames[i] = name
|
||||
}
|
||||
sort.Strings(mapKeyNames)
|
||||
|
||||
for i, mapKeyName := range mapKeyNames {
|
||||
mapKey := mapKeys[mapKeyName]
|
||||
mapValue := value.MapIndex(mapKey)
|
||||
|
||||
kname := tag.Get("locationNameKey")
|
||||
if kname == "" {
|
||||
kname = "key"
|
||||
}
|
||||
vname := tag.Get("locationNameValue")
|
||||
if vname == "" {
|
||||
vname = "value"
|
||||
}
|
||||
|
||||
// serialize key
|
||||
var keyName string
|
||||
if prefix == "" {
|
||||
keyName = strconv.Itoa(i+1) + "." + kname
|
||||
} else {
|
||||
keyName = prefix + "." + strconv.Itoa(i+1) + "." + kname
|
||||
}
|
||||
|
||||
if err := q.parseValue(v, mapKey, keyName, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// serialize value
|
||||
var valueName string
|
||||
if prefix == "" {
|
||||
valueName = strconv.Itoa(i+1) + "." + vname
|
||||
} else {
|
||||
valueName = prefix + "." + strconv.Itoa(i+1) + "." + vname
|
||||
}
|
||||
|
||||
if err := q.parseValue(v, mapValue, valueName, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error {
|
||||
switch value := r.Interface().(type) {
|
||||
case string:
|
||||
v.Set(name, value)
|
||||
case []byte:
|
||||
if !r.IsNil() {
|
||||
v.Set(name, base64.StdEncoding.EncodeToString(value))
|
||||
}
|
||||
case bool:
|
||||
v.Set(name, strconv.FormatBool(value))
|
||||
case int64:
|
||||
v.Set(name, strconv.FormatInt(value, 10))
|
||||
case int:
|
||||
v.Set(name, strconv.Itoa(value))
|
||||
case float64:
|
||||
v.Set(name, strconv.FormatFloat(value, 'f', -1, 64))
|
||||
case float32:
|
||||
v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32))
|
||||
case time.Time:
|
||||
const ISO8601UTC = "2006-01-02T15:04:05Z"
|
||||
v.Set(name, value.UTC().Format(ISO8601UTC))
|
||||
default:
|
||||
return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Generated
Vendored
-26
@@ -1,26 +0,0 @@
|
||||
package query
|
||||
|
||||
//go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/output/query.json unmarshal_test.go
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil"
|
||||
)
|
||||
|
||||
func Unmarshal(r *aws.Request) {
|
||||
defer r.HTTPResponse.Body.Close()
|
||||
if r.DataFilled() {
|
||||
decoder := xml.NewDecoder(r.HTTPResponse.Body)
|
||||
err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result")
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func UnmarshalMeta(r *aws.Request) {
|
||||
// TODO implement unmarshaling of request IDs
|
||||
}
|
||||
Generated
Vendored
-31
@@ -1,31 +0,0 @@
|
||||
package query
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"io"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
)
|
||||
|
||||
type xmlErrorResponse struct {
|
||||
XMLName xml.Name `xml:"ErrorResponse"`
|
||||
Code string `xml:"Error>Code"`
|
||||
Message string `xml:"Error>Message"`
|
||||
RequestID string `xml:"RequestId"`
|
||||
}
|
||||
|
||||
func UnmarshalError(r *aws.Request) {
|
||||
defer r.HTTPResponse.Body.Close()
|
||||
|
||||
resp := &xmlErrorResponse{}
|
||||
err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp)
|
||||
if err != nil && err != io.EOF {
|
||||
r.Error = err
|
||||
} else {
|
||||
r.Error = aws.APIError{
|
||||
StatusCode: r.HTTPResponse.StatusCode,
|
||||
Code: resp.Code,
|
||||
Message: resp.Message,
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-1544
File diff suppressed because it is too large
Load Diff
Generated
Vendored
-215
@@ -1,215 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"path"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
)
|
||||
|
||||
// RFC822 returns an RFC822 formatted timestamp for AWS protocols
|
||||
const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT"
|
||||
|
||||
func Build(r *aws.Request) {
|
||||
if r.ParamsFilled() {
|
||||
v := reflect.ValueOf(r.Params).Elem()
|
||||
buildLocationElements(r, v)
|
||||
buildBody(r, v)
|
||||
}
|
||||
}
|
||||
|
||||
func buildLocationElements(r *aws.Request, v reflect.Value) {
|
||||
query := r.HTTPRequest.URL.Query()
|
||||
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
m := v.Field(i)
|
||||
if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) {
|
||||
continue
|
||||
}
|
||||
|
||||
if m.IsValid() {
|
||||
field := v.Type().Field(i)
|
||||
name := field.Tag.Get("locationName")
|
||||
if name == "" {
|
||||
name = field.Name
|
||||
}
|
||||
if m.Kind() == reflect.Ptr {
|
||||
m = m.Elem()
|
||||
}
|
||||
if !m.IsValid() {
|
||||
continue
|
||||
}
|
||||
|
||||
switch field.Tag.Get("location") {
|
||||
case "headers": // header maps
|
||||
buildHeaderMap(r, m, field.Tag.Get("locationName"))
|
||||
case "header":
|
||||
buildHeader(r, m, name)
|
||||
case "uri":
|
||||
buildURI(r, m, name)
|
||||
case "querystring":
|
||||
buildQueryString(r, m, name, query)
|
||||
}
|
||||
}
|
||||
if r.Error != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
r.HTTPRequest.URL.RawQuery = query.Encode()
|
||||
updatePath(r.HTTPRequest.URL, r.HTTPRequest.URL.Path)
|
||||
}
|
||||
|
||||
func buildBody(r *aws.Request, v reflect.Value) {
|
||||
if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
|
||||
if payloadName := field.Tag.Get("payload"); payloadName != "" {
|
||||
pfield, _ := v.Type().FieldByName(payloadName)
|
||||
if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" {
|
||||
payload := reflect.Indirect(v.FieldByName(payloadName))
|
||||
if payload.IsValid() && payload.Interface() != nil {
|
||||
switch reader := payload.Interface().(type) {
|
||||
case io.ReadSeeker:
|
||||
r.SetReaderBody(reader)
|
||||
case []byte:
|
||||
r.SetBufferBody(reader)
|
||||
case string:
|
||||
r.SetBufferBody([]byte(reader))
|
||||
default:
|
||||
r.Error = fmt.Errorf("unknown payload type %s", payload.Type())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func buildHeader(r *aws.Request, v reflect.Value, name string) {
|
||||
str, err := convertType(v)
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
} else if str != nil {
|
||||
r.HTTPRequest.Header.Add(name, *str)
|
||||
}
|
||||
}
|
||||
|
||||
func buildHeaderMap(r *aws.Request, v reflect.Value, prefix string) {
|
||||
for _, key := range v.MapKeys() {
|
||||
str, err := convertType(v.MapIndex(key))
|
||||
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
} else if str != nil {
|
||||
r.HTTPRequest.Header.Add(prefix+key.String(), *str)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func buildURI(r *aws.Request, v reflect.Value, name string) {
|
||||
value, err := convertType(v)
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
} else if value != nil {
|
||||
uri := r.HTTPRequest.URL.Path
|
||||
uri = strings.Replace(uri, "{"+name+"}", escapePath(*value, true), -1)
|
||||
uri = strings.Replace(uri, "{"+name+"+}", escapePath(*value, false), -1)
|
||||
r.HTTPRequest.URL.Path = uri
|
||||
}
|
||||
}
|
||||
|
||||
func buildQueryString(r *aws.Request, v reflect.Value, name string, query url.Values) {
|
||||
str, err := convertType(v)
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
} else if str != nil {
|
||||
query.Set(name, *str)
|
||||
}
|
||||
}
|
||||
|
||||
func updatePath(url *url.URL, urlPath string) {
|
||||
scheme, query := url.Scheme, url.RawQuery
|
||||
|
||||
// clean up path
|
||||
urlPath = path.Clean(urlPath)
|
||||
|
||||
// get formatted URL minus scheme so we can build this into Opaque
|
||||
url.Scheme, url.Path, url.RawQuery = "", "", ""
|
||||
s := url.String()
|
||||
url.Scheme = scheme
|
||||
url.RawQuery = query
|
||||
|
||||
// build opaque URI
|
||||
url.Opaque = s + urlPath
|
||||
}
|
||||
|
||||
// Whether the byte value can be sent without escaping in AWS URLs
|
||||
var noEscape [256]bool
|
||||
var noEscapeInitialized = false
|
||||
|
||||
// initialise noEscape
|
||||
func initNoEscape() {
|
||||
for i := range noEscape {
|
||||
// Amazon expects every character except these escaped
|
||||
noEscape[i] = (i >= 'A' && i <= 'Z') ||
|
||||
(i >= 'a' && i <= 'z') ||
|
||||
(i >= '0' && i <= '9') ||
|
||||
i == '-' ||
|
||||
i == '.' ||
|
||||
i == '_' ||
|
||||
i == '~'
|
||||
}
|
||||
}
|
||||
|
||||
// escapePath escapes part of a URL path in Amazon style
|
||||
func escapePath(path string, encodeSep bool) string {
|
||||
if !noEscapeInitialized {
|
||||
initNoEscape()
|
||||
noEscapeInitialized = true
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
for i := 0; i < len(path); i++ {
|
||||
c := path[i]
|
||||
if noEscape[c] || (c == '/' && !encodeSep) {
|
||||
buf.WriteByte(c)
|
||||
} else {
|
||||
buf.WriteByte('%')
|
||||
buf.WriteString(strings.ToUpper(strconv.FormatUint(uint64(c), 16)))
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func convertType(v reflect.Value) (*string, error) {
|
||||
v = reflect.Indirect(v)
|
||||
if !v.IsValid() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var str string
|
||||
switch value := v.Interface().(type) {
|
||||
case string:
|
||||
str = value
|
||||
case []byte:
|
||||
str = base64.StdEncoding.EncodeToString(value)
|
||||
case bool:
|
||||
str = strconv.FormatBool(value)
|
||||
case int64:
|
||||
str = strconv.FormatInt(value, 10)
|
||||
case float64:
|
||||
str = strconv.FormatFloat(value, 'f', -1, 64)
|
||||
case time.Time:
|
||||
str = value.UTC().Format(RFC822)
|
||||
default:
|
||||
err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type())
|
||||
return nil, err
|
||||
}
|
||||
return &str, nil
|
||||
}
|
||||
Generated
Vendored
-43
@@ -1,43 +0,0 @@
|
||||
package rest
|
||||
|
||||
import "reflect"
|
||||
|
||||
func PayloadMember(i interface{}) interface{} {
|
||||
if i == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
v := reflect.ValueOf(i).Elem()
|
||||
if !v.IsValid() {
|
||||
return nil
|
||||
}
|
||||
if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
|
||||
if payloadName := field.Tag.Get("payload"); payloadName != "" {
|
||||
field, _ := v.Type().FieldByName(payloadName)
|
||||
if field.Tag.Get("type") != "structure" {
|
||||
return nil
|
||||
}
|
||||
|
||||
payload := v.FieldByName(payloadName)
|
||||
if payload.IsValid() || (payload.Kind() == reflect.Ptr && !payload.IsNil()) {
|
||||
return payload.Interface()
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func PayloadType(i interface{}) string {
|
||||
v := reflect.Indirect(reflect.ValueOf(i))
|
||||
if !v.IsValid() {
|
||||
return ""
|
||||
}
|
||||
if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
|
||||
if payloadName := field.Tag.Get("payload"); payloadName != "" {
|
||||
if member, ok := v.Type().FieldByName(payloadName); ok {
|
||||
return member.Tag.Get("type")
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
Generated
Vendored
-174
@@ -1,174 +0,0 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
)
|
||||
|
||||
func Unmarshal(r *aws.Request) {
|
||||
if r.DataFilled() {
|
||||
v := reflect.Indirect(reflect.ValueOf(r.Data))
|
||||
unmarshalBody(r, v)
|
||||
unmarshalLocationElements(r, v)
|
||||
}
|
||||
}
|
||||
|
||||
func unmarshalBody(r *aws.Request, v reflect.Value) {
|
||||
if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
|
||||
if payloadName := field.Tag.Get("payload"); payloadName != "" {
|
||||
pfield, _ := v.Type().FieldByName(payloadName)
|
||||
if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" {
|
||||
payload := reflect.Indirect(v.FieldByName(payloadName))
|
||||
if payload.IsValid() {
|
||||
switch payload.Interface().(type) {
|
||||
case []byte:
|
||||
b, err := ioutil.ReadAll(r.HTTPResponse.Body)
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
} else {
|
||||
payload.Set(reflect.ValueOf(b))
|
||||
}
|
||||
case string:
|
||||
b, err := ioutil.ReadAll(r.HTTPResponse.Body)
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
} else {
|
||||
payload.Set(reflect.ValueOf(string(b)))
|
||||
}
|
||||
default:
|
||||
switch payload.Type().String() {
|
||||
case "io.ReadSeeker":
|
||||
payload.Set(reflect.ValueOf(aws.ReadSeekCloser(r.HTTPResponse.Body)))
|
||||
case "aws.ReadSeekCloser", "io.ReadCloser":
|
||||
payload.Set(reflect.ValueOf(r.HTTPResponse.Body))
|
||||
default:
|
||||
r.Error = fmt.Errorf("unknown payload type %s", payload.Type())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func unmarshalLocationElements(r *aws.Request, v reflect.Value) {
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
m, field := v.Field(i), v.Type().Field(i)
|
||||
if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) {
|
||||
continue
|
||||
}
|
||||
|
||||
if m.IsValid() {
|
||||
name := field.Tag.Get("locationName")
|
||||
if name == "" {
|
||||
name = field.Name
|
||||
}
|
||||
|
||||
switch field.Tag.Get("location") {
|
||||
case "statusCode":
|
||||
unmarshalStatusCode(m, r.HTTPResponse.StatusCode)
|
||||
case "header":
|
||||
err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name))
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
break
|
||||
}
|
||||
case "headers":
|
||||
prefix := field.Tag.Get("locationName")
|
||||
err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix)
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if r.Error != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func unmarshalStatusCode(v reflect.Value, statusCode int) {
|
||||
if !v.IsValid() {
|
||||
return
|
||||
}
|
||||
|
||||
switch v.Interface().(type) {
|
||||
case *int64:
|
||||
s := int64(statusCode)
|
||||
v.Set(reflect.ValueOf(&s))
|
||||
}
|
||||
}
|
||||
|
||||
func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string) error {
|
||||
switch r.Interface().(type) {
|
||||
case *map[string]*string: // we only support string map value types
|
||||
out := map[string]*string{}
|
||||
for k, v := range headers {
|
||||
k = http.CanonicalHeaderKey(k)
|
||||
if strings.HasPrefix(strings.ToLower(k), strings.ToLower(prefix)) {
|
||||
out[k[len(prefix):]] = &v[0]
|
||||
}
|
||||
}
|
||||
r.Set(reflect.ValueOf(&out))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unmarshalHeader(v reflect.Value, header string) error {
|
||||
if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch v.Interface().(type) {
|
||||
case *string:
|
||||
v.Set(reflect.ValueOf(&header))
|
||||
case []byte:
|
||||
b, err := base64.StdEncoding.DecodeString(header)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
v.Set(reflect.ValueOf(&b))
|
||||
}
|
||||
case *bool:
|
||||
b, err := strconv.ParseBool(header)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
v.Set(reflect.ValueOf(&b))
|
||||
}
|
||||
case *int64:
|
||||
i, err := strconv.ParseInt(header, 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
v.Set(reflect.ValueOf(&i))
|
||||
}
|
||||
case *float64:
|
||||
f, err := strconv.ParseFloat(header, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
v.Set(reflect.ValueOf(&f))
|
||||
}
|
||||
case *time.Time:
|
||||
t, err := time.Parse(RFC822, header)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
v.Set(reflect.ValueOf(&t))
|
||||
}
|
||||
default:
|
||||
err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type())
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Generated
Vendored
-2864
File diff suppressed because it is too large
Load Diff
Generated
Vendored
-48
@@ -1,48 +0,0 @@
|
||||
package restxml
|
||||
|
||||
//go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/input/rest-xml.json build_test.go
|
||||
//go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/output/rest-xml.json unmarshal_test.go
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/internal/protocol/query"
|
||||
"github.com/awslabs/aws-sdk-go/internal/protocol/rest"
|
||||
"github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil"
|
||||
)
|
||||
|
||||
func Build(r *aws.Request) {
|
||||
rest.Build(r)
|
||||
|
||||
if t := rest.PayloadType(r.Params); t == "structure" || t == "" {
|
||||
var buf bytes.Buffer
|
||||
err := xmlutil.BuildXML(r.Params, xml.NewEncoder(&buf))
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
return
|
||||
}
|
||||
r.SetBufferBody(buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func Unmarshal(r *aws.Request) {
|
||||
if t := rest.PayloadType(r.Data); t == "structure" || t == "" {
|
||||
defer r.HTTPResponse.Body.Close()
|
||||
decoder := xml.NewDecoder(r.HTTPResponse.Body)
|
||||
err := xmlutil.UnmarshalXML(r.Data, decoder, "")
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func UnmarshalMeta(r *aws.Request) {
|
||||
rest.Unmarshal(r)
|
||||
}
|
||||
|
||||
func UnmarshalError(r *aws.Request) {
|
||||
query.UnmarshalError(r)
|
||||
}
|
||||
Generated
Vendored
-1320
File diff suppressed because it is too large
Load Diff
Generated
Vendored
-263
@@ -1,263 +0,0 @@
|
||||
package xmlutil
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func BuildXML(params interface{}, e *xml.Encoder) error {
|
||||
b := xmlBuilder{encoder: e, namespaces: map[string]string{}}
|
||||
root := NewXMLElement(xml.Name{})
|
||||
if err := b.buildValue(reflect.ValueOf(params), root, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range root.Children {
|
||||
for _, v := range c {
|
||||
return StructToXML(e, v, false)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func elemOf(value reflect.Value) reflect.Value {
|
||||
for value.Kind() == reflect.Ptr {
|
||||
value = value.Elem()
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
type xmlBuilder struct {
|
||||
encoder *xml.Encoder
|
||||
namespaces map[string]string
|
||||
}
|
||||
|
||||
func (b *xmlBuilder) buildValue(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
|
||||
value = elemOf(value)
|
||||
if !value.IsValid() { // no need to handle zero values
|
||||
return nil
|
||||
} else if tag.Get("location") != "" { // don't handle non-body location values
|
||||
return nil
|
||||
}
|
||||
|
||||
t := tag.Get("type")
|
||||
if t == "" {
|
||||
switch value.Kind() {
|
||||
case reflect.Struct:
|
||||
t = "structure"
|
||||
case reflect.Slice:
|
||||
t = "list"
|
||||
case reflect.Map:
|
||||
t = "map"
|
||||
}
|
||||
}
|
||||
|
||||
switch t {
|
||||
case "structure":
|
||||
if field, ok := value.Type().FieldByName("SDKShapeTraits"); ok {
|
||||
tag = tag + reflect.StructTag(" ") + field.Tag
|
||||
}
|
||||
return b.buildStruct(value, current, tag)
|
||||
case "list":
|
||||
return b.buildList(value, current, tag)
|
||||
case "map":
|
||||
return b.buildMap(value, current, tag)
|
||||
default:
|
||||
return b.buildScalar(value, current, tag)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
|
||||
if !value.IsValid() {
|
||||
return nil
|
||||
}
|
||||
|
||||
fieldAdded := false
|
||||
|
||||
// unwrap payloads
|
||||
if payload := tag.Get("payload"); payload != "" {
|
||||
field, _ := value.Type().FieldByName(payload)
|
||||
tag = field.Tag
|
||||
value = elemOf(value.FieldByName(payload))
|
||||
|
||||
if !value.IsValid() {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
child := NewXMLElement(xml.Name{Local: tag.Get("locationName")})
|
||||
|
||||
// there is an xmlNamespace associated with this struct
|
||||
if prefix, uri := tag.Get("xmlPrefix"), tag.Get("xmlURI"); uri != "" {
|
||||
ns := xml.Attr{
|
||||
Name: xml.Name{Local: "xmlns"},
|
||||
Value: uri,
|
||||
}
|
||||
if prefix != "" {
|
||||
b.namespaces[prefix] = uri // register the namespace
|
||||
ns.Name.Local = "xmlns:" + prefix
|
||||
}
|
||||
|
||||
child.Attr = append(child.Attr, ns)
|
||||
}
|
||||
|
||||
t := value.Type()
|
||||
for i := 0; i < value.NumField(); i++ {
|
||||
if c := t.Field(i).Name[0:1]; strings.ToLower(c) == c {
|
||||
continue // ignore unexported fields
|
||||
}
|
||||
|
||||
member := elemOf(value.Field(i))
|
||||
field := t.Field(i)
|
||||
mTag := field.Tag
|
||||
|
||||
if mTag.Get("location") != "" { // skip non-body members
|
||||
continue
|
||||
}
|
||||
|
||||
memberName := mTag.Get("locationName")
|
||||
if memberName == "" {
|
||||
memberName = field.Name
|
||||
mTag = reflect.StructTag(string(mTag) + ` locationName:"` + memberName + `"`)
|
||||
}
|
||||
if err := b.buildValue(member, child, mTag); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fieldAdded = true
|
||||
}
|
||||
|
||||
if fieldAdded { // only append this child if we have one ore more valid members
|
||||
current.AddChild(child)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *xmlBuilder) buildList(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
|
||||
if value.IsNil() { // don't build omitted lists
|
||||
return nil
|
||||
}
|
||||
|
||||
// check for unflattened list member
|
||||
flattened := tag.Get("flattened") != ""
|
||||
|
||||
xname := xml.Name{Local: tag.Get("locationName")}
|
||||
if flattened {
|
||||
for i := 0; i < value.Len(); i++ {
|
||||
child := NewXMLElement(xname)
|
||||
current.AddChild(child)
|
||||
if err := b.buildValue(value.Index(i), child, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
list := NewXMLElement(xname)
|
||||
current.AddChild(list)
|
||||
|
||||
for i := 0; i < value.Len(); i++ {
|
||||
iname := tag.Get("locationNameList")
|
||||
if iname == "" {
|
||||
iname = "member"
|
||||
}
|
||||
|
||||
child := NewXMLElement(xml.Name{Local: iname})
|
||||
list.AddChild(child)
|
||||
if err := b.buildValue(value.Index(i), child, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *xmlBuilder) buildMap(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
|
||||
if value.IsNil() { // don't build omitted maps
|
||||
return nil
|
||||
}
|
||||
|
||||
maproot := NewXMLElement(xml.Name{Local: tag.Get("locationName")})
|
||||
current.AddChild(maproot)
|
||||
current = maproot
|
||||
|
||||
kname, vname := "key", "value"
|
||||
if n := tag.Get("locationNameKey"); n != "" {
|
||||
kname = n
|
||||
}
|
||||
if n := tag.Get("locationNameValue"); n != "" {
|
||||
vname = n
|
||||
}
|
||||
|
||||
// sorting is not required for compliance, but it makes testing easier
|
||||
keys := make([]string, value.Len())
|
||||
for i, k := range value.MapKeys() {
|
||||
keys[i] = k.String()
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
for _, k := range keys {
|
||||
v := value.MapIndex(reflect.ValueOf(k))
|
||||
|
||||
mapcur := current
|
||||
if tag.Get("flattened") == "" { // add "entry" tag to non-flat maps
|
||||
child := NewXMLElement(xml.Name{Local: "entry"})
|
||||
mapcur.AddChild(child)
|
||||
mapcur = child
|
||||
}
|
||||
|
||||
kchild := NewXMLElement(xml.Name{Local: kname})
|
||||
kchild.Text = k
|
||||
vchild := NewXMLElement(xml.Name{Local: vname})
|
||||
mapcur.AddChild(kchild)
|
||||
mapcur.AddChild(vchild)
|
||||
|
||||
if err := b.buildValue(v, vchild, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *xmlBuilder) buildScalar(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
|
||||
var str string
|
||||
switch converted := value.Interface().(type) {
|
||||
case string:
|
||||
str = converted
|
||||
case []byte:
|
||||
if !value.IsNil() {
|
||||
str = base64.StdEncoding.EncodeToString(converted)
|
||||
}
|
||||
case bool:
|
||||
str = strconv.FormatBool(converted)
|
||||
case int64:
|
||||
str = strconv.FormatInt(converted, 10)
|
||||
case int:
|
||||
str = strconv.Itoa(converted)
|
||||
case float64:
|
||||
str = strconv.FormatFloat(converted, 'f', -1, 64)
|
||||
case float32:
|
||||
str = strconv.FormatFloat(float64(converted), 'f', -1, 32)
|
||||
case time.Time:
|
||||
const ISO8601UTC = "2006-01-02T15:04:05Z"
|
||||
str = converted.UTC().Format(ISO8601UTC)
|
||||
default:
|
||||
return fmt.Errorf("unsupported value for param %s: %v (%s)",
|
||||
tag.Get("locationName"), value.Interface(), value.Type().Name())
|
||||
}
|
||||
|
||||
xname := xml.Name{Local: tag.Get("locationName")}
|
||||
if tag.Get("xmlAttribute") != "" { // put into current node's attribute list
|
||||
attr := xml.Attr{Name: xname, Value: str}
|
||||
current.Attr = append(current.Attr, attr)
|
||||
} else { // regular text node
|
||||
current.AddChild(&XMLNode{Name: xname, Text: str})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Generated
Vendored
-251
@@ -1,251 +0,0 @@
|
||||
package xmlutil
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error {
|
||||
n, _ := XMLToStruct(d, nil)
|
||||
if n.Children != nil {
|
||||
for _, root := range n.Children {
|
||||
for _, c := range root {
|
||||
if wrappedChild, ok := c.Children[wrapper]; ok {
|
||||
c = wrappedChild[0] // pull out wrapped element
|
||||
}
|
||||
|
||||
err := parse(reflect.ValueOf(v), c, "")
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parse(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
|
||||
rtype := r.Type()
|
||||
if rtype.Kind() == reflect.Ptr {
|
||||
rtype = rtype.Elem() // check kind of actual element type
|
||||
}
|
||||
|
||||
t := tag.Get("type")
|
||||
if t == "" {
|
||||
switch rtype.Kind() {
|
||||
case reflect.Struct:
|
||||
t = "structure"
|
||||
case reflect.Slice:
|
||||
t = "list"
|
||||
case reflect.Map:
|
||||
t = "map"
|
||||
}
|
||||
}
|
||||
|
||||
switch t {
|
||||
case "structure":
|
||||
if field, ok := rtype.FieldByName("SDKShapeTraits"); ok {
|
||||
tag = field.Tag
|
||||
}
|
||||
return parseStruct(r, node, tag)
|
||||
case "list":
|
||||
return parseList(r, node, tag)
|
||||
case "map":
|
||||
return parseMap(r, node, tag)
|
||||
default:
|
||||
return parseScalar(r, node, tag)
|
||||
}
|
||||
}
|
||||
|
||||
func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
|
||||
t := r.Type()
|
||||
if r.Kind() == reflect.Ptr {
|
||||
if r.IsNil() { // create the structure if it's nil
|
||||
s := reflect.New(r.Type().Elem())
|
||||
r.Set(s)
|
||||
r = s
|
||||
}
|
||||
|
||||
r = r.Elem()
|
||||
t = t.Elem()
|
||||
}
|
||||
|
||||
// unwrap any payloads
|
||||
if payload := tag.Get("payload"); payload != "" {
|
||||
field, _ := t.FieldByName(payload)
|
||||
return parseStruct(r.FieldByName(payload), node, field.Tag)
|
||||
}
|
||||
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
field := t.Field(i)
|
||||
if c := field.Name[0:1]; strings.ToLower(c) == c {
|
||||
continue // ignore unexported fields
|
||||
}
|
||||
|
||||
// figure out what this field is called
|
||||
name := field.Name
|
||||
if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" {
|
||||
name = field.Tag.Get("locationNameList")
|
||||
} else if locName := field.Tag.Get("locationName"); locName != "" {
|
||||
name = locName
|
||||
}
|
||||
|
||||
// try to find the field by name in elements
|
||||
elems := node.Children[name]
|
||||
|
||||
if elems == nil { // try to find the field in attributes
|
||||
for _, a := range node.Attr {
|
||||
if name == a.Name.Local {
|
||||
// turn this into a text node for de-serializing
|
||||
elems = []*XMLNode{{Text: a.Value}}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
member := r.FieldByName(field.Name)
|
||||
for _, elem := range elems {
|
||||
err := parse(member, elem, field.Tag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseList(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
|
||||
t := r.Type()
|
||||
|
||||
if tag.Get("flattened") == "" { // look at all item entries
|
||||
mname := "member"
|
||||
if name := tag.Get("locationNameList"); name != "" {
|
||||
mname = name
|
||||
}
|
||||
|
||||
if Children, ok := node.Children[mname]; ok {
|
||||
if r.IsNil() {
|
||||
r.Set(reflect.MakeSlice(t, len(Children), len(Children)))
|
||||
}
|
||||
|
||||
for i, c := range Children {
|
||||
err := parse(r.Index(i), c, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
} else { // flattened list means this is a single element
|
||||
if r.IsNil() {
|
||||
r.Set(reflect.MakeSlice(t, 0, 0))
|
||||
}
|
||||
|
||||
childR := reflect.Zero(t.Elem())
|
||||
r.Set(reflect.Append(r, childR))
|
||||
err := parse(r.Index(r.Len()-1), node, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseMap(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
|
||||
t := r.Type()
|
||||
if r.Kind() == reflect.Ptr {
|
||||
t = t.Elem()
|
||||
if r.IsNil() {
|
||||
r.Set(reflect.New(t))
|
||||
r.Elem().Set(reflect.MakeMap(t))
|
||||
}
|
||||
|
||||
r = r.Elem()
|
||||
}
|
||||
|
||||
if tag.Get("flattened") == "" { // look at all child entries
|
||||
for _, entry := range node.Children["entry"] {
|
||||
parseMapEntry(r, entry, tag)
|
||||
}
|
||||
} else { // this element is itself an entry
|
||||
parseMapEntry(r, node, tag)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseMapEntry(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
|
||||
kname, vname := "key", "value"
|
||||
if n := tag.Get("locationNameKey"); n != "" {
|
||||
kname = n
|
||||
}
|
||||
if n := tag.Get("locationNameValue"); n != "" {
|
||||
vname = n
|
||||
}
|
||||
|
||||
keys, ok := node.Children[kname]
|
||||
values := node.Children[vname]
|
||||
if ok {
|
||||
for i, key := range keys {
|
||||
keyR := reflect.ValueOf(key.Text)
|
||||
value := values[i]
|
||||
valueR := reflect.New(r.Type().Elem()).Elem()
|
||||
|
||||
parse(valueR, value, "")
|
||||
r.SetMapIndex(keyR, valueR)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseScalar(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
|
||||
switch r.Interface().(type) {
|
||||
case *string:
|
||||
r.Set(reflect.ValueOf(&node.Text))
|
||||
return nil
|
||||
case []byte:
|
||||
b, err := base64.StdEncoding.DecodeString(node.Text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Set(reflect.ValueOf(b))
|
||||
case *bool:
|
||||
v, err := strconv.ParseBool(node.Text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Set(reflect.ValueOf(&v))
|
||||
case *int64:
|
||||
v, err := strconv.ParseInt(node.Text, 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Set(reflect.ValueOf(&v))
|
||||
case *float64:
|
||||
v, err := strconv.ParseFloat(node.Text, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Set(reflect.ValueOf(&v))
|
||||
case *time.Time:
|
||||
const ISO8601UTC = "2006-01-02T15:04:05Z"
|
||||
t, err := time.Parse(ISO8601UTC, node.Text)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
r.Set(reflect.ValueOf(&t))
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unsupported value: %v (%s)", r.Interface(), r.Type())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Generated
Vendored
-100
@@ -1,100 +0,0 @@
|
||||
package xmlutil
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type XMLNode struct {
|
||||
Name xml.Name `json:",omitempty"`
|
||||
Children map[string][]*XMLNode `json:",omitempty"`
|
||||
Text string `json:",omitempty"`
|
||||
Attr []xml.Attr `json:",omitempty"`
|
||||
}
|
||||
|
||||
func NewXMLElement(name xml.Name) *XMLNode {
|
||||
return &XMLNode{
|
||||
Name: name,
|
||||
Children: map[string][]*XMLNode{},
|
||||
Attr: []xml.Attr{},
|
||||
}
|
||||
}
|
||||
|
||||
func (n *XMLNode) AddChild(child *XMLNode) {
|
||||
if _, ok := n.Children[child.Name.Local]; !ok {
|
||||
n.Children[child.Name.Local] = []*XMLNode{}
|
||||
}
|
||||
n.Children[child.Name.Local] = append(n.Children[child.Name.Local], child)
|
||||
}
|
||||
|
||||
func XMLToStruct(d *xml.Decoder, s *xml.StartElement) (*XMLNode, error) {
|
||||
out := &XMLNode{}
|
||||
for {
|
||||
tok, err := d.Token()
|
||||
if tok == nil || err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
|
||||
switch typed := tok.(type) {
|
||||
case xml.CharData:
|
||||
out.Text = string(typed.Copy())
|
||||
case xml.StartElement:
|
||||
el := typed.Copy()
|
||||
out.Attr = el.Attr
|
||||
if out.Children == nil {
|
||||
out.Children = map[string][]*XMLNode{}
|
||||
}
|
||||
|
||||
name := typed.Name.Local
|
||||
slice := out.Children[name]
|
||||
if slice == nil {
|
||||
slice = []*XMLNode{}
|
||||
}
|
||||
node, e := XMLToStruct(d, &el)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
node.Name = typed.Name
|
||||
slice = append(slice, node)
|
||||
out.Children[name] = slice
|
||||
case xml.EndElement:
|
||||
if s != nil && s.Name.Local == typed.Name.Local { // matching end token
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func StructToXML(e *xml.Encoder, node *XMLNode, sorted bool) error {
|
||||
e.EncodeToken(xml.StartElement{Name: node.Name, Attr: node.Attr})
|
||||
|
||||
if node.Text != "" {
|
||||
e.EncodeToken(xml.CharData([]byte(node.Text)))
|
||||
} else if sorted {
|
||||
sortedNames := []string{}
|
||||
for k := range node.Children {
|
||||
sortedNames = append(sortedNames, k)
|
||||
}
|
||||
sort.Strings(sortedNames)
|
||||
|
||||
for _, k := range sortedNames {
|
||||
for _, v := range node.Children[k] {
|
||||
StructToXML(e, v, sorted)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, c := range node.Children {
|
||||
for _, v := range c {
|
||||
StructToXML(e, v, sorted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
e.EncodeToken(xml.EndElement{Name: node.Name})
|
||||
return e.Flush()
|
||||
}
|
||||
-301
@@ -1,301 +0,0 @@
|
||||
package v4
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
)
|
||||
|
||||
const (
|
||||
authHeaderPrefix = "AWS4-HMAC-SHA256"
|
||||
timeFormat = "20060102T150405Z"
|
||||
shortTimeFormat = "20060102"
|
||||
)
|
||||
|
||||
var ignoredHeaders = map[string]bool{
|
||||
"Authorization": true,
|
||||
"Content-Type": true,
|
||||
"Content-Length": true,
|
||||
"User-Agent": true,
|
||||
}
|
||||
|
||||
type signer struct {
|
||||
Request *http.Request
|
||||
Time time.Time
|
||||
ExpireTime time.Duration
|
||||
ServiceName string
|
||||
Region string
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
SessionToken string
|
||||
Query url.Values
|
||||
Body io.ReadSeeker
|
||||
Debug uint
|
||||
Logger io.Writer
|
||||
|
||||
isPresign bool
|
||||
formattedTime string
|
||||
formattedShortTime string
|
||||
|
||||
signedHeaders string
|
||||
canonicalHeaders string
|
||||
canonicalString string
|
||||
credentialString string
|
||||
stringToSign string
|
||||
signature string
|
||||
authorization string
|
||||
}
|
||||
|
||||
// Sign requests with signature version 4.
|
||||
func Sign(req *aws.Request) {
|
||||
creds, err := req.Service.Config.Credentials.Credentials()
|
||||
if err != nil {
|
||||
req.Error = err
|
||||
return
|
||||
}
|
||||
|
||||
region := req.Service.SigningRegion
|
||||
if region == "" {
|
||||
region = req.Service.Config.Region
|
||||
}
|
||||
|
||||
s := signer{
|
||||
Request: req.HTTPRequest,
|
||||
Time: req.Time,
|
||||
ExpireTime: req.ExpireTime,
|
||||
Query: req.HTTPRequest.URL.Query(),
|
||||
Body: req.Body,
|
||||
ServiceName: req.Service.ServiceName,
|
||||
Region: region,
|
||||
AccessKeyID: creds.AccessKeyID,
|
||||
SecretAccessKey: creds.SecretAccessKey,
|
||||
SessionToken: creds.SessionToken,
|
||||
Debug: req.Service.Config.LogLevel,
|
||||
Logger: req.Service.Config.Logger,
|
||||
}
|
||||
s.sign()
|
||||
return
|
||||
}
|
||||
|
||||
func (v4 *signer) sign() {
|
||||
if v4.ExpireTime != 0 {
|
||||
v4.isPresign = true
|
||||
}
|
||||
|
||||
if v4.isPresign {
|
||||
v4.Query.Set("X-Amz-Algorithm", authHeaderPrefix)
|
||||
if v4.SessionToken != "" {
|
||||
v4.Query.Set("X-Amz-Security-Token", v4.SessionToken)
|
||||
} else {
|
||||
v4.Query.Del("X-Amz-Security-Token")
|
||||
}
|
||||
} else if v4.SessionToken != "" {
|
||||
v4.Request.Header.Set("X-Amz-Security-Token", v4.SessionToken)
|
||||
}
|
||||
|
||||
v4.build()
|
||||
|
||||
if v4.Debug > 0 {
|
||||
out := v4.Logger
|
||||
fmt.Fprintf(out, "---[ CANONICAL STRING ]-----------------------------\n")
|
||||
fmt.Fprintln(out, v4.canonicalString)
|
||||
fmt.Fprintf(out, "---[ STRING TO SIGN ]--------------------------------\n")
|
||||
fmt.Fprintln(out, v4.stringToSign)
|
||||
fmt.Fprintf(out, "---[ SIGNED URL ]--------------------------------\n")
|
||||
fmt.Fprintln(out, v4.Request.URL)
|
||||
fmt.Fprintf(out, "-----------------------------------------------------\n")
|
||||
}
|
||||
}
|
||||
|
||||
func (v4 *signer) build() {
|
||||
v4.buildTime() // no depends
|
||||
v4.buildCredentialString() // no depends
|
||||
if v4.isPresign {
|
||||
v4.buildQuery() // no depends
|
||||
}
|
||||
v4.buildCanonicalHeaders() // depends on cred string
|
||||
v4.buildCanonicalString() // depends on canon headers / signed headers
|
||||
v4.buildStringToSign() // depends on canon string
|
||||
v4.buildSignature() // depends on string to sign
|
||||
|
||||
if v4.isPresign {
|
||||
v4.Request.URL.RawQuery += "&X-Amz-Signature=" + v4.signature
|
||||
} else {
|
||||
parts := []string{
|
||||
authHeaderPrefix + " Credential=" + v4.AccessKeyID + "/" + v4.credentialString,
|
||||
"SignedHeaders=" + v4.signedHeaders,
|
||||
"Signature=" + v4.signature,
|
||||
}
|
||||
v4.Request.Header.Set("Authorization", strings.Join(parts, ", "))
|
||||
}
|
||||
}
|
||||
|
||||
func (v4 *signer) buildTime() {
|
||||
v4.formattedTime = v4.Time.UTC().Format(timeFormat)
|
||||
v4.formattedShortTime = v4.Time.UTC().Format(shortTimeFormat)
|
||||
|
||||
if v4.isPresign {
|
||||
duration := int64(v4.ExpireTime / time.Second)
|
||||
v4.Query.Set("X-Amz-Date", v4.formattedTime)
|
||||
v4.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10))
|
||||
} else {
|
||||
v4.Request.Header.Set("X-Amz-Date", v4.formattedTime)
|
||||
}
|
||||
}
|
||||
|
||||
func (v4 *signer) buildCredentialString() {
|
||||
v4.credentialString = strings.Join([]string{
|
||||
v4.formattedShortTime,
|
||||
v4.Region,
|
||||
v4.ServiceName,
|
||||
"aws4_request",
|
||||
}, "/")
|
||||
|
||||
if v4.isPresign {
|
||||
v4.Query.Set("X-Amz-Credential", v4.AccessKeyID+"/"+v4.credentialString)
|
||||
}
|
||||
}
|
||||
|
||||
func (v4 *signer) buildQuery() {
|
||||
for k, h := range v4.Request.Header {
|
||||
if strings.HasPrefix(http.CanonicalHeaderKey(k), "X-Amz-") {
|
||||
continue // never hoist x-amz-* headers, they must be signed
|
||||
}
|
||||
if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok {
|
||||
continue // never hoist ignored headers
|
||||
}
|
||||
|
||||
v4.Request.Header.Del(k)
|
||||
v4.Query.Del(k)
|
||||
for _, v := range h {
|
||||
v4.Query.Add(k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v4 *signer) buildCanonicalHeaders() {
|
||||
headers := make([]string, 0)
|
||||
headers = append(headers, "host")
|
||||
for k := range v4.Request.Header {
|
||||
if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok {
|
||||
continue // ignored header
|
||||
}
|
||||
headers = append(headers, strings.ToLower(k))
|
||||
}
|
||||
sort.Strings(headers)
|
||||
|
||||
v4.signedHeaders = strings.Join(headers, ";")
|
||||
|
||||
if v4.isPresign {
|
||||
v4.Query.Set("X-Amz-SignedHeaders", v4.signedHeaders)
|
||||
}
|
||||
|
||||
headerValues := make([]string, len(headers))
|
||||
for i, k := range headers {
|
||||
if k == "host" {
|
||||
headerValues[i] = "host:" + v4.Request.URL.Host
|
||||
} else {
|
||||
headerValues[i] = k + ":" +
|
||||
strings.Join(v4.Request.Header[http.CanonicalHeaderKey(k)], ",")
|
||||
}
|
||||
}
|
||||
|
||||
v4.canonicalHeaders = strings.Join(headerValues, "\n")
|
||||
}
|
||||
|
||||
func (v4 *signer) buildCanonicalString() {
|
||||
v4.Request.URL.RawQuery = v4.Query.Encode()
|
||||
uri := v4.Request.URL.Opaque
|
||||
if uri != "" {
|
||||
uri = "/" + strings.Join(strings.Split(uri, "/")[3:], "/")
|
||||
} else {
|
||||
uri = v4.Request.URL.Path
|
||||
}
|
||||
if uri == "" {
|
||||
uri = "/"
|
||||
}
|
||||
|
||||
v4.canonicalString = strings.Join([]string{
|
||||
v4.Request.Method,
|
||||
uri,
|
||||
v4.Request.URL.RawQuery,
|
||||
v4.canonicalHeaders + "\n",
|
||||
v4.signedHeaders,
|
||||
v4.bodyDigest(),
|
||||
}, "\n")
|
||||
}
|
||||
|
||||
func (v4 *signer) buildStringToSign() {
|
||||
v4.stringToSign = strings.Join([]string{
|
||||
authHeaderPrefix,
|
||||
v4.formattedTime,
|
||||
v4.credentialString,
|
||||
hex.EncodeToString(makeSha256([]byte(v4.canonicalString))),
|
||||
}, "\n")
|
||||
}
|
||||
|
||||
func (v4 *signer) buildSignature() {
|
||||
secret := v4.SecretAccessKey
|
||||
date := makeHmac([]byte("AWS4"+secret), []byte(v4.formattedShortTime))
|
||||
region := makeHmac(date, []byte(v4.Region))
|
||||
service := makeHmac(region, []byte(v4.ServiceName))
|
||||
credentials := makeHmac(service, []byte("aws4_request"))
|
||||
signature := makeHmac(credentials, []byte(v4.stringToSign))
|
||||
v4.signature = hex.EncodeToString(signature)
|
||||
}
|
||||
|
||||
func (v4 *signer) bodyDigest() string {
|
||||
hash := v4.Request.Header.Get("X-Amz-Content-Sha256")
|
||||
if hash == "" {
|
||||
if v4.isPresign && v4.ServiceName == "s3" {
|
||||
hash = "UNSIGNED-PAYLOAD"
|
||||
} else if v4.Body == nil {
|
||||
hash = hex.EncodeToString(makeSha256([]byte{}))
|
||||
} else {
|
||||
hash = hex.EncodeToString(makeSha256Reader(v4.Body))
|
||||
}
|
||||
v4.Request.Header.Add("X-Amz-Content-Sha256", hash)
|
||||
}
|
||||
return hash
|
||||
}
|
||||
|
||||
func makeHmac(key []byte, data []byte) []byte {
|
||||
hash := hmac.New(sha256.New, key)
|
||||
hash.Write(data)
|
||||
return hash.Sum(nil)
|
||||
}
|
||||
|
||||
func makeSha256(data []byte) []byte {
|
||||
hash := sha256.New()
|
||||
hash.Write(data)
|
||||
return hash.Sum(nil)
|
||||
}
|
||||
|
||||
func makeSha256Reader(reader io.ReadSeeker) []byte {
|
||||
packet := make([]byte, 4096)
|
||||
hash := sha256.New()
|
||||
|
||||
reader.Seek(0, 0)
|
||||
for {
|
||||
n, err := reader.Read(packet)
|
||||
if n > 0 {
|
||||
hash.Write(packet[0:n])
|
||||
}
|
||||
if err == io.EOF || n == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
reader.Seek(0, 0)
|
||||
|
||||
return hash.Sum(nil)
|
||||
}
|
||||
Generated
Vendored
-89
@@ -1,89 +0,0 @@
|
||||
package v4
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func buildSigner(serviceName string, region string, signTime time.Time, expireTime time.Duration, body string) signer {
|
||||
endpoint := "https://" + serviceName + "." + region + ".amazonaws.com"
|
||||
reader := strings.NewReader(body)
|
||||
req, _ := http.NewRequest("POST", endpoint, reader)
|
||||
req.URL.Opaque = "//example.org/bucket/key-._~,!@#$%^&*()"
|
||||
req.Header.Add("X-Amz-Target", "prefix.Operation")
|
||||
req.Header.Add("Content-Type", "application/x-amz-json-1.0")
|
||||
req.Header.Add("Content-Length", string(len(body)))
|
||||
req.Header.Add("X-Amz-Meta-Other-Header", "some-value=!@#$%^&* ()")
|
||||
|
||||
return signer{
|
||||
Request: req,
|
||||
Time: signTime,
|
||||
ExpireTime: expireTime,
|
||||
Query: req.URL.Query(),
|
||||
Body: reader,
|
||||
ServiceName: serviceName,
|
||||
Region: region,
|
||||
AccessKeyID: "AKID",
|
||||
SecretAccessKey: "SECRET",
|
||||
SessionToken: "SESSION",
|
||||
}
|
||||
}
|
||||
|
||||
func removeWS(text string) string {
|
||||
text = strings.Replace(text, " ", "", -1)
|
||||
text = strings.Replace(text, "\n", "", -1)
|
||||
text = strings.Replace(text, "\t", "", -1)
|
||||
return text
|
||||
}
|
||||
|
||||
func assertEqual(t *testing.T, expected, given string) {
|
||||
if removeWS(expected) != removeWS(given) {
|
||||
t.Errorf("\nExpected: %s\nGiven: %s", expected, given)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresignRequest(t *testing.T) {
|
||||
signer := buildSigner("dynamodb", "us-east-1", time.Unix(0, 0), 300*time.Second, "{}")
|
||||
signer.sign()
|
||||
|
||||
expectedDate := "19700101T000000Z"
|
||||
expectedHeaders := "host;x-amz-meta-other-header;x-amz-target"
|
||||
expectedSig := "41c18d68f9191079dfeead4e3f034328f89d86c79f8e9d51dd48bb70eaf623fc"
|
||||
expectedCred := "AKID/19700101/us-east-1/dynamodb/aws4_request"
|
||||
|
||||
q := signer.Request.URL.Query()
|
||||
assert.Equal(t, expectedSig, q.Get("X-Amz-Signature"))
|
||||
assert.Equal(t, expectedCred, q.Get("X-Amz-Credential"))
|
||||
assert.Equal(t, expectedHeaders, q.Get("X-Amz-SignedHeaders"))
|
||||
assert.Equal(t, expectedDate, q.Get("X-Amz-Date"))
|
||||
}
|
||||
|
||||
func TestSignRequest(t *testing.T) {
|
||||
signer := buildSigner("dynamodb", "us-east-1", time.Unix(0, 0), 0, "{}")
|
||||
signer.sign()
|
||||
|
||||
expectedDate := "19700101T000000Z"
|
||||
expectedSig := "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/dynamodb/aws4_request, SignedHeaders=host;x-amz-date;x-amz-meta-other-header;x-amz-security-token;x-amz-target, Signature=0196959cabd964bd10c05217b40ed151882dd394190438bab0c658dafdbff7a1"
|
||||
|
||||
q := signer.Request.Header
|
||||
assert.Equal(t, expectedSig, q.Get("Authorization"))
|
||||
assert.Equal(t, expectedDate, q.Get("X-Amz-Date"))
|
||||
}
|
||||
|
||||
func BenchmarkPresignRequest(b *testing.B) {
|
||||
signer := buildSigner("dynamodb", "us-east-1", time.Now(), 300*time.Second, "{}")
|
||||
for i := 0; i < b.N; i++ {
|
||||
signer.sign()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkSignRequest(b *testing.B) {
|
||||
signer := buildSigner("dynamodb", "us-east-1", time.Now(), 0, "{}")
|
||||
for i := 0; i < b.N; i++ {
|
||||
signer.sign()
|
||||
}
|
||||
}
|
||||
-4917
File diff suppressed because it is too large
Load Diff
Generated
Vendored
-41
@@ -1,41 +0,0 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"regexp"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/aws/awsutil"
|
||||
)
|
||||
|
||||
var reBucketLocation = regexp.MustCompile(`>([^<>]+)<\/Location`)
|
||||
|
||||
func buildGetBucketLocation(r *aws.Request) {
|
||||
if r.DataFilled() {
|
||||
out := r.Data.(*GetBucketLocationOutput)
|
||||
b, err := ioutil.ReadAll(r.HTTPResponse.Body)
|
||||
if err != nil {
|
||||
r.Error = err
|
||||
return
|
||||
}
|
||||
|
||||
match := reBucketLocation.FindSubmatch(b)
|
||||
if len(match) > 1 {
|
||||
loc := string(match[1])
|
||||
out.LocationConstraint = &loc
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func populateLocationConstraint(r *aws.Request) {
|
||||
if r.ParamsFilled() && r.Config.Region != "us-east-1" {
|
||||
in := r.Params.(*CreateBucketInput)
|
||||
if in.CreateBucketConfiguration == nil {
|
||||
r.Params = awsutil.CopyOf(r.Params)
|
||||
in = r.Params.(*CreateBucketInput)
|
||||
in.CreateBucketConfiguration = &CreateBucketConfiguration{
|
||||
LocationConstraint: &r.Config.Region,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-73
@@ -1,73 +0,0 @@
|
||||
package s3_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/aws/awsutil"
|
||||
"github.com/awslabs/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var s3LocationTests = []struct {
|
||||
body string
|
||||
loc string
|
||||
}{
|
||||
{`<?xml version="1.0" encoding="UTF-8"?><LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`, ``},
|
||||
{`<?xml version="1.0" encoding="UTF-8"?><LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">EU</LocationConstraint>`, `EU`},
|
||||
}
|
||||
|
||||
func TestGetBucketLocation(t *testing.T) {
|
||||
for _, test := range s3LocationTests {
|
||||
s := s3.New(baseConfig)
|
||||
s.Handlers.Send.Clear()
|
||||
s.Handlers.Send.PushBack(func(r *aws.Request) {
|
||||
reader := ioutil.NopCloser(bytes.NewReader([]byte(test.body)))
|
||||
r.HTTPResponse = &http.Response{StatusCode: 200, Body: reader}
|
||||
})
|
||||
|
||||
resp, err := s.GetBucketLocation(&s3.GetBucketLocationInput{Bucket: aws.String("bucket")})
|
||||
assert.NoError(t, err)
|
||||
if test.loc == "" {
|
||||
assert.Nil(t, resp.LocationConstraint)
|
||||
} else {
|
||||
assert.Equal(t, test.loc, *resp.LocationConstraint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPopulateLocationConstraint(t *testing.T) {
|
||||
s := s3.New(baseConfig)
|
||||
in := &s3.CreateBucketInput{
|
||||
Bucket: aws.String("bucket"),
|
||||
}
|
||||
req, _ := s.CreateBucketRequest(in)
|
||||
err := req.Build()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "mock-region", awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint")[0])
|
||||
assert.Nil(t, in.CreateBucketConfiguration) // don't modify original params
|
||||
}
|
||||
|
||||
func TestNoPopulateLocationConstraintIfProvided(t *testing.T) {
|
||||
s := s3.New(baseConfig)
|
||||
req, _ := s.CreateBucketRequest(&s3.CreateBucketInput{
|
||||
Bucket: aws.String("bucket"),
|
||||
CreateBucketConfiguration: &s3.CreateBucketConfiguration{},
|
||||
})
|
||||
err := req.Build()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 0, len(awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint")))
|
||||
}
|
||||
|
||||
func TestNoPopulateLocationConstraintIfClassic(t *testing.T) {
|
||||
s := s3.New(baseConfig.Merge(&aws.Config{Region: "us-east-1"}))
|
||||
req, _ := s.CreateBucketRequest(&s3.CreateBucketInput{
|
||||
Bucket: aws.String("bucket"),
|
||||
})
|
||||
err := req.Build()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 0, len(awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint")))
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
)
|
||||
|
||||
// contentMD5 computes and sets the HTTP Content-MD5 header for requests that
|
||||
// require it.
|
||||
func contentMD5(r *aws.Request) {
|
||||
h := md5.New()
|
||||
|
||||
// hash the body. seek back to the first position after reading to reset
|
||||
// the body for transmission. copy errors may be assumed to be from the
|
||||
// body.
|
||||
_, err := io.Copy(h, r.Body)
|
||||
if err != nil {
|
||||
r.Error = fmt.Errorf("content-md5: read: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = r.Body.Seek(0, 0)
|
||||
if err != nil {
|
||||
r.Error = fmt.Errorf("content-md5: seek: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// encode the md5 checksum in base64 and set the request header.
|
||||
sum := h.Sum(nil)
|
||||
sum64 := make([]byte, base64.StdEncoding.EncodedLen(len(sum)))
|
||||
base64.StdEncoding.Encode(sum64, sum)
|
||||
r.HTTPRequest.Header.Set("Content-MD5", string(sum64))
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package s3
|
||||
|
||||
import "github.com/awslabs/aws-sdk-go/aws"
|
||||
|
||||
func init() {
|
||||
initService = func(s *aws.Service) {
|
||||
// Support building custom host-style bucket endpoints
|
||||
s.Handlers.Build.PushFront(updateHostWithBucket)
|
||||
|
||||
// Require SSL when using SSE keys
|
||||
s.Handlers.Validate.PushBack(validateSSERequiresSSL)
|
||||
s.Handlers.Build.PushBack(computeSSEKeys)
|
||||
|
||||
// S3 uses custom error unmarshaling logic
|
||||
s.Handlers.UnmarshalError.Clear()
|
||||
s.Handlers.UnmarshalError.PushBack(unmarshalError)
|
||||
}
|
||||
|
||||
initRequest = func(r *aws.Request) {
|
||||
switch r.Operation {
|
||||
case opPutBucketCORS, opPutBucketLifecycle, opPutBucketTagging, opDeleteObjects:
|
||||
// These S3 operations require Content-MD5 to be set
|
||||
r.Handlers.Build.PushBack(contentMD5)
|
||||
case opGetBucketLocation:
|
||||
// GetBucketLocation has custom parsing logic
|
||||
r.Handlers.Unmarshal.PushFront(buildGetBucketLocation)
|
||||
case opCreateBucket:
|
||||
// Auto-populate LocationConstraint with current region
|
||||
r.Handlers.Validate.PushFront(populateLocationConstraint)
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-78
@@ -1,78 +0,0 @@
|
||||
package s3_test
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func assertMD5(t *testing.T, req *aws.Request) {
|
||||
err := req.Build()
|
||||
assert.NoError(t, err)
|
||||
|
||||
b, _ := ioutil.ReadAll(req.HTTPRequest.Body)
|
||||
out := md5.Sum(b)
|
||||
assert.NotEmpty(t, b)
|
||||
assert.Equal(t, base64.StdEncoding.EncodeToString(out[:]), req.HTTPRequest.Header.Get("Content-MD5"))
|
||||
}
|
||||
|
||||
func TestMD5InPutBucketCORS(t *testing.T) {
|
||||
svc := s3.New(baseConfig)
|
||||
req, _ := svc.PutBucketCORSRequest(&s3.PutBucketCORSInput{
|
||||
Bucket: aws.String("bucketname"),
|
||||
CORSConfiguration: &s3.CORSConfiguration{
|
||||
CORSRules: []*s3.CORSRule{
|
||||
{AllowedMethods: []*string{aws.String("GET")}},
|
||||
},
|
||||
},
|
||||
})
|
||||
assertMD5(t, req)
|
||||
}
|
||||
|
||||
func TestMD5InPutBucketLifecycle(t *testing.T) {
|
||||
svc := s3.New(baseConfig)
|
||||
req, _ := svc.PutBucketLifecycleRequest(&s3.PutBucketLifecycleInput{
|
||||
Bucket: aws.String("bucketname"),
|
||||
LifecycleConfiguration: &s3.LifecycleConfiguration{
|
||||
Rules: []*s3.LifecycleRule{
|
||||
{
|
||||
ID: aws.String("ID"),
|
||||
Prefix: aws.String("Prefix"),
|
||||
Status: aws.String("Enabled"),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
assertMD5(t, req)
|
||||
}
|
||||
|
||||
func TestMD5InPutBucketTagging(t *testing.T) {
|
||||
svc := s3.New(baseConfig)
|
||||
req, _ := svc.PutBucketTaggingRequest(&s3.PutBucketTaggingInput{
|
||||
Bucket: aws.String("bucketname"),
|
||||
Tagging: &s3.Tagging{
|
||||
TagSet: []*s3.Tag{
|
||||
{Key: aws.String("KEY"), Value: aws.String("VALUE")},
|
||||
},
|
||||
},
|
||||
})
|
||||
assertMD5(t, req)
|
||||
}
|
||||
|
||||
func TestMD5InDeleteObjects(t *testing.T) {
|
||||
svc := s3.New(baseConfig)
|
||||
req, _ := svc.DeleteObjectsRequest(&s3.DeleteObjectsInput{
|
||||
Bucket: aws.String("bucketname"),
|
||||
Delete: &s3.Delete{
|
||||
Objects: []*s3.ObjectIdentifier{
|
||||
{Key: aws.String("key")},
|
||||
},
|
||||
},
|
||||
})
|
||||
assertMD5(t, req)
|
||||
}
|
||||
-1472
File diff suppressed because it is too large
Load Diff
Generated
Vendored
-53
@@ -1,53 +0,0 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/aws/awsutil"
|
||||
)
|
||||
|
||||
var reDomain = regexp.MustCompile(`^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$`)
|
||||
var reIPAddress = regexp.MustCompile(`^(\d+\.){3}\d+$`)
|
||||
|
||||
// dnsCompatibleBucketName returns true if the bucket name is DNS compatible.
|
||||
// Buckets created outside of the classic region MUST be DNS compatible.
|
||||
func dnsCompatibleBucketName(bucket string) bool {
|
||||
return reDomain.MatchString(bucket) &&
|
||||
!reIPAddress.MatchString(bucket) &&
|
||||
!strings.Contains(bucket, "..")
|
||||
}
|
||||
|
||||
// hostStyleBucketName returns true if the request should put the bucket in
|
||||
// the host. This is false if S3ForcePathStyle is explicitly set or if the
|
||||
// bucket is not DNS compatible.
|
||||
func hostStyleBucketName(r *aws.Request, bucket string) bool {
|
||||
if r.Config.S3ForcePathStyle {
|
||||
return false
|
||||
}
|
||||
|
||||
// Bucket might be DNS compatible but dots in the hostname will fail
|
||||
// certificate validation, so do not use host-style.
|
||||
if r.HTTPRequest.URL.Scheme == "https" && strings.Contains(bucket, ".") {
|
||||
return false
|
||||
}
|
||||
|
||||
// Use host-style if the bucket is DNS compatible
|
||||
return dnsCompatibleBucketName(bucket)
|
||||
}
|
||||
|
||||
func updateHostWithBucket(r *aws.Request) {
|
||||
b := awsutil.ValuesAtPath(r.Params, "Bucket")
|
||||
if len(b) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
if bucket := b[0].(string); bucket != "" && hostStyleBucketName(r, bucket) {
|
||||
r.HTTPRequest.URL.Host = bucket + "." + r.HTTPRequest.URL.Host
|
||||
r.HTTPRequest.URL.Path = strings.Replace(r.HTTPRequest.URL.Path, "/{Bucket}", "", -1)
|
||||
if r.HTTPRequest.URL.Path == "" {
|
||||
r.HTTPRequest.URL.Path = "/"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-63
@@ -1,63 +0,0 @@
|
||||
package s3_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
type s3BucketTest struct {
|
||||
bucket string
|
||||
url string
|
||||
}
|
||||
|
||||
var (
|
||||
baseConfig = &aws.Config{
|
||||
Credentials: aws.DetectCreds("AKID", "SECRET", ""),
|
||||
Region: "mock-region",
|
||||
}
|
||||
|
||||
sslTests = []s3BucketTest{
|
||||
{"abc", "https://abc.s3.mock-region.amazonaws.com/"},
|
||||
{"a$b$c", "https://s3.mock-region.amazonaws.com/a%24b%24c"},
|
||||
{"a.b.c", "https://s3.mock-region.amazonaws.com/a.b.c"},
|
||||
{"a..bc", "https://s3.mock-region.amazonaws.com/a..bc"},
|
||||
}
|
||||
|
||||
nosslTests = []s3BucketTest{
|
||||
{"a.b.c", "http://a.b.c.s3.mock-region.amazonaws.com/"},
|
||||
{"a..bc", "http://s3.mock-region.amazonaws.com/a..bc"},
|
||||
}
|
||||
|
||||
forcepathTests = []s3BucketTest{
|
||||
{"abc", "https://s3.mock-region.amazonaws.com/abc"},
|
||||
{"a$b$c", "https://s3.mock-region.amazonaws.com/a%24b%24c"},
|
||||
{"a.b.c", "https://s3.mock-region.amazonaws.com/a.b.c"},
|
||||
{"a..bc", "https://s3.mock-region.amazonaws.com/a..bc"},
|
||||
}
|
||||
)
|
||||
|
||||
func runTests(t *testing.T, svc *s3.S3, tests []s3BucketTest) {
|
||||
for _, test := range tests {
|
||||
req, _ := svc.ListObjectsRequest(&s3.ListObjectsInput{Bucket: &test.bucket})
|
||||
req.Build()
|
||||
assert.Equal(t, test.url, req.HTTPRequest.URL.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostStyleBucketBuild(t *testing.T) {
|
||||
s := s3.New(baseConfig)
|
||||
runTests(t, s, sslTests)
|
||||
}
|
||||
|
||||
func TestHostStyleBucketBuildNoSSL(t *testing.T) {
|
||||
s := s3.New(baseConfig.Merge(&aws.Config{DisableSSL: true}))
|
||||
runTests(t, s, nosslTests)
|
||||
}
|
||||
|
||||
func TestPathStyleBucketBuild(t *testing.T) {
|
||||
s := s3.New(baseConfig.Merge(&aws.Config{S3ForcePathStyle: true}))
|
||||
runTests(t, s, forcepathTests)
|
||||
}
|
||||
Generated
Vendored
-107
@@ -1,107 +0,0 @@
|
||||
// +build integration
|
||||
|
||||
package s3_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var bucketName *string
|
||||
var svc *s3.S3
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
setup()
|
||||
defer teardown() // only called if we panic
|
||||
result := m.Run()
|
||||
teardown()
|
||||
os.Exit(result)
|
||||
}
|
||||
|
||||
// Create a bucket for testing
|
||||
func setup() {
|
||||
svc = s3.New(nil)
|
||||
bucketName = aws.String(
|
||||
fmt.Sprintf("aws-sdk-go-integration-%d", time.Now().Unix()))
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
_, err := svc.CreateBucket(&s3.CreateBucketInput{Bucket: bucketName})
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
// Delete the bucket
|
||||
func teardown() {
|
||||
resp, _ := svc.ListObjects(&s3.ListObjectsInput{Bucket: bucketName})
|
||||
for _, o := range resp.Contents {
|
||||
svc.DeleteObject(&s3.DeleteObjectInput{Bucket: bucketName, Key: o.Key})
|
||||
}
|
||||
svc.DeleteBucket(&s3.DeleteBucketInput{Bucket: bucketName})
|
||||
}
|
||||
|
||||
func TestWriteToObject(t *testing.T) {
|
||||
_, err := svc.PutObject(&s3.PutObjectInput{
|
||||
Bucket: bucketName,
|
||||
Key: aws.String("key name"),
|
||||
Body: bytes.NewReader([]byte("hello world")),
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
|
||||
resp, err := svc.GetObject(&s3.GetObjectInput{
|
||||
Bucket: bucketName,
|
||||
Key: aws.String("key name"),
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
|
||||
b, _ := ioutil.ReadAll(resp.Body)
|
||||
assert.Equal(t, []byte("hello world"), b)
|
||||
}
|
||||
|
||||
func TestPresignedGetPut(t *testing.T) {
|
||||
putreq, _ := svc.PutObjectRequest(&s3.PutObjectInput{
|
||||
Bucket: bucketName,
|
||||
Key: aws.String("presigned-key"),
|
||||
})
|
||||
|
||||
// Presign a PUT request
|
||||
puturl, err := putreq.Presign(300 * time.Second)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// PUT to the presigned URL with a body
|
||||
buf := bytes.NewReader([]byte("hello world"))
|
||||
puthttpreq, err := http.NewRequest("PUT", puturl, buf)
|
||||
assert.NoError(t, err)
|
||||
|
||||
putresp, err := http.DefaultClient.Do(puthttpreq)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 200, putresp.StatusCode)
|
||||
|
||||
// Presign a GET on the same URL
|
||||
getreq, _ := svc.GetObjectRequest(&s3.GetObjectInput{
|
||||
Bucket: bucketName,
|
||||
Key: aws.String("presigned-key"),
|
||||
})
|
||||
|
||||
geturl, err := getreq.Presign(300 * time.Second)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Get the body
|
||||
getresp, err := http.Get(geturl)
|
||||
assert.NoError(t, err)
|
||||
|
||||
defer getresp.Body.Close()
|
||||
b, err := ioutil.ReadAll(getresp.Body)
|
||||
assert.Equal(t, "hello world", string(b))
|
||||
}
|
||||
Generated
Vendored
-111
@@ -1,111 +0,0 @@
|
||||
package s3iface
|
||||
|
||||
import (
|
||||
"github.com/awslabs/aws-sdk-go/service/s3"
|
||||
)
|
||||
|
||||
type S3API interface {
|
||||
AbortMultipartUpload(*s3.AbortMultipartUploadInput) (*s3.AbortMultipartUploadOutput, error)
|
||||
|
||||
CompleteMultipartUpload(*s3.CompleteMultipartUploadInput) (*s3.CompleteMultipartUploadOutput, error)
|
||||
|
||||
CopyObject(*s3.CopyObjectInput) (*s3.CopyObjectOutput, error)
|
||||
|
||||
CreateBucket(*s3.CreateBucketInput) (*s3.CreateBucketOutput, error)
|
||||
|
||||
CreateMultipartUpload(*s3.CreateMultipartUploadInput) (*s3.CreateMultipartUploadOutput, error)
|
||||
|
||||
DeleteBucket(*s3.DeleteBucketInput) (*s3.DeleteBucketOutput, error)
|
||||
|
||||
DeleteBucketCORS(*s3.DeleteBucketCORSInput) (*s3.DeleteBucketCORSOutput, error)
|
||||
|
||||
DeleteBucketLifecycle(*s3.DeleteBucketLifecycleInput) (*s3.DeleteBucketLifecycleOutput, error)
|
||||
|
||||
DeleteBucketPolicy(*s3.DeleteBucketPolicyInput) (*s3.DeleteBucketPolicyOutput, error)
|
||||
|
||||
DeleteBucketReplication(*s3.DeleteBucketReplicationInput) (*s3.DeleteBucketReplicationOutput, error)
|
||||
|
||||
DeleteBucketTagging(*s3.DeleteBucketTaggingInput) (*s3.DeleteBucketTaggingOutput, error)
|
||||
|
||||
DeleteBucketWebsite(*s3.DeleteBucketWebsiteInput) (*s3.DeleteBucketWebsiteOutput, error)
|
||||
|
||||
DeleteObject(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error)
|
||||
|
||||
DeleteObjects(*s3.DeleteObjectsInput) (*s3.DeleteObjectsOutput, error)
|
||||
|
||||
GetBucketACL(*s3.GetBucketACLInput) (*s3.GetBucketACLOutput, error)
|
||||
|
||||
GetBucketCORS(*s3.GetBucketCORSInput) (*s3.GetBucketCORSOutput, error)
|
||||
|
||||
GetBucketLifecycle(*s3.GetBucketLifecycleInput) (*s3.GetBucketLifecycleOutput, error)
|
||||
|
||||
GetBucketLocation(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error)
|
||||
|
||||
GetBucketLogging(*s3.GetBucketLoggingInput) (*s3.GetBucketLoggingOutput, error)
|
||||
|
||||
GetBucketNotification(*s3.GetBucketNotificationInput) (*s3.GetBucketNotificationOutput, error)
|
||||
|
||||
GetBucketPolicy(*s3.GetBucketPolicyInput) (*s3.GetBucketPolicyOutput, error)
|
||||
|
||||
GetBucketReplication(*s3.GetBucketReplicationInput) (*s3.GetBucketReplicationOutput, error)
|
||||
|
||||
GetBucketRequestPayment(*s3.GetBucketRequestPaymentInput) (*s3.GetBucketRequestPaymentOutput, error)
|
||||
|
||||
GetBucketTagging(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error)
|
||||
|
||||
GetBucketVersioning(*s3.GetBucketVersioningInput) (*s3.GetBucketVersioningOutput, error)
|
||||
|
||||
GetBucketWebsite(*s3.GetBucketWebsiteInput) (*s3.GetBucketWebsiteOutput, error)
|
||||
|
||||
GetObject(*s3.GetObjectInput) (*s3.GetObjectOutput, error)
|
||||
|
||||
GetObjectACL(*s3.GetObjectACLInput) (*s3.GetObjectACLOutput, error)
|
||||
|
||||
GetObjectTorrent(*s3.GetObjectTorrentInput) (*s3.GetObjectTorrentOutput, error)
|
||||
|
||||
HeadBucket(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error)
|
||||
|
||||
HeadObject(*s3.HeadObjectInput) (*s3.HeadObjectOutput, error)
|
||||
|
||||
ListBuckets(*s3.ListBucketsInput) (*s3.ListBucketsOutput, error)
|
||||
|
||||
ListMultipartUploads(*s3.ListMultipartUploadsInput) (*s3.ListMultipartUploadsOutput, error)
|
||||
|
||||
ListObjectVersions(*s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error)
|
||||
|
||||
ListObjects(*s3.ListObjectsInput) (*s3.ListObjectsOutput, error)
|
||||
|
||||
ListParts(*s3.ListPartsInput) (*s3.ListPartsOutput, error)
|
||||
|
||||
PutBucketACL(*s3.PutBucketACLInput) (*s3.PutBucketACLOutput, error)
|
||||
|
||||
PutBucketCORS(*s3.PutBucketCORSInput) (*s3.PutBucketCORSOutput, error)
|
||||
|
||||
PutBucketLifecycle(*s3.PutBucketLifecycleInput) (*s3.PutBucketLifecycleOutput, error)
|
||||
|
||||
PutBucketLogging(*s3.PutBucketLoggingInput) (*s3.PutBucketLoggingOutput, error)
|
||||
|
||||
PutBucketNotification(*s3.PutBucketNotificationInput) (*s3.PutBucketNotificationOutput, error)
|
||||
|
||||
PutBucketPolicy(*s3.PutBucketPolicyInput) (*s3.PutBucketPolicyOutput, error)
|
||||
|
||||
PutBucketReplication(*s3.PutBucketReplicationInput) (*s3.PutBucketReplicationOutput, error)
|
||||
|
||||
PutBucketRequestPayment(*s3.PutBucketRequestPaymentInput) (*s3.PutBucketRequestPaymentOutput, error)
|
||||
|
||||
PutBucketTagging(*s3.PutBucketTaggingInput) (*s3.PutBucketTaggingOutput, error)
|
||||
|
||||
PutBucketVersioning(*s3.PutBucketVersioningInput) (*s3.PutBucketVersioningOutput, error)
|
||||
|
||||
PutBucketWebsite(*s3.PutBucketWebsiteInput) (*s3.PutBucketWebsiteOutput, error)
|
||||
|
||||
PutObject(*s3.PutObjectInput) (*s3.PutObjectOutput, error)
|
||||
|
||||
PutObjectACL(*s3.PutObjectACLInput) (*s3.PutObjectACLOutput, error)
|
||||
|
||||
RestoreObject(*s3.RestoreObjectInput) (*s3.RestoreObjectOutput, error)
|
||||
|
||||
UploadPart(*s3.UploadPartInput) (*s3.UploadPartOutput, error)
|
||||
|
||||
UploadPartCopy(*s3.UploadPartCopyInput) (*s3.UploadPartCopyOutput, error)
|
||||
}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/internal/protocol/restxml"
|
||||
"github.com/awslabs/aws-sdk-go/internal/signer/v4"
|
||||
)
|
||||
|
||||
// S3 is a client for Amazon S3.
|
||||
type S3 struct {
|
||||
*aws.Service
|
||||
}
|
||||
|
||||
// Used for custom service initialization logic
|
||||
var initService func(*aws.Service)
|
||||
|
||||
// Used for custom request initialization logic
|
||||
var initRequest func(*aws.Request)
|
||||
|
||||
// New returns a new S3 client.
|
||||
func New(config *aws.Config) *S3 {
|
||||
if config == nil {
|
||||
config = &aws.Config{}
|
||||
}
|
||||
|
||||
service := &aws.Service{
|
||||
Config: aws.DefaultConfig.Merge(config),
|
||||
ServiceName: "s3",
|
||||
APIVersion: "2006-03-01",
|
||||
}
|
||||
service.Initialize()
|
||||
|
||||
// Handlers
|
||||
service.Handlers.Sign.PushBack(v4.Sign)
|
||||
service.Handlers.Build.PushBack(restxml.Build)
|
||||
service.Handlers.Unmarshal.PushBack(restxml.Unmarshal)
|
||||
service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta)
|
||||
service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError)
|
||||
|
||||
// Run custom service initialization if present
|
||||
if initService != nil {
|
||||
initService(service)
|
||||
}
|
||||
|
||||
return &S3{service}
|
||||
}
|
||||
|
||||
// newRequest creates a new request for a S3 operation and runs any
|
||||
// custom request initialization.
|
||||
func (c *S3) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {
|
||||
req := aws.NewRequest(c.Service, op, params, data)
|
||||
|
||||
// Run custom request initialization if present
|
||||
if initRequest != nil {
|
||||
initRequest(req)
|
||||
}
|
||||
|
||||
return req
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/aws/awsutil"
|
||||
)
|
||||
|
||||
var errSSERequiresSSL = aws.APIError{
|
||||
Code: "ConfigError",
|
||||
Message: "cannot send SSE keys over HTTP.",
|
||||
}
|
||||
|
||||
func validateSSERequiresSSL(r *aws.Request) {
|
||||
if r.HTTPRequest.URL.Scheme != "https" {
|
||||
p := awsutil.ValuesAtPath(r.Params, "SSECustomerKey||CopySourceSSECustomerKey")
|
||||
if len(p) > 0 {
|
||||
r.Error = errSSERequiresSSL
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func computeSSEKeys(r *aws.Request) {
|
||||
headers := []string{
|
||||
"x-amz-server-side-encryption-customer-key",
|
||||
"x-amz-copy-source-server-side-encryption-customer-key",
|
||||
}
|
||||
|
||||
for _, h := range headers {
|
||||
md5h := h + "-md5"
|
||||
if key := r.HTTPRequest.Header.Get(h); key != "" {
|
||||
// Base64-encode the value
|
||||
b64v := base64.StdEncoding.EncodeToString([]byte(key))
|
||||
r.HTTPRequest.Header.Set(h, b64v)
|
||||
|
||||
// Add MD5 if it wasn't computed
|
||||
if r.HTTPRequest.Header.Get(md5h) == "" {
|
||||
sum := md5.Sum([]byte(key))
|
||||
b64sum := base64.StdEncoding.EncodeToString(sum[:])
|
||||
r.HTTPRequest.Header.Set(md5h, b64sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
package s3_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSSECustomerKeyOverHTTPError(t *testing.T) {
|
||||
s := s3.New(baseConfig.Merge(&aws.Config{DisableSSL: true}))
|
||||
req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{
|
||||
Bucket: aws.String("bucket"),
|
||||
CopySource: aws.String("bucket/source"),
|
||||
Key: aws.String("dest"),
|
||||
SSECustomerKey: aws.String("key"),
|
||||
})
|
||||
err := req.Build()
|
||||
|
||||
assert.Error(t, err)
|
||||
aerr := aws.Error(err)
|
||||
assert.Equal(t, "ConfigError", aerr.Code)
|
||||
assert.Contains(t, aerr.Message, "cannot send SSE keys over HTTP")
|
||||
}
|
||||
|
||||
func TestCopySourceSSECustomerKeyOverHTTPError(t *testing.T) {
|
||||
s := s3.New(baseConfig.Merge(&aws.Config{DisableSSL: true}))
|
||||
req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{
|
||||
Bucket: aws.String("bucket"),
|
||||
CopySource: aws.String("bucket/source"),
|
||||
Key: aws.String("dest"),
|
||||
CopySourceSSECustomerKey: aws.String("key"),
|
||||
})
|
||||
err := req.Build()
|
||||
|
||||
assert.Error(t, err)
|
||||
aerr := aws.Error(err)
|
||||
assert.Equal(t, "ConfigError", aerr.Code)
|
||||
assert.Contains(t, aerr.Message, "cannot send SSE keys over HTTP")
|
||||
}
|
||||
|
||||
func TestComputeSSEKeys(t *testing.T) {
|
||||
s := s3.New(baseConfig)
|
||||
req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{
|
||||
Bucket: aws.String("bucket"),
|
||||
CopySource: aws.String("bucket/source"),
|
||||
Key: aws.String("dest"),
|
||||
SSECustomerKey: aws.String("key"),
|
||||
CopySourceSSECustomerKey: aws.String("key"),
|
||||
})
|
||||
err := req.Build()
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key"))
|
||||
assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key"))
|
||||
assert.Equal(t, "PG4LipwVIkqCKLmpjKFTHQ==", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key-md5"))
|
||||
assert.Equal(t, "PG4LipwVIkqCKLmpjKFTHQ==", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key-md5"))
|
||||
}
|
||||
|
||||
func TestComputeSSEKeysShortcircuit(t *testing.T) {
|
||||
s := s3.New(baseConfig)
|
||||
req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{
|
||||
Bucket: aws.String("bucket"),
|
||||
CopySource: aws.String("bucket/source"),
|
||||
Key: aws.String("dest"),
|
||||
SSECustomerKey: aws.String("key"),
|
||||
CopySourceSSECustomerKey: aws.String("key"),
|
||||
SSECustomerKeyMD5: aws.String("MD5"),
|
||||
CopySourceSSECustomerKeyMD5: aws.String("MD5"),
|
||||
})
|
||||
err := req.Build()
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key"))
|
||||
assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key"))
|
||||
assert.Equal(t, "MD5", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key-md5"))
|
||||
assert.Equal(t, "MD5", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key-md5"))
|
||||
}
|
||||
Generated
Vendored
-41
@@ -1,41 +0,0 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
)
|
||||
|
||||
type xmlErrorResponse struct {
|
||||
XMLName xml.Name `xml:"Error"`
|
||||
Code string `xml:"Code"`
|
||||
Message string `xml:"Message"`
|
||||
}
|
||||
|
||||
func unmarshalError(r *aws.Request) {
|
||||
defer r.HTTPResponse.Body.Close()
|
||||
|
||||
if r.HTTPResponse.ContentLength == int64(0) {
|
||||
// No body, use status code to generate an APIError
|
||||
r.Error = aws.APIError{
|
||||
StatusCode: r.HTTPResponse.StatusCode,
|
||||
Code: strings.Replace(r.HTTPResponse.Status, " ", "", -1),
|
||||
Message: r.HTTPResponse.Status,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
resp := &xmlErrorResponse{}
|
||||
err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp)
|
||||
if err != nil && err != io.EOF {
|
||||
r.Error = err
|
||||
} else {
|
||||
r.Error = aws.APIError{
|
||||
StatusCode: r.HTTPResponse.StatusCode,
|
||||
Code: resp.Code,
|
||||
Message: resp.Message,
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-49
@@ -1,49 +0,0 @@
|
||||
package s3_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/awslabs/aws-sdk-go/aws"
|
||||
"github.com/awslabs/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var s3StatusCodeErrorTests = []struct {
|
||||
scode int
|
||||
status string
|
||||
body string
|
||||
code string
|
||||
message string
|
||||
}{
|
||||
{403, "Forbidden", "", "Forbidden", "Forbidden"},
|
||||
{400, "Bad Request", "", "BadRequest", "Bad Request"},
|
||||
{404, "Not Found", "", "NotFound", "Not Found"},
|
||||
{500, "Internal Error", "", "InternalError", "Internal Error"},
|
||||
}
|
||||
|
||||
func TestStatusCodeError(t *testing.T) {
|
||||
for _, test := range s3StatusCodeErrorTests {
|
||||
s := s3.New(baseConfig)
|
||||
s.Handlers.Send.Clear()
|
||||
s.Handlers.Send.PushBack(func(r *aws.Request) {
|
||||
body := ioutil.NopCloser(bytes.NewReader([]byte(test.body)))
|
||||
r.HTTPResponse = &http.Response{
|
||||
ContentLength: int64(len(test.body)),
|
||||
StatusCode: test.scode,
|
||||
Status: test.status,
|
||||
Body: body,
|
||||
}
|
||||
})
|
||||
_, err := s.PutBucketACL(&s3.PutBucketACLInput{
|
||||
Bucket: aws.String("bucket"), ACL: aws.String("public-read"),
|
||||
})
|
||||
|
||||
assert.Error(t, err)
|
||||
aerr := aws.Error(err)
|
||||
assert.Equal(t, test.code, aerr.Code)
|
||||
assert.Equal(t, test.message, aerr.Message)
|
||||
}
|
||||
}
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
Copyright (c) 2012-2014 Charles Banning <clbanning@gmail.com>. All rights reserved.
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
===============================================================================
|
||||
|
||||
Go Language Copyright & License -
|
||||
|
||||
Copyright 2009 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.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
-177
@@ -1,177 +0,0 @@
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultElementTag = "element"
|
||||
)
|
||||
|
||||
// Encode arbitrary value as XML.
|
||||
//
|
||||
// Note: unmarshaling the resultant
|
||||
// XML may not return the original value, since tag labels may have been injected
|
||||
// to create the XML representation of the value.
|
||||
/*
|
||||
Encode an arbitrary JSON object.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github/clbanning/mxj"
|
||||
)
|
||||
|
||||
func main() {
|
||||
jsondata := []byte(`[
|
||||
{ "somekey":"somevalue" },
|
||||
"string",
|
||||
3.14159265,
|
||||
true
|
||||
]`)
|
||||
var i interface{}
|
||||
err := json.Unmarshal(jsondata, &i)
|
||||
if err != nil {
|
||||
// do something
|
||||
}
|
||||
x, err := anyxml.XmlIndent(i, "", " ", "mydoc")
|
||||
if err != nil {
|
||||
// do something else
|
||||
}
|
||||
fmt.Println(string(x))
|
||||
}
|
||||
|
||||
output:
|
||||
<mydoc>
|
||||
<somekey>somevalue</somekey>
|
||||
<element>string</element>
|
||||
<element>3.14159265</element>
|
||||
<element>true</element>
|
||||
</mydoc>
|
||||
*/
|
||||
// Alternative values for DefaultRootTag and DefaultElementTag can be set as:
|
||||
// AnyXmlIndent( v, myRootTag, myElementTag).
|
||||
func AnyXml(v interface{}, tags ...string) ([]byte, error) {
|
||||
if reflect.TypeOf(v).Kind() == reflect.Struct {
|
||||
return xml.Marshal(v)
|
||||
}
|
||||
|
||||
var err error
|
||||
s := new(string)
|
||||
p := new(pretty)
|
||||
|
||||
var rt, et string
|
||||
if len(tags) == 1 || len(tags) == 2 {
|
||||
rt = tags[0]
|
||||
} else {
|
||||
rt = DefaultRootTag
|
||||
}
|
||||
if len(tags) == 2 {
|
||||
et = tags[1]
|
||||
} else {
|
||||
et = DefaultElementTag
|
||||
}
|
||||
|
||||
var ss string
|
||||
var b []byte
|
||||
switch v.(type) {
|
||||
case []interface{}:
|
||||
ss = "<" + rt + ">"
|
||||
for _, vv := range v.([]interface{}) {
|
||||
switch vv.(type) {
|
||||
case map[string]interface{}:
|
||||
m := vv.(map[string]interface{})
|
||||
if len(m) == 1 {
|
||||
for tag, val := range m {
|
||||
err = mapToXmlIndent(false, s, tag, val, p)
|
||||
}
|
||||
} else {
|
||||
err = mapToXmlIndent(false, s, et, vv, p)
|
||||
}
|
||||
default:
|
||||
err = mapToXmlIndent(false, s, et, vv, p)
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
ss += *s + "</" + rt + ">"
|
||||
b = []byte(ss)
|
||||
case map[string]interface{}:
|
||||
m := Map(v.(map[string]interface{}))
|
||||
b, err = m.Xml(rt)
|
||||
default:
|
||||
err = mapToXmlIndent(false, s, rt, v, p)
|
||||
b = []byte(*s)
|
||||
}
|
||||
|
||||
return b, err
|
||||
}
|
||||
|
||||
// Encode an arbitrary value as a pretty XML string.
|
||||
// Alternative values for DefaultRootTag and DefaultElementTag can be set as:
|
||||
// AnyXmlIndent( v, "", " ", myRootTag, myElementTag).
|
||||
func AnyXmlIndent(v interface{}, prefix, indent string, tags ...string) ([]byte, error) {
|
||||
if reflect.TypeOf(v).Kind() == reflect.Struct {
|
||||
return xml.MarshalIndent(v, prefix, indent)
|
||||
}
|
||||
|
||||
var err error
|
||||
s := new(string)
|
||||
p := new(pretty)
|
||||
p.indent = indent
|
||||
p.padding = prefix
|
||||
|
||||
var rt, et string
|
||||
if len(tags) == 1 || len(tags) == 2 {
|
||||
rt = tags[0]
|
||||
} else {
|
||||
rt = DefaultRootTag
|
||||
}
|
||||
if len(tags) == 2 {
|
||||
et = tags[1]
|
||||
} else {
|
||||
et = DefaultElementTag
|
||||
}
|
||||
|
||||
var ss string
|
||||
var b []byte
|
||||
switch v.(type) {
|
||||
case []interface{}:
|
||||
ss = "<" + rt + ">\n"
|
||||
p.Indent()
|
||||
for _, vv := range v.([]interface{}) {
|
||||
switch vv.(type) {
|
||||
case map[string]interface{}:
|
||||
m := vv.(map[string]interface{})
|
||||
if len(m) == 1 {
|
||||
for tag, val := range m {
|
||||
err = mapToXmlIndent(true, s, tag, val, p)
|
||||
}
|
||||
} else {
|
||||
p.start = 1 // we 1 tag in
|
||||
err = mapToXmlIndent(true, s, et, vv, p)
|
||||
*s += "\n"
|
||||
}
|
||||
default:
|
||||
p.start = 0 // in case trailing p.start = 1
|
||||
err = mapToXmlIndent(true, s, et, vv, p)
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
ss += *s + "</" + rt + ">"
|
||||
b = []byte(ss)
|
||||
case map[string]interface{}:
|
||||
m := Map(v.(map[string]interface{}))
|
||||
b, err = m.XmlIndent(prefix, indent, rt)
|
||||
default:
|
||||
err = mapToXmlIndent(true, s, rt, v, p)
|
||||
b = []byte(*s)
|
||||
}
|
||||
|
||||
return b, err
|
||||
}
|
||||
-110
@@ -1,110 +0,0 @@
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAnyXmlHeader(t *testing.T) {
|
||||
fmt.Println("\n---------------- anyxml_test.go ...\n")
|
||||
}
|
||||
|
||||
var anydata = []byte(`[
|
||||
{
|
||||
"somekey": "somevalue"
|
||||
},
|
||||
{
|
||||
"somekey": "somevalue"
|
||||
},
|
||||
{
|
||||
"somekey": "somevalue",
|
||||
"someotherkey": "someothervalue"
|
||||
},
|
||||
"string",
|
||||
3.14159265,
|
||||
true
|
||||
]`)
|
||||
|
||||
type MyStruct struct {
|
||||
Somekey string `xml:"somekey"`
|
||||
B float32 `xml:"floatval"`
|
||||
}
|
||||
|
||||
func TestAnyXml(t *testing.T) {
|
||||
var i interface{}
|
||||
err := json.Unmarshal(anydata, &i)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
x, err := AnyXml(i)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println("[]->x:", string(x))
|
||||
|
||||
a := []interface{}{"try", "this", 3.14159265, true}
|
||||
x, err = AnyXml(a)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println("a->x:", string(x))
|
||||
|
||||
x, err = AnyXml(a, "myRootTag", "myElementTag")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println("a->x:", string(x))
|
||||
|
||||
x, err = AnyXml(3.14159625)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println("f->x:", string(x))
|
||||
|
||||
s := MyStruct{"somevalue", 3.14159625}
|
||||
x, err = AnyXml(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println("s->x:", string(x))
|
||||
}
|
||||
|
||||
func TestAnyXmlIndent(t *testing.T) {
|
||||
var i interface{}
|
||||
err := json.Unmarshal(anydata, &i)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
x, err := AnyXmlIndent(i, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println("[]->x:\n", string(x))
|
||||
|
||||
a := []interface{}{"try", "this", 3.14159265, true}
|
||||
x, err = AnyXmlIndent(a, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println("a->x:\n", string(x))
|
||||
|
||||
x, err = AnyXmlIndent(3.14159625, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println("f->x:\n", string(x))
|
||||
|
||||
x, err = AnyXmlIndent(3.14159625, "", " ", "myRootTag", "myElementTag")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println("f->x:\n", string(x))
|
||||
|
||||
s := MyStruct{"somevalue", 3.14159625}
|
||||
x, err = AnyXmlIndent(s, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println("s->x:\n", string(x))
|
||||
}
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
// bulk_test.go - uses Handler and Writer functions to process some streams as a demo.
|
||||
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBulkHeader(t *testing.T) {
|
||||
fmt.Println("\n---------------- bulk_test.go ...\n")
|
||||
}
|
||||
|
||||
var jsonWriter = new(bytes.Buffer)
|
||||
var xmlWriter = new(bytes.Buffer)
|
||||
|
||||
var jsonErrLog = new(bytes.Buffer)
|
||||
var xmlErrLog = new(bytes.Buffer)
|
||||
|
||||
func TestXmlReader(t *testing.T) {
|
||||
// create Reader for xmldata
|
||||
xmlReader := bytes.NewReader(xmldata)
|
||||
|
||||
// read XML from Readerand pass Map value with the raw XML to handler
|
||||
err := HandleXmlReader(xmlReader, bxmaphandler, bxerrhandler)
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
}
|
||||
|
||||
// get the JSON
|
||||
j := make([]byte, jsonWriter.Len())
|
||||
_, _ = jsonWriter.Read(j)
|
||||
|
||||
// get the errors
|
||||
e := make([]byte, xmlErrLog.Len())
|
||||
_, _ = xmlErrLog.Read(e)
|
||||
|
||||
// print the input
|
||||
fmt.Println("XmlReader, xmldata:\n", string(xmldata))
|
||||
// print the result
|
||||
fmt.Println("XmlReader, result :\n", string(j))
|
||||
// print the errors
|
||||
fmt.Println("XmlReader, errors :\n", string(e))
|
||||
}
|
||||
|
||||
func bxmaphandler(m Map) bool {
|
||||
j, err := m.JsonIndent("", " ", true)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
_, _ = jsonWriter.Write(j)
|
||||
// put in a NL to pretty up printing the Writer
|
||||
_, _ = jsonWriter.Write([]byte("\n"))
|
||||
return true
|
||||
}
|
||||
|
||||
func bxerrhandler(err error) bool {
|
||||
// write errors to file
|
||||
_, _ = xmlErrLog.Write([]byte(err.Error()))
|
||||
_, _ = xmlErrLog.Write([]byte("\n")) // pretty up
|
||||
return true
|
||||
}
|
||||
|
||||
func TestJsonReader(t *testing.T) {
|
||||
jsonReader := bytes.NewReader(jsondata)
|
||||
|
||||
// read all the JSON
|
||||
err := HandleJsonReader(jsonReader, bjmaphandler, bjerrhandler)
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
}
|
||||
|
||||
// get the XML
|
||||
x := make([]byte, xmlWriter.Len())
|
||||
_, _ = xmlWriter.Read(x)
|
||||
|
||||
// get the errors
|
||||
e := make([]byte, jsonErrLog.Len())
|
||||
_, _ = jsonErrLog.Read(e)
|
||||
|
||||
// print the input
|
||||
fmt.Println("JsonReader, jsondata:\n", string(jsondata))
|
||||
// print the result
|
||||
fmt.Println("JsonReader, result :\n", string(x))
|
||||
// print the errors
|
||||
fmt.Println("JsonReader, errors :\n", string(e))
|
||||
}
|
||||
|
||||
func bjmaphandler(m Map) bool {
|
||||
x, err := m.XmlIndent(" ", " ")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
_, _ = xmlWriter.Write(x)
|
||||
// put in a NL to pretty up printing the Writer
|
||||
_, _ = xmlWriter.Write([]byte("\n"))
|
||||
return true
|
||||
}
|
||||
|
||||
func bjerrhandler(err error) bool {
|
||||
// write errors to file
|
||||
_, _ = jsonErrLog.Write([]byte(err.Error()))
|
||||
_, _ = jsonErrLog.Write([]byte("\n")) // pretty up
|
||||
return true
|
||||
}
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
// bulk_test.go - uses Handler and Writer functions to process some streams as a demo.
|
||||
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBulkRawHeader(t *testing.T) {
|
||||
fmt.Println("\n---------------- bulkraw_test.go ...\n")
|
||||
}
|
||||
|
||||
// use data from bulk_test.go
|
||||
|
||||
var jsonWriterRaw = new(bytes.Buffer)
|
||||
var xmlWriterRaw = new(bytes.Buffer)
|
||||
|
||||
var jsonErrLogRaw = new(bytes.Buffer)
|
||||
var xmlErrLogRaw = new(bytes.Buffer)
|
||||
|
||||
func TestXmlReaderRaw(t *testing.T) {
|
||||
// create Reader for xmldata
|
||||
xmlReader := bytes.NewReader(xmldata)
|
||||
|
||||
// read XML from Reader and pass Map value with the raw XML to handler
|
||||
err := HandleXmlReaderRaw(xmlReader, bxmaphandlerRaw, bxerrhandlerRaw)
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
}
|
||||
|
||||
// get the JSON
|
||||
j := make([]byte, jsonWriterRaw.Len())
|
||||
_, _ = jsonWriterRaw.Read(j)
|
||||
|
||||
// get the errors
|
||||
e := make([]byte, xmlErrLogRaw.Len())
|
||||
_, _ = xmlErrLogRaw.Read(e)
|
||||
|
||||
// print the input
|
||||
fmt.Println("XmlReaderRaw, xmldata:\n", string(xmldata))
|
||||
// print the result
|
||||
fmt.Println("XmlReaderRaw, result :\n", string(j))
|
||||
// print the errors
|
||||
fmt.Println("XmlReaderRaw, errors :\n", string(e))
|
||||
}
|
||||
|
||||
func bxmaphandlerRaw(m Map, raw []byte) bool {
|
||||
j, err := m.JsonIndent("", " ", true)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
_, _ = jsonWriterRaw.Write(j)
|
||||
// put in a NL to pretty up printing the Writer
|
||||
_, _ = jsonWriterRaw.Write([]byte("\n"))
|
||||
return true
|
||||
}
|
||||
|
||||
func bxerrhandlerRaw(err error, raw []byte) bool {
|
||||
// write errors to file
|
||||
_, _ = xmlErrLogRaw.Write([]byte(err.Error()))
|
||||
_, _ = xmlErrLogRaw.Write([]byte("\n")) // pretty up
|
||||
_, _ = xmlErrLogRaw.Write(raw)
|
||||
_, _ = xmlErrLogRaw.Write([]byte("\n")) // pretty up
|
||||
return true
|
||||
}
|
||||
|
||||
func TestJsonReaderRaw(t *testing.T) {
|
||||
jsonReader := bytes.NewReader(jsondata)
|
||||
|
||||
// read all the JSON
|
||||
err := HandleJsonReaderRaw(jsonReader, bjmaphandlerRaw, bjerrhandlerRaw)
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
}
|
||||
|
||||
// get the XML
|
||||
x := make([]byte, xmlWriterRaw.Len())
|
||||
_, _ = xmlWriterRaw.Read(x)
|
||||
|
||||
// get the errors
|
||||
e := make([]byte, jsonErrLogRaw.Len())
|
||||
_, _ = jsonErrLogRaw.Read(e)
|
||||
|
||||
// print the input
|
||||
fmt.Println("JsonReaderRaw, jsondata:\n", string(jsondata))
|
||||
// print the result
|
||||
fmt.Println("JsonReaderRaw, result :\n", string(x))
|
||||
// print the errors
|
||||
fmt.Println("JsonReaderRaw, errors :\n", string(e))
|
||||
}
|
||||
|
||||
func bjmaphandlerRaw(m Map, raw []byte) bool {
|
||||
x, err := m.XmlIndent(" ", " ")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
_, _ = xmlWriterRaw.Write(x)
|
||||
// put in a NL to pretty up printing the Writer
|
||||
_, _ = xmlWriterRaw.Write([]byte("\n"))
|
||||
return true
|
||||
}
|
||||
|
||||
func bjerrhandlerRaw(err error, raw []byte) bool {
|
||||
// write errors to file
|
||||
_, _ = jsonErrLogRaw.Write([]byte(err.Error()))
|
||||
_, _ = jsonErrLogRaw.Write([]byte("\n")) // pretty up, Error() from json.Unmarshal !NL
|
||||
_, _ = jsonErrLogRaw.Write(raw)
|
||||
_, _ = jsonErrLogRaw.Write([]byte("\n")) // pretty up
|
||||
return true
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package mxj
|
||||
|
||||
var xmldata = []byte(`
|
||||
<book>
|
||||
<author>William H. Gaddis</author>
|
||||
<title>The Recognitions</title>
|
||||
<review>One of the seminal American novels of the 20th century.</review>
|
||||
</book>
|
||||
<book>
|
||||
<author>William H. Gaddis</author>
|
||||
<title>JR</title>
|
||||
<review>Won the National Book Award.</end_tag_error>
|
||||
</book>
|
||||
<book>
|
||||
<author>Austin Tappan Wright</author>
|
||||
<title>Islandia</title>
|
||||
<review>An example of earlier 20th century American utopian fiction.</review>
|
||||
</book>
|
||||
<book>
|
||||
<author>John Hawkes</author>
|
||||
<title>The Beetle Leg</title>
|
||||
<review>A lyrical novel about the construction of Ft. Peck Dam in Montana.</review>
|
||||
</book>
|
||||
<book>
|
||||
<author>
|
||||
<first_name>T.E.</first_name>
|
||||
<last_name>Porter</last_name>
|
||||
</author>
|
||||
<title>King's Day</title>
|
||||
<review>A magical novella.</review>
|
||||
</book>`)
|
||||
|
||||
var jsondata = []byte(`
|
||||
{"book":{"author":"William H. Gaddis","review":"One of the great seminal American novels of the 20th century.","title":"The Recognitions"}}
|
||||
{"book":{"author":"Austin Tappan Wright","review":"An example of earlier 20th century American utopian fiction.","title":"Islandia"}}
|
||||
{"book":{"author":"John Hawkes","review":"A lyrical novel about the construction of Ft. Peck Dam in Montana.","title":"The Beetle Leg"}}
|
||||
{"book":{"author":{"first_name":"T.E.","last_name":"Porter"},"review":"A magical novella.","title":"King's Day"}}
|
||||
{ "here":"we", "put":"in", "an":error }`)
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
// mxj - A collection of map[string]interface{} and associated XML and JSON utilities.
|
||||
// Copyright 2012-2014 Charles Banning. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file
|
||||
|
||||
/*
|
||||
Marshal/Unmarshal XML to/from JSON and map[string]interface{} values, and extract/modify values from maps by key or key-path, including wildcards.
|
||||
|
||||
mxj supplants the legacy x2j and j2x packages. If you want the old syntax, use mxj/x2j or mxj/j2x packages.
|
||||
|
||||
Note: this library was designed for processing ad hoc anonymous messages. Bulk processing large data sets may be much more efficiently performed using the encoding/xml or encoding/json packages from Go's standard library directly.
|
||||
|
||||
Note:
|
||||
2014-08-02: AnyXml() and AnyXmlIndent() will try to marshal arbitrary values to XML.
|
||||
|
||||
SUMMARY
|
||||
|
||||
type Map map[string]interface{}
|
||||
|
||||
Create a Map value, 'm', from any map[string]interface{} value, 'v':
|
||||
m := Map(v)
|
||||
|
||||
Unmarshal / marshal XML as a Map value, 'm':
|
||||
m, err := NewMapXml(xmlValue) // unmarshal
|
||||
xmlValue, err := m.Xml() // marshal
|
||||
|
||||
Unmarshal XML from an io.Reader as a Map value, 'm':
|
||||
m, err := NewMapReader(xmlReader) // repeated calls, as with an os.File Reader, will process stream
|
||||
m, raw, err := NewMapReaderRaw(xmlReader) // 'raw' is the raw XML that was decoded
|
||||
|
||||
Marshal Map value, 'm', to an XML Writer (io.Writer):
|
||||
err := m.XmlWriter(xmlWriter)
|
||||
raw, err := m.XmlWriterRaw(xmlWriter) // 'raw' is the raw XML that was written on xmlWriter
|
||||
|
||||
Also, for prettified output:
|
||||
xmlValue, err := m.XmlIndent(prefix, indent, ...)
|
||||
err := m.XmlIndentWriter(xmlWriter, prefix, indent, ...)
|
||||
raw, err := m.XmlIndentWriterRaw(xmlWriter, prefix, indent, ...)
|
||||
|
||||
Bulk process XML with error handling (note: handlers must return a boolean value):
|
||||
err := HandleXmlReader(xmlReader, mapHandler(Map), errHandler(error))
|
||||
err := HandleXmlReaderRaw(xmlReader, mapHandler(Map, []byte), errHandler(error, []byte))
|
||||
|
||||
Converting XML to JSON: see Examples for NewMapXml and HandleXmlReader.
|
||||
|
||||
There are comparable functions and methods for JSON processing.
|
||||
|
||||
Arbitrary structure values can be decoded to / encoded from Map values:
|
||||
m, err := NewMapStruct(structVal)
|
||||
err := m.Struct(structPointer)
|
||||
|
||||
To work with XML tag values, JSON or Map key values or structure field values, decode the XML, JSON
|
||||
or structure to a Map value, 'm', or cast a map[string]interface{} value to a Map value, 'm', then:
|
||||
paths := m.PathsForKey(key)
|
||||
path := m.PathForKeyShortest(key)
|
||||
values, err := m.ValuesForKey(key, subkeys)
|
||||
values, err := m.ValuesForPath(path, subkeys) // 'path' can be dot-notation with wildcards and indexed arrays.
|
||||
count, err := m.UpdateValuesForPath(newVal, path, subkeys)
|
||||
|
||||
Get everything at once, irrespective of path depth:
|
||||
leafnodes := m.LeafNodes()
|
||||
leafvalues := m.LeafValues()
|
||||
|
||||
A new Map with whatever keys are desired can be created from the current Map and then encoded in XML
|
||||
or JSON. (Note: keys can use dot-notation. 'oldKey' can also use wildcards and indexed arrays.)
|
||||
newMap := m.NewMap("oldKey_1:newKey_1", "oldKey_2:newKey_2", ..., "oldKey_N:newKey_N")
|
||||
newXml := newMap.Xml() // for example
|
||||
newJson := newMap.Json() // ditto
|
||||
|
||||
XML PARSING CONVENTIONS
|
||||
|
||||
- Attributes are parsed to map[string]interface{} values by prefixing a hyphen, '-',
|
||||
to the attribute label. (PrependAttrWithHyphen(false) will override this.)
|
||||
- If the element is a simple element and has attributes, the element value
|
||||
is given the key '#text' for its map[string]interface{} representation.
|
||||
|
||||
XML ENCODING CONVENTIONS
|
||||
|
||||
- 'nil' Map values, which may represent 'null' JSON values, are encoded as "<tag/>".
|
||||
NOTE: the operation is not symmetric as "<tag/>" elements are decoded as 'tag:""' Map values,
|
||||
which, then, encode in JSON as '"tag":""' values..
|
||||
|
||||
*/
|
||||
package mxj
|
||||
-344
@@ -1,344 +0,0 @@
|
||||
// note - "// Output:" is a key for "go test" to match function ouput with the lines that follow.
|
||||
// It is also use by "godoc" to build the Output block of the function / method documentation.
|
||||
// To skip processing Example* functions, use: go test -run "Test*"
|
||||
// or make sure example function output matches // Output: documentation EXACTLY.
|
||||
|
||||
package mxj_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"io"
|
||||
)
|
||||
|
||||
func ExampleHandleXmlReader() {
|
||||
/*
|
||||
Bulk processing XML to JSON seems to be a common requirement.
|
||||
See: bulk_test.go for working example.
|
||||
Run "go test" in package directory then scroll back to find output.
|
||||
|
||||
The logic is as follows.
|
||||
|
||||
// need somewhere to write the JSON.
|
||||
var jsonWriter io.Writer
|
||||
|
||||
// probably want to log any errors in reading the XML stream
|
||||
var xmlErrLogger io.Writer
|
||||
|
||||
// func to handle Map value from XML Reader
|
||||
func maphandler(m mxj.Map) bool {
|
||||
// marshal Map as JSON
|
||||
jsonVal, err := m.Json()
|
||||
if err != nil {
|
||||
// log error
|
||||
return false // stops further processing of XML Reader
|
||||
}
|
||||
|
||||
// write JSON somewhere
|
||||
_, err = jsonWriter.Write(jsonVal)
|
||||
if err != nil {
|
||||
// log error
|
||||
return false // stops further processing of XML Reader
|
||||
}
|
||||
|
||||
// continue - get next XML from Reader
|
||||
return true
|
||||
}
|
||||
|
||||
// func to handle error from unmarshaling XML Reader
|
||||
func errhandler(errVal error) bool {
|
||||
// log error somewhere
|
||||
_, err := xmlErrLogger.Write([]byte(errVal.Error()))
|
||||
if err != nil {
|
||||
// log error
|
||||
return false // stops further processing of XML Reader
|
||||
}
|
||||
|
||||
// continue processing
|
||||
return true
|
||||
}
|
||||
|
||||
// func that starts bulk processing of the XML
|
||||
...
|
||||
// set up io.Reader for XML data - perhaps an os.File
|
||||
...
|
||||
err := mxj.HandleXmlReader(xmlReader, maphandler, errhandler)
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
...
|
||||
*/
|
||||
}
|
||||
|
||||
func ExampleHandleXmlReaderRaw() {
|
||||
/*
|
||||
See: bulkraw_test.go for working example.
|
||||
Run "go test" in package directory then scroll back to find output.
|
||||
|
||||
Basic logic for bulk XML to JSON processing is in HandleXmlReader example;
|
||||
the only major difference is in handler function signatures so they are passed
|
||||
the raw XML. (Read documentation on NewXmlReader regarding performance.)
|
||||
*/
|
||||
}
|
||||
|
||||
func ExampleHandleJsonReader() {
|
||||
/*
|
||||
See: bulk_test.go for working example.
|
||||
Run "go test" in package directory then scroll back to find output.
|
||||
|
||||
Basic logic for bulk JSON to XML processing is similar to that for
|
||||
bulk XML to JSON processing as outlined in the HandleXmlReader example.
|
||||
The test case is also a good example.
|
||||
*/
|
||||
}
|
||||
|
||||
func ExampleHandleJsonReaderRaw() {
|
||||
/*
|
||||
See: bulkraw_test.go for working example.
|
||||
Run "go test" in package directory then scroll back to find output.
|
||||
|
||||
Basic logic for bulk JSON to XML processing is similar to that for
|
||||
bulk XML to JSON processing as outlined in the HandleXmlReader example.
|
||||
The test case is also a good example.
|
||||
*/
|
||||
}
|
||||
|
||||
/*
|
||||
func ExampleNewMapXmlReaderRaw() {
|
||||
// in an http.Handler
|
||||
|
||||
mapVal, raw, err := mxj.NewMapXmlReader(req.Body)
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
logger.Print(string(*raw))
|
||||
// do something with mapVal
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
func ExampleNewMapStruct() {
|
||||
type str struct {
|
||||
IntVal int `json:"int"`
|
||||
StrVal string `json:"str"`
|
||||
FloatVal float64 `json:"float"`
|
||||
BoolVal bool `json:"bool"`
|
||||
private string
|
||||
}
|
||||
strVal := str{IntVal: 4, StrVal: "now's the time", FloatVal: 3.14159, BoolVal: true, private: "Skies are blue"}
|
||||
|
||||
mapVal, merr := mxj.NewMapStruct(strVal)
|
||||
if merr != nil {
|
||||
// handle error
|
||||
}
|
||||
|
||||
fmt.Printf("strVal: %#v\n", strVal)
|
||||
fmt.Printf("mapVal: %#v\n", mapVal)
|
||||
// Note: example output is conformed to pass "go test". "mxj_test" is example_test.go package name.
|
||||
|
||||
// Output:
|
||||
// strVal: mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"}
|
||||
// mapVal: mxj.Map{"int":4, "str":"now's the time", "float":3.14159, "bool":true}
|
||||
}
|
||||
|
||||
func ExampleMap_Struct() {
|
||||
type str struct {
|
||||
IntVal int `json:"int"`
|
||||
StrVal string `json:"str"`
|
||||
FloatVal float64 `json:"float"`
|
||||
BoolVal bool `json:"bool"`
|
||||
private string
|
||||
}
|
||||
|
||||
mapVal := mxj.Map{"int": 4, "str": "now's the time", "float": 3.14159, "bool": true, "private": "Somewhere over the rainbow"}
|
||||
|
||||
var strVal str
|
||||
mverr := mapVal.Struct(&strVal)
|
||||
if mverr != nil {
|
||||
// handle error
|
||||
}
|
||||
|
||||
fmt.Printf("mapVal: %#v\n", mapVal)
|
||||
fmt.Printf("strVal: %#v\n", strVal)
|
||||
// Note: example output is conformed to pass "go test". "mxj_test" is example_test.go package name.
|
||||
|
||||
// Output:
|
||||
// mapVal: mxj.Map{"int":4, "str":"now's the time", "float":3.14159, "bool":true, "private":"Somewhere over the rainbow"}
|
||||
// strVal: mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:""}
|
||||
}
|
||||
|
||||
func ExampleMap_ValuesForKeyPath() {
|
||||
// a snippet from examples/gonuts1.go
|
||||
// How to compensate for irregular tag labels in data.
|
||||
// Need to extract from an XML stream the values for "netid" and "idnet".
|
||||
// Solution: use a wildcard path "data.*" to anonymize the "netid" and "idnet" tags.
|
||||
|
||||
var msg1 = []byte(`
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<data>
|
||||
<netid>
|
||||
<disable>no</disable>
|
||||
<text1>default:text</text1>
|
||||
<word1>default:word</word1>
|
||||
</netid>
|
||||
</data>
|
||||
`)
|
||||
|
||||
var msg2 = []byte(`
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<data>
|
||||
<idnet>
|
||||
<disable>yes</disable>
|
||||
<text1>default:text</text1>
|
||||
<word1>default:word</word1>
|
||||
</idnet>
|
||||
</data>
|
||||
`)
|
||||
|
||||
// let's create a message stream
|
||||
buf := new(bytes.Buffer)
|
||||
// load a couple of messages into it
|
||||
_, _ = buf.Write(msg1)
|
||||
_, _ = buf.Write(msg2)
|
||||
|
||||
n := 0
|
||||
for {
|
||||
n++
|
||||
// Read the stream as Map values - quit on io.EOF.
|
||||
// Get the raw XML as well as the Map value.
|
||||
m, merr := mxj.NewMapXmlReader(buf)
|
||||
if merr != nil && merr != io.EOF {
|
||||
// handle error - for demo we just print it and continue
|
||||
fmt.Printf("msg: %d - merr: %s\n", n, merr.Error())
|
||||
continue
|
||||
} else if merr == io.EOF {
|
||||
break
|
||||
}
|
||||
|
||||
// get the values for "netid" or "idnet" key using path == "data.*"
|
||||
values, _ := m.ValuesForPath("data.*")
|
||||
fmt.Println("\nmsg:", n, "> path == data.* - got array of values, len:", len(values))
|
||||
for i, val := range values {
|
||||
fmt.Println("ValuesForPath result array member -", i, ":", val)
|
||||
fmt.Println(" k:v pairs for array member:", i)
|
||||
for key, val := range val.(map[string]interface{}) {
|
||||
// You'd probably want to process the value, as appropriate.
|
||||
// Here we just print it out.
|
||||
fmt.Println("\t\t", key, ":", val)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Output:
|
||||
// msg: 1 > path == data.* - got array of values, len: 1
|
||||
// ValuesForPath result array member - 0 : map[disable:no text1:default:text word1:default:word]
|
||||
// k:v pairs for array member: 0
|
||||
// disable : no
|
||||
// text1 : default:text
|
||||
// word1 : default:word
|
||||
//
|
||||
// msg: 2 > path == data.* - got array of values, len: 1
|
||||
// ValuesForPath result array member - 0 : map[disable:yes text1:default:text word1:default:word]
|
||||
// k:v pairs for array member: 0
|
||||
// disable : yes
|
||||
// text1 : default:text
|
||||
// word1 : default:word
|
||||
}
|
||||
|
||||
func ExampleMap_UpdateValuesForPath() {
|
||||
/*
|
||||
|
||||
var biblioDoc = []byte(`
|
||||
<biblio>
|
||||
<author>
|
||||
<name>William Gaddis</name>
|
||||
<books>
|
||||
<book>
|
||||
<title>The Recognitions</title>
|
||||
<date>1955</date>
|
||||
<review>A novel that changed the face of American literature.</review>
|
||||
</book>
|
||||
<book>
|
||||
<title>JR</title>
|
||||
<date>1975</date>
|
||||
<review>Winner of National Book Award for Fiction.</review>
|
||||
</book>
|
||||
</books>
|
||||
</author>
|
||||
</biblio>`)
|
||||
|
||||
...
|
||||
m, merr := mxj.NewMapXml(biblioDoc)
|
||||
if merr != nil {
|
||||
// handle error
|
||||
}
|
||||
|
||||
// change 'review' for a book
|
||||
count, err := m.UpdateValuesForPath("review:National Book Award winner." "*.*.*.*", "title:JR")
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
...
|
||||
|
||||
// change 'date' value from string type to float64 type
|
||||
// Note: the following is equivalent to m, merr := NewMapXml(biblioDoc, mxj.Cast).
|
||||
path := m.PathForKeyShortest("date")
|
||||
v, err := m.ValuesForPath(path)
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
var total int
|
||||
for _, vv := range v {
|
||||
oldVal := "date:" + vv.(string)
|
||||
newVal := "date:" + vv.(string) + ":num"
|
||||
n, err := m.UpdateValuesForPath(newVal, path, oldVal)
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
total += n
|
||||
}
|
||||
...
|
||||
*/
|
||||
}
|
||||
|
||||
func ExampleMap_Copy() {
|
||||
// Hand-crafted Map values that include structures do NOT Copy() as expected,
|
||||
// since to simulate a deep copy the original Map value is JSON encoded then decoded.
|
||||
|
||||
type str struct {
|
||||
IntVal int `json:"int"`
|
||||
StrVal string `json:"str"`
|
||||
FloatVal float64 `json:"float"`
|
||||
BoolVal bool `json:"bool"`
|
||||
private string
|
||||
}
|
||||
s := str{IntVal: 4, StrVal: "now's the time", FloatVal: 3.14159, BoolVal: true, private: "Skies are blue"}
|
||||
m := make(map[string]interface{}, 0)
|
||||
m["struct"] = interface{}(s)
|
||||
m["struct_ptr"] = interface{}(&s)
|
||||
m["misc"] = interface{}(`Now is the time`)
|
||||
|
||||
mv := mxj.Map(m)
|
||||
cp, _ := mv.Copy()
|
||||
|
||||
fmt.Printf("mv:%s\n", mv.StringIndent(2))
|
||||
fmt.Printf("cp:%s\n", cp.StringIndent(2))
|
||||
|
||||
// Output:
|
||||
// mv:
|
||||
// struct :[unknown] mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"}
|
||||
// struct_ptr :[unknown] &mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"}
|
||||
// misc :[string] Now is the time
|
||||
// cp:
|
||||
// misc :[string] Now is the time
|
||||
// struct :
|
||||
// int :[float64] 4.00e+00
|
||||
// str :[string] now's the time
|
||||
// float :[float64] 3.14e+00
|
||||
// bool :[bool] true
|
||||
// struct_ptr :
|
||||
// int :[float64] 4.00e+00
|
||||
// str :[string] now's the time
|
||||
// float :[float64] 3.14e+00
|
||||
// bool :[bool] true
|
||||
}
|
||||
-124
@@ -1,124 +0,0 @@
|
||||
Examples of using ValuesFromTagPath().
|
||||
|
||||
A number of interesting examples have shown up in the gonuts discussion group
|
||||
that could be handled - after a fashion - using the ValuesFromTagPath() function.
|
||||
|
||||
gonuts1.go -
|
||||
|
||||
Here we see that the message stream has a problem with multiple tag spellings,
|
||||
though the message structure remains constant. In this example we 'anonymize'
|
||||
the tag for the variant spellings.
|
||||
values := m.ValuesForPath("data.*)
|
||||
where '*' is any possible spelling - "netid" or "idnet"
|
||||
and the result is a list with 1 member of map[string]interface{} type.
|
||||
|
||||
Once we've retrieved the Map, we can parse it using the known keys - "disable",
|
||||
"text1" and "word1".
|
||||
|
||||
|
||||
gonuts1a.go - (03-mar-14)
|
||||
|
||||
Here we just permute the tag labels using m.NewMap() to make all the messages
|
||||
consistent. Then they can be decoded into a single structure definition.
|
||||
|
||||
|
||||
gonuts2.go -
|
||||
|
||||
This is an interesting case where there was a need to handle messages with lists
|
||||
of "ClaimStatusCodeRecord" entries as well as messages with NONE. (Here we see
|
||||
some of the vagaries of dealing with mixed messages that are verging on becoming
|
||||
anonymous.)
|
||||
|
||||
msg1 - the message with two ClaimStatusCodeRecord entries
|
||||
msg2 - the message with one ClaimStatusCodeRecord entry
|
||||
msg3 - the message with NO ClaimStatusCodeRecord entries
|
||||
|
||||
ValuesForPath options:
|
||||
|
||||
path == "Envelope.Body.GetClaimStatusCodesResponse.GetClaimStatusCodesResult.ClaimStatusCodeRecord"
|
||||
for msg == msg1:
|
||||
returns: a list - []interface{} - with two values of map[string]interface{} type
|
||||
for msg == msg2:
|
||||
returns: a list - []interface{} - with one map[string]interface{} type
|
||||
for msg == msg3:
|
||||
returns 'nil' - no values
|
||||
|
||||
path == "*.*.*.*.*"
|
||||
for msg == msg1:
|
||||
returns: a list - []interface{} - with two values of map[string]interface{} type
|
||||
|
||||
path == "*.*.*.*.*.Description
|
||||
for msg == msg1:
|
||||
returns: a list - []interface{} - with two values of string type, the individual
|
||||
values from parsing the two map[string]interface{} values where key=="Description"
|
||||
|
||||
path == "*.*.*.*.*.*"
|
||||
for msg == msg1:
|
||||
returns: a list - []interface{} - with six values of string type, the individual
|
||||
values from parsing all keys in the two map[string]interface{} values
|
||||
|
||||
Think of the wildcard character "*" as anonymizing the tag in the position of the path where
|
||||
it occurs. The books.go example has a range of use cases.
|
||||
|
||||
|
||||
gonuts3.go -
|
||||
|
||||
Uses the ValuesForKey method to extract a list of image "src" file names that are encoded as
|
||||
attribute values.
|
||||
|
||||
|
||||
gonuts4.go -
|
||||
|
||||
Here we use the ValuesForPath to extract attribute values for country names. The attribute
|
||||
is included in the 'path' argument by prepending it with a hyphen: ""doc.some_tag.geoInfo.country.-name".
|
||||
|
||||
|
||||
gonuts5.go (10-mar-14) -
|
||||
|
||||
Extract a node of values using ValuesForPath based on name="list3-1-1-1". Then get the values
|
||||
for the 'int' entries based on attribute 'name' values - mv.ValuesForKey("int", "-name:"+n).
|
||||
|
||||
gonuts5a.go (10-mar-14) -
|
||||
|
||||
Extract a node of values using ValuesForPath based on name="list3-1-1-1". Then get the values
|
||||
for the 'int' entries based on attribute 'name' values - mv.ValuesForKey("*", "-name:"+n).
|
||||
(Same as gonuts5.go but with wildcarded key value, since we're matching elements on subkey.)
|
||||
|
||||
|
||||
EAT YOUR OWN DOG FOOD ...
|
||||
|
||||
I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an
|
||||
application that had 355,100 lines of code in 211 packages into CSV data sets. The report
|
||||
included application-, package-, class- and method-level metrics reported in an element,
|
||||
"Value", with varying attributes.
|
||||
<Value value=""/>
|
||||
<Value name="" package="" value=""/>
|
||||
<Value name="" source="" package="" value=""/>
|
||||
<Value name="" source="" package="" value="" inrange=""/>
|
||||
|
||||
In addition, the metrics were reported with two different "Metric" compound elements:
|
||||
<Metrics>
|
||||
<Metric id="" description="">
|
||||
<Values>
|
||||
<Value.../>
|
||||
...
|
||||
</Values>
|
||||
</Metric>
|
||||
...
|
||||
<Metric id="" description="">
|
||||
<Value.../>
|
||||
</Metric>
|
||||
...
|
||||
</Metrics>
|
||||
|
||||
Using the mxj package seemed a more straightforward approach than using Go vernacular
|
||||
and the standard xml package. I wrote the program getmetrics.go to do this. Here are
|
||||
three version to illustrate using
|
||||
getmetrics1.go - pass os.File handle for metrics_data.xml to NewMapXmlReader.
|
||||
getmetrics2.go - load metrics_data.xml into an in-memory buffer, then pass it to NewMapXml.
|
||||
getmetrics3.go - demonstrates overhead of extracting the raw XML while decoding with NewMapXmlReaderRaw.
|
||||
|
||||
To run example getmetrics1.go, extract a 120,000+ row data set from metrics_data.zip. Then:
|
||||
go run getmetrics1.go -file=metrics_data.xml
|
||||
|
||||
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
// Note: this illustrates ValuesForKey() and ValuesForPath() methods
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"log"
|
||||
)
|
||||
|
||||
var xmldata = []byte(`
|
||||
<books>
|
||||
<book seq="1">
|
||||
<author>William H. Gaddis</author>
|
||||
<title>The Recognitions</title>
|
||||
<review>One of the great seminal American novels of the 20th century.</review>
|
||||
</book>
|
||||
<book seq="2">
|
||||
<author>Austin Tappan Wright</author>
|
||||
<title>Islandia</title>
|
||||
<review>An example of earlier 20th century American utopian fiction.</review>
|
||||
</book>
|
||||
<book seq="3">
|
||||
<author>John Hawkes</author>
|
||||
<title>The Beetle Leg</title>
|
||||
<review>A lyrical novel about the construction of Ft. Peck Dam in Montana.</review>
|
||||
</book>
|
||||
<book seq="4">
|
||||
<author>T.E. Porter</author>
|
||||
<title>King's Day</title>
|
||||
<review>A magical novella.</review>
|
||||
</book>
|
||||
</books>
|
||||
`)
|
||||
|
||||
func main() {
|
||||
fmt.Println(string(xmldata))
|
||||
|
||||
m, err := mxj.NewMapXml(xmldata)
|
||||
if err != nil {
|
||||
log.Fatal("err:", err.Error())
|
||||
}
|
||||
|
||||
v, _ := m.ValuesForKey("books")
|
||||
fmt.Println("path: books; len(v):", len(v))
|
||||
fmt.Printf("\t%+v\n", v)
|
||||
|
||||
v, _ = m.ValuesForPath("books.book")
|
||||
fmt.Println("path: books.book; len(v):", len(v))
|
||||
for _, vv := range v {
|
||||
fmt.Printf("\t%+v\n", vv)
|
||||
}
|
||||
|
||||
v, _ = m.ValuesForPath("books.*")
|
||||
fmt.Println("path: books.*; len(v):", len(v))
|
||||
for _, vv := range v {
|
||||
fmt.Printf("\t%+v\n", vv)
|
||||
}
|
||||
|
||||
v, _ = m.ValuesForPath("books.*.title")
|
||||
fmt.Println("path: books.*.title len(v):", len(v))
|
||||
for _, vv := range v {
|
||||
fmt.Printf("\t%+v\n", vv)
|
||||
}
|
||||
|
||||
v, _ = m.ValuesForPath("books.*.*")
|
||||
fmt.Println("path: books.*.*; len(v):", len(v))
|
||||
for _, vv := range v {
|
||||
fmt.Printf("\t%+v\n", vv)
|
||||
}
|
||||
}
|
||||
-176
@@ -1,176 +0,0 @@
|
||||
// getmetrics1.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric
|
||||
// Uses NewMapXmlReader on os.File without copying the raw XML into a buffer while decoding..
|
||||
// Shows no significant overhead for not first buffering large XML file as in getmetrics2.go.
|
||||
|
||||
/*
|
||||
I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an
|
||||
application that had 355,100 lines of code in 211 packages into CSV data sets. The report
|
||||
included application-, package-, class- and method-level metrics reported in an element,
|
||||
"Value", with varying attributes.
|
||||
<Value value=""/>
|
||||
<Value name="" package="" value=""/>
|
||||
<Value name="" source="" package="" value=""/>
|
||||
<Value name="" source="" package="" value="" inrange=""/>
|
||||
|
||||
In addition, the metrics were reported with two different "Metric" compound elements:
|
||||
<Metrics>
|
||||
<Metric id="" description="">
|
||||
<Values>
|
||||
<Value.../>
|
||||
...
|
||||
</Values>
|
||||
</Metric>
|
||||
...
|
||||
<Metric id="" description="">
|
||||
<Value.../>
|
||||
</Metric>
|
||||
...
|
||||
</Metrics>
|
||||
|
||||
To run this example, extract the metrics_data.xml file from metrics_data.zip, then:
|
||||
> go run getmetrics1 -file=metrics_data.xml
|
||||
|
||||
The output will be a set of "csv" files.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var file string
|
||||
flag.StringVar(&file, "file", "", "file to process")
|
||||
flag.Parse()
|
||||
|
||||
fh, fherr := os.Open(file)
|
||||
if fherr != nil {
|
||||
fmt.Println("fherr:", fherr.Error())
|
||||
return
|
||||
}
|
||||
defer fh.Close()
|
||||
fmt.Println(time.Now().String(), "... File Opened:", file)
|
||||
|
||||
/*
|
||||
// Get the XML data set from the file.
|
||||
fs, _ := fh.Stat()
|
||||
xmldata := make([]byte, fs.Size())
|
||||
n, frerr := fh.Read(xmldata)
|
||||
if frerr != nil {
|
||||
fmt.Println("frerr:", frerr.Error())
|
||||
return
|
||||
}
|
||||
if int64(n) != fs.Size() {
|
||||
fmt.Println("n:", n, "fs.Size():", fs.Size())
|
||||
return
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... File Read - size:", fs.Size())
|
||||
|
||||
// load XML into a Map value
|
||||
m, merr := mxj.NewMapXml(xmldata)
|
||||
*/
|
||||
// Consume the file using os.File Reader.
|
||||
// Note: there is a single record with root tag of "Metrics".
|
||||
m, merr := mxj.NewMapXmlReader(fh)
|
||||
if merr != nil {
|
||||
log.Fatal("merr:", merr.Error())
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... XML Unmarshaled - len:", len(m))
|
||||
|
||||
// Get just the key values of interest.
|
||||
// Could also use m.ValuesForKey("Metric"),
|
||||
// since there's just the one path.
|
||||
metricVals, err := m.ValuesForPath("Metrics.Metric")
|
||||
if err != nil {
|
||||
log.Fatal("err:", err.Error())
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... ValuesFromKeyPath - len:", len(metricVals))
|
||||
|
||||
// now just manipulate Map entries returned as []interface{} array.
|
||||
for _, v := range metricVals {
|
||||
aMetricVal := v.(map[string]interface{})
|
||||
|
||||
// create file to hold csv data sets
|
||||
id := aMetricVal["-id"].(string)
|
||||
desc := aMetricVal["-description"].(string)
|
||||
mf, mferr := os.OpenFile(id+".csv", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
|
||||
if mferr != nil {
|
||||
fmt.Println("mferr:", mferr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Print(time.Now().String(), " id: ", id, " desc: ", desc)
|
||||
mf.WriteString(id + "," + desc + "\n")
|
||||
|
||||
// rescan looking for keys with data: Values or Value
|
||||
for key, val := range aMetricVal {
|
||||
switch key {
|
||||
case "Values":
|
||||
// extract the list of "Value" from map
|
||||
values := val.(map[string]interface{})["Value"].([]interface{})
|
||||
fmt.Println(" len(Values):", len(values))
|
||||
|
||||
// first line in file is the metric label values (keys)
|
||||
var gotKeys bool
|
||||
for _, vval := range values {
|
||||
valueEntry := vval.(map[string]interface{})
|
||||
|
||||
// no guarantee that range on map will follow any sequence
|
||||
lv := len(valueEntry)
|
||||
type ev [2]string
|
||||
list := make([]ev, lv)
|
||||
var i int
|
||||
for k, v := range valueEntry {
|
||||
list[i][0] = k
|
||||
list[i][1] = v.(string)
|
||||
i++
|
||||
}
|
||||
|
||||
// extract keys as column header on first pass
|
||||
if !gotKeys {
|
||||
// print out the keys
|
||||
var gotFirstKey bool
|
||||
// for kk, _ := range valueEntry {
|
||||
for i := 0; i < lv; i++ {
|
||||
if gotFirstKey {
|
||||
mf.WriteString(",")
|
||||
} else {
|
||||
gotFirstKey = true
|
||||
}
|
||||
// strip prepended hyphen
|
||||
mf.WriteString((list[i][0])[1:])
|
||||
}
|
||||
mf.WriteString("\n")
|
||||
gotKeys = true
|
||||
}
|
||||
|
||||
// print out values
|
||||
var gotFirstVal bool
|
||||
// for _, vv := range valueEntry {
|
||||
for i := 0; i < lv; i++ {
|
||||
if gotFirstVal {
|
||||
mf.WriteString(",")
|
||||
} else {
|
||||
gotFirstVal = true
|
||||
}
|
||||
mf.WriteString(list[i][1])
|
||||
}
|
||||
|
||||
// terminate row of data
|
||||
mf.WriteString("\n")
|
||||
}
|
||||
case "Value":
|
||||
vv := val.(map[string]interface{})
|
||||
fmt.Println(" len(Value):", len(vv))
|
||||
mf.WriteString("value\n" + vv["-value"].(string) + "\n")
|
||||
}
|
||||
}
|
||||
mf.Close()
|
||||
}
|
||||
}
|
||||
-173
@@ -1,173 +0,0 @@
|
||||
// getmetrics2.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric
|
||||
// Uses an in-memory buffer for the XML data and direct XML decoding of the buffer into a Map.
|
||||
// Not significantly faster than getmetrics1.go that uses an io.Reader (os.File) to directly
|
||||
// decode the XML from the file.
|
||||
|
||||
/*
|
||||
I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an
|
||||
application that had 355,100 lines of code in 211 packages into CSV data sets. The report
|
||||
included application-, package-, class- and method-level metrics reported in an element,
|
||||
"Value", with varying attributes.
|
||||
<Value value=""/>
|
||||
<Value name="" package="" value=""/>
|
||||
<Value name="" source="" package="" value=""/>
|
||||
<Value name="" source="" package="" value="" inrange=""/>
|
||||
|
||||
In addition, the metrics were reported with two different "Metric" compound elements:
|
||||
<Metrics>
|
||||
<Metric id="" description="">
|
||||
<Values>
|
||||
<Value.../>
|
||||
...
|
||||
</Values>
|
||||
</Metric>
|
||||
...
|
||||
<Metric id="" description="">
|
||||
<Value.../>
|
||||
</Metric>
|
||||
...
|
||||
</Metrics>
|
||||
|
||||
To run this example, extract the metrics_data.xml file from metrics_data.zip, then:
|
||||
> go run getmetrics -file=metrics_data.xml
|
||||
|
||||
The output will be a set of "csv" files.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var file string
|
||||
flag.StringVar(&file, "file", "", "file to process")
|
||||
flag.Parse()
|
||||
|
||||
fh, fherr := os.Open(file)
|
||||
if fherr != nil {
|
||||
fmt.Println("fherr:", fherr.Error())
|
||||
return
|
||||
}
|
||||
defer fh.Close()
|
||||
fmt.Println(time.Now().String(), "... File Opened:", file)
|
||||
|
||||
// Get the XML data set from the file.
|
||||
fs, _ := fh.Stat()
|
||||
xmldata := make([]byte, fs.Size())
|
||||
n, frerr := fh.Read(xmldata)
|
||||
if frerr != nil {
|
||||
fmt.Println("frerr:", frerr.Error())
|
||||
return
|
||||
}
|
||||
if int64(n) != fs.Size() {
|
||||
fmt.Println("n:", n, "fs.Size():", fs.Size())
|
||||
return
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... File Read - size:", fs.Size())
|
||||
|
||||
// load XML into a Map value
|
||||
// Note: there is a single record with root tag of "Metrics".
|
||||
m, merr := mxj.NewMapXml(xmldata)
|
||||
if merr != nil {
|
||||
log.Fatal("merr:", merr.Error())
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... XML Unmarshaled - len:", len(m))
|
||||
|
||||
// Get just the key values of interest.
|
||||
// Could also use m.ValuesForKey("Metric"),
|
||||
// since there's just the one path.
|
||||
metricVals, err := m.ValuesForPath("Metrics.Metric")
|
||||
if err != nil {
|
||||
log.Fatal("err:", err.Error())
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... ValuesFromKeyPath - len:", len(metricVals))
|
||||
|
||||
// now just manipulate Map entries returned as []interface{} array.
|
||||
for _, v := range metricVals {
|
||||
aMetricVal := v.(map[string]interface{})
|
||||
|
||||
// create file to hold csv data sets
|
||||
id := aMetricVal["-id"].(string)
|
||||
desc := aMetricVal["-description"].(string)
|
||||
mf, mferr := os.OpenFile(id+".csv", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
|
||||
if mferr != nil {
|
||||
fmt.Println("mferr:", mferr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Print(time.Now().String(), " id: ", id, " desc: ", desc)
|
||||
mf.WriteString(id + "," + desc + "\n")
|
||||
|
||||
// rescan looking for keys with data: Values or Value
|
||||
for key, val := range aMetricVal {
|
||||
switch key {
|
||||
case "Values":
|
||||
// extract the list of "Value" from map
|
||||
values := val.(map[string]interface{})["Value"].([]interface{})
|
||||
fmt.Println(" len(Values):", len(values))
|
||||
|
||||
// first line in file is the metric label values (keys)
|
||||
var gotKeys bool
|
||||
for _, vval := range values {
|
||||
valueEntry := vval.(map[string]interface{})
|
||||
|
||||
// no guarantee that range on map will follow any sequence
|
||||
lv := len(valueEntry)
|
||||
type ev [2]string
|
||||
list := make([]ev, lv)
|
||||
var i int
|
||||
for k, v := range valueEntry {
|
||||
list[i][0] = k
|
||||
list[i][1] = v.(string)
|
||||
i++
|
||||
}
|
||||
|
||||
// extract keys as column header on first pass
|
||||
if !gotKeys {
|
||||
// print out the keys
|
||||
var gotFirstKey bool
|
||||
// for kk, _ := range valueEntry {
|
||||
for i := 0; i < lv; i++ {
|
||||
if gotFirstKey {
|
||||
mf.WriteString(",")
|
||||
} else {
|
||||
gotFirstKey = true
|
||||
}
|
||||
// strip prepended hyphen
|
||||
mf.WriteString((list[i][0])[1:])
|
||||
}
|
||||
mf.WriteString("\n")
|
||||
gotKeys = true
|
||||
}
|
||||
|
||||
// print out values
|
||||
var gotFirstVal bool
|
||||
// for _, vv := range valueEntry {
|
||||
for i := 0; i < lv; i++ {
|
||||
if gotFirstVal {
|
||||
mf.WriteString(",")
|
||||
} else {
|
||||
gotFirstVal = true
|
||||
}
|
||||
mf.WriteString(list[i][1])
|
||||
}
|
||||
|
||||
// terminate row of data
|
||||
mf.WriteString("\n")
|
||||
}
|
||||
case "Value":
|
||||
vv := val.(map[string]interface{})
|
||||
fmt.Println(" len(Value):", len(vv))
|
||||
mf.WriteString("value\n" + vv["-value"].(string) + "\n")
|
||||
}
|
||||
}
|
||||
mf.Close()
|
||||
}
|
||||
}
|
||||
-180
@@ -1,180 +0,0 @@
|
||||
// getmetrics3.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric
|
||||
// Uses NewMapXmlReaderRaw that requires loading raw XML into a []byte buffer using a ByteReader.
|
||||
// Show's performance impact of copying the raw XML while simultaneously decoding it from on os.File
|
||||
// Reader. (vs. getmetrics1.go) If you're processing a file and need a copy of the raw XML and SPEED,
|
||||
// should buffer the file in memory and decode using mxj.NewMapXmlReaderRaw as in getmetrics4.go.
|
||||
|
||||
/*
|
||||
I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an
|
||||
application that had 355,100 lines of code in 211 packages into CSV data sets. The report
|
||||
included application-, package-, class- and method-level metrics reported in an element,
|
||||
"Value", with varying attributes.
|
||||
<Value value=""/>
|
||||
<Value name="" package="" value=""/>
|
||||
<Value name="" source="" package="" value=""/>
|
||||
<Value name="" source="" package="" value="" inrange=""/>
|
||||
|
||||
In addition, the metrics were reported with two different "Metric" compound elements:
|
||||
<Metrics>
|
||||
<Metric id="" description="">
|
||||
<Values>
|
||||
<Value.../>
|
||||
...
|
||||
</Values>
|
||||
</Metric>
|
||||
...
|
||||
<Metric id="" description="">
|
||||
<Value.../>
|
||||
</Metric>
|
||||
...
|
||||
</Metrics>
|
||||
|
||||
To run this example, extract the metrics_data.xml file from metrics_data.zip, then:
|
||||
> go run getmetrics3 -file=metrics_data.xml
|
||||
|
||||
The output will be a set of "csv" files.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var file string
|
||||
flag.StringVar(&file, "file", "", "file to process")
|
||||
flag.Parse()
|
||||
|
||||
fh, fherr := os.Open(file)
|
||||
if fherr != nil {
|
||||
fmt.Println("fherr:", fherr.Error())
|
||||
return
|
||||
}
|
||||
defer fh.Close()
|
||||
fmt.Println(time.Now().String(), "... File Opened:", file)
|
||||
|
||||
/*
|
||||
// Get the XML data set from the file.
|
||||
fs, _ := fh.Stat()
|
||||
xmldata := make([]byte, fs.Size())
|
||||
n, frerr := fh.Read(xmldata)
|
||||
if frerr != nil {
|
||||
fmt.Println("frerr:", frerr.Error())
|
||||
return
|
||||
}
|
||||
if int64(n) != fs.Size() {
|
||||
fmt.Println("n:", n, "fs.Size():", fs.Size())
|
||||
return
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... File Read - size:", fs.Size())
|
||||
|
||||
// load XML into a Map value
|
||||
m, merr := mxj.NewMapXml(xmldata)
|
||||
*/
|
||||
// Consume the file using os.File Reader.
|
||||
// Note: there is a single record with root tag of "Metrics".
|
||||
// Also: this is MUCH slower than using buffer or not loading raw XML.
|
||||
m, raw, merr := mxj.NewMapXmlReaderRaw(fh)
|
||||
if merr != nil {
|
||||
log.Fatal("merr:", merr.Error())
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... XML Unmarshaled - len:", len(m))
|
||||
fmt.Println("raw XML buffer size (should be same as File size):", len(*raw))
|
||||
|
||||
// Get just the key values of interest.
|
||||
// Could also use m.ValuesForKey("Metric"),
|
||||
// since there's just the one path.
|
||||
metricVals, err := m.ValuesForPath("Metrics.Metric")
|
||||
if err != nil {
|
||||
log.Fatal("err:", err.Error())
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... ValuesFromKeyPath - len:", len(metricVals))
|
||||
|
||||
// now just manipulate Map entries returned as []interface{} array.
|
||||
for _, v := range metricVals {
|
||||
aMetricVal := v.(map[string]interface{})
|
||||
|
||||
// create file to hold csv data sets
|
||||
id := aMetricVal["-id"].(string)
|
||||
desc := aMetricVal["-description"].(string)
|
||||
mf, mferr := os.OpenFile(id+".csv", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
|
||||
if mferr != nil {
|
||||
fmt.Println("mferr:", mferr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Print(time.Now().String(), " id: ", id, " desc: ", desc)
|
||||
mf.WriteString(id + "," + desc + "\n")
|
||||
|
||||
// rescan looking for keys with data: Values or Value
|
||||
for key, val := range aMetricVal {
|
||||
switch key {
|
||||
case "Values":
|
||||
// extract the list of "Value" from map
|
||||
values := val.(map[string]interface{})["Value"].([]interface{})
|
||||
fmt.Println(" len(Values):", len(values))
|
||||
|
||||
// first line in file is the metric label values (keys)
|
||||
var gotKeys bool
|
||||
for _, vval := range values {
|
||||
valueEntry := vval.(map[string]interface{})
|
||||
|
||||
// no guarantee that range on map will follow any sequence
|
||||
lv := len(valueEntry)
|
||||
type ev [2]string
|
||||
list := make([]ev, lv)
|
||||
var i int
|
||||
for k, v := range valueEntry {
|
||||
list[i][0] = k
|
||||
list[i][1] = v.(string)
|
||||
i++
|
||||
}
|
||||
|
||||
// extract keys as column header on first pass
|
||||
if !gotKeys {
|
||||
// print out the keys
|
||||
var gotFirstKey bool
|
||||
// for kk, _ := range valueEntry {
|
||||
for i := 0; i < lv; i++ {
|
||||
if gotFirstKey {
|
||||
mf.WriteString(",")
|
||||
} else {
|
||||
gotFirstKey = true
|
||||
}
|
||||
// strip prepended hyphen
|
||||
mf.WriteString((list[i][0])[1:])
|
||||
}
|
||||
mf.WriteString("\n")
|
||||
gotKeys = true
|
||||
}
|
||||
|
||||
// print out values
|
||||
var gotFirstVal bool
|
||||
// for _, vv := range valueEntry {
|
||||
for i := 0; i < lv; i++ {
|
||||
if gotFirstVal {
|
||||
mf.WriteString(",")
|
||||
} else {
|
||||
gotFirstVal = true
|
||||
}
|
||||
mf.WriteString(list[i][1])
|
||||
}
|
||||
|
||||
// terminate row of data
|
||||
mf.WriteString("\n")
|
||||
}
|
||||
case "Value":
|
||||
vv := val.(map[string]interface{})
|
||||
fmt.Println(" len(Value):", len(vv))
|
||||
mf.WriteString("value\n" + vv["-value"].(string) + "\n")
|
||||
}
|
||||
}
|
||||
mf.Close()
|
||||
}
|
||||
}
|
||||
-179
@@ -1,179 +0,0 @@
|
||||
// getmetrics2.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric
|
||||
// Uses an in-memory buffer for the XML data and direct XML decoding of the buffer into a Map.
|
||||
// Then XML buffer is decoded into a Map while the raw XML is copied using NewMapXmlReaderRaw()
|
||||
// to illustrate processing overhead relative to getmetrics2.go. Not a practical example,
|
||||
// but confirms the getmetrics1.go vs. getmetrics3.go use case.
|
||||
|
||||
/*
|
||||
I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an
|
||||
application that had 355,100 lines of code in 211 packages into CSV data sets. The report
|
||||
included application-, package-, class- and method-level metrics reported in an element,
|
||||
"Value", with varying attributes.
|
||||
<Value value=""/>
|
||||
<Value name="" package="" value=""/>
|
||||
<Value name="" source="" package="" value=""/>
|
||||
<Value name="" source="" package="" value="" inrange=""/>
|
||||
|
||||
In addition, the metrics were reported with two different "Metric" compound elements:
|
||||
<Metrics>
|
||||
<Metric id="" description="">
|
||||
<Values>
|
||||
<Value.../>
|
||||
...
|
||||
</Values>
|
||||
</Metric>
|
||||
...
|
||||
<Metric id="" description="">
|
||||
<Value.../>
|
||||
</Metric>
|
||||
...
|
||||
</Metrics>
|
||||
|
||||
To run this example, extract the metrics_data.xml file from metrics_data.zip, then:
|
||||
> go run getmetrics -file=metrics_data.xml
|
||||
|
||||
The output will be a set of "csv" files.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var file string
|
||||
flag.StringVar(&file, "file", "", "file to process")
|
||||
flag.Parse()
|
||||
|
||||
fh, fherr := os.Open(file)
|
||||
if fherr != nil {
|
||||
fmt.Println("fherr:", fherr.Error())
|
||||
return
|
||||
}
|
||||
defer fh.Close()
|
||||
fmt.Println(time.Now().String(), "... File Opened:", file)
|
||||
|
||||
// Get the XML data set from the file.
|
||||
fs, _ := fh.Stat()
|
||||
xmldata := make([]byte, fs.Size())
|
||||
n, frerr := fh.Read(xmldata)
|
||||
if frerr != nil {
|
||||
fmt.Println("frerr:", frerr.Error())
|
||||
return
|
||||
}
|
||||
if int64(n) != fs.Size() {
|
||||
fmt.Println("n:", n, "fs.Size():", fs.Size())
|
||||
return
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... File Read - size:", fs.Size())
|
||||
|
||||
// wrap the buffer in an io.Reader
|
||||
xmlReader := bytes.NewBuffer(xmldata)
|
||||
|
||||
// load XML into a Map value
|
||||
// Note: there is a single record with root tag of "Metrics".
|
||||
m, raw, merr := mxj.NewMapXmlReaderRaw(xmlReader) // don't catch the pointer to raw XML
|
||||
if merr != nil {
|
||||
log.Fatal("merr:", merr.Error())
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... XML Unmarshaled - len:", len(m))
|
||||
fmt.Println("raw XML buffer size (should be same as File size):", len(*raw))
|
||||
|
||||
// Get just the key values of interest.
|
||||
// Could also use m.ValuesForKey("Metric"),
|
||||
// since there's just the one path.
|
||||
metricVals, err := m.ValuesForPath("Metrics.Metric")
|
||||
if err != nil {
|
||||
log.Fatal("err:", err.Error())
|
||||
}
|
||||
fmt.Println(time.Now().String(), "... ValuesFromKeyPath - len:", len(metricVals))
|
||||
|
||||
// now just manipulate Map entries returned as []interface{} array.
|
||||
for _, v := range metricVals {
|
||||
aMetricVal := v.(map[string]interface{})
|
||||
|
||||
// create file to hold csv data sets
|
||||
id := aMetricVal["-id"].(string)
|
||||
desc := aMetricVal["-description"].(string)
|
||||
mf, mferr := os.OpenFile(id+".csv", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
|
||||
if mferr != nil {
|
||||
fmt.Println("mferr:", mferr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Print(time.Now().String(), " id: ", id, " desc: ", desc)
|
||||
mf.WriteString(id + "," + desc + "\n")
|
||||
|
||||
// rescan looking for keys with data: Values or Value
|
||||
for key, val := range aMetricVal {
|
||||
switch key {
|
||||
case "Values":
|
||||
// extract the list of "Value" from map
|
||||
values := val.(map[string]interface{})["Value"].([]interface{})
|
||||
fmt.Println(" len(Values):", len(values))
|
||||
|
||||
// first line in file is the metric label values (keys)
|
||||
var gotKeys bool
|
||||
for _, vval := range values {
|
||||
valueEntry := vval.(map[string]interface{})
|
||||
|
||||
// no guarantee that range on map will follow any sequence
|
||||
lv := len(valueEntry)
|
||||
type ev [2]string
|
||||
list := make([]ev, lv)
|
||||
var i int
|
||||
for k, v := range valueEntry {
|
||||
list[i][0] = k
|
||||
list[i][1] = v.(string)
|
||||
i++
|
||||
}
|
||||
|
||||
// extract keys as column header on first pass
|
||||
if !gotKeys {
|
||||
// print out the keys
|
||||
var gotFirstKey bool
|
||||
// for kk, _ := range valueEntry {
|
||||
for i := 0; i < lv; i++ {
|
||||
if gotFirstKey {
|
||||
mf.WriteString(",")
|
||||
} else {
|
||||
gotFirstKey = true
|
||||
}
|
||||
// strip prepended hyphen
|
||||
mf.WriteString((list[i][0])[1:])
|
||||
}
|
||||
mf.WriteString("\n")
|
||||
gotKeys = true
|
||||
}
|
||||
|
||||
// print out values
|
||||
var gotFirstVal bool
|
||||
// for _, vv := range valueEntry {
|
||||
for i := 0; i < lv; i++ {
|
||||
if gotFirstVal {
|
||||
mf.WriteString(",")
|
||||
} else {
|
||||
gotFirstVal = true
|
||||
}
|
||||
mf.WriteString(list[i][1])
|
||||
}
|
||||
|
||||
// terminate row of data
|
||||
mf.WriteString("\n")
|
||||
}
|
||||
case "Value":
|
||||
vv := val.(map[string]interface{})
|
||||
fmt.Println(" len(Value):", len(vv))
|
||||
mf.WriteString("value\n" + vv["-value"].(string) + "\n")
|
||||
}
|
||||
}
|
||||
mf.Close()
|
||||
}
|
||||
}
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
// https://groups.google.com/forum/#!searchin/golang-nuts/idnet$20netid/golang-nuts/guM3ZHHqSF0/K1pBpMqQSSwJ
|
||||
// http://play.golang.org/p/BFFDxphKYK
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Demo how to compensate for irregular tag labels in data.
|
||||
// Need to extract from an XML stream the values for "netid" and "idnet".
|
||||
// Solution: use a wildcard path "data.*" to anonymize the "netid" and "idnet" tags.
|
||||
|
||||
var msg1 = []byte(`
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<data>
|
||||
<netid>
|
||||
<disable>no</disable>
|
||||
<text1>default:text</text1>
|
||||
<word1>default:word</word1>
|
||||
</netid>
|
||||
</data>
|
||||
`)
|
||||
|
||||
var msg2 = []byte(`
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<data>
|
||||
<idnet>
|
||||
<disable>yes</disable>
|
||||
<text1>default:text</text1>
|
||||
<word1>default:word</word1>
|
||||
</idnet>
|
||||
</data>
|
||||
`)
|
||||
|
||||
func main() {
|
||||
// let's create a message stream
|
||||
buf := new(bytes.Buffer)
|
||||
// load a couple of messages into it
|
||||
_, _ = buf.Write(msg1)
|
||||
_, _ = buf.Write(msg2)
|
||||
|
||||
n := 0
|
||||
for {
|
||||
n++
|
||||
// read the stream as Map values - quit on io.EOF
|
||||
m, raw, merr := mxj.NewMapXmlReaderRaw(buf)
|
||||
if merr != nil && merr != io.EOF {
|
||||
// handle error - for demo we just print it and continue
|
||||
fmt.Printf("msg: %d - merr: %s\n", n, merr.Error())
|
||||
continue
|
||||
} else if merr == io.EOF {
|
||||
break
|
||||
}
|
||||
fmt.Println("\nMessage to parse:", string(*raw))
|
||||
fmt.Println("Map value for XML message:", m.StringIndent())
|
||||
|
||||
// get the values for "netid" or "idnet" key using path == "data.*"
|
||||
values, _ := m.ValuesForPath("data.*")
|
||||
fmt.Println("\nmsg:", n, "> path == data.* - got array of values, len:", len(values))
|
||||
for i, val := range values {
|
||||
fmt.Println("ValuesForPath result array member -", i, ":", val)
|
||||
fmt.Println(" k:v pairs for array member:", i)
|
||||
for key, val := range val.(map[string]interface{}) {
|
||||
// You'd probably want to process the value, as appropriate.
|
||||
// Here we just print it out.
|
||||
fmt.Println("\t\t", key, ":", val)
|
||||
}
|
||||
}
|
||||
|
||||
// This shows what happens if you wildcard the value keys for "idnet" and "netid"
|
||||
values, _ = m.ValuesForPath("data.*.*")
|
||||
fmt.Println("\npath == data.*.* - got an array of values, len(v):", len(values))
|
||||
fmt.Println("(Note: values returned by ValuesForPath are at maximum depth of the tree. So just have values.)")
|
||||
for i, val := range values {
|
||||
fmt.Println("ValuesForPath array member -", i, ":", val)
|
||||
}
|
||||
}
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
// https://groups.google.com/forum/#!searchin/golang-nuts/idnet$20netid/golang-nuts/guM3ZHHqSF0/K1pBpMqQSSwJ
|
||||
// http://play.golang.org/p/BFFDxphKYK
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Demo how to re-label a key using mv.NewMap().
|
||||
// Need to normalize from an XML stream the tags "netid" and "idnet".
|
||||
// Solution: make everything "netid".
|
||||
|
||||
var msg1 = []byte(`
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<data>
|
||||
<netid>
|
||||
<disable>no</disable>
|
||||
<text1>default:text</text1>
|
||||
<word1>default:word</word1>
|
||||
</netid>
|
||||
</data>
|
||||
`)
|
||||
|
||||
var msg2 = []byte(`
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<data>
|
||||
<idnet>
|
||||
<disable>yes</disable>
|
||||
<text1>default:text</text1>
|
||||
<word1>default:word</word1>
|
||||
</idnet>
|
||||
</data>
|
||||
`)
|
||||
|
||||
func main() {
|
||||
// let's create a message stream
|
||||
buf := new(bytes.Buffer)
|
||||
// load a couple of messages into it
|
||||
_, _ = buf.Write(msg1)
|
||||
_, _ = buf.Write(msg2)
|
||||
|
||||
n := 0
|
||||
for {
|
||||
n++
|
||||
// read the stream as Map values - quit on io.EOF
|
||||
m, raw, merr := mxj.NewMapXmlReaderRaw(buf)
|
||||
if merr != nil && merr != io.EOF {
|
||||
// handle error - for demo we just print it and continue
|
||||
fmt.Printf("msg: %d - merr: %s\n", n, merr.Error())
|
||||
continue
|
||||
} else if merr == io.EOF {
|
||||
break
|
||||
}
|
||||
|
||||
// the first keypair retains values if data correct
|
||||
// the second keypair relabels "idnet" to "netid"
|
||||
n, _ := m.NewMap("data.netid", "data.idnet:data.netid")
|
||||
x, _ := n.XmlIndent("", " ")
|
||||
|
||||
fmt.Println("original value:", string(raw))
|
||||
fmt.Println("new value:")
|
||||
fmt.Println(string(x))
|
||||
}
|
||||
}
|
||||
-240
@@ -1,240 +0,0 @@
|
||||
// https://groups.google.com/forum/#!topic/golang-nuts/V83jUKluLnM
|
||||
// http://play.golang.org/p/alWGk4MDBc
|
||||
|
||||
// Here messsages come in one of three forms:
|
||||
// <GetClaimStatusCodesResult>... list of ClaimStatusCodeRecord ...</GetClaimStatusCodeResult>
|
||||
// <GetClaimStatusCodesResult>... one instance of ClaimStatusCodeRecord ...</GetClaimStatusCodeResult>
|
||||
// <GetClaimStatusCodesResult>... empty element ...</GetClaimStatusCodeResult>
|
||||
// ValueForPath
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
var xmlmsg1 = []byte(`<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
|
||||
<s:Body>
|
||||
<GetClaimStatusCodesResponse xmlns="http://tempuri.org/">
|
||||
<GetClaimStatusCodesResult xmlns:a="http://schemas.datacontract.org/2004/07/MRA.Claim.WebService.Domain" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<a:ClaimStatusCodeRecord>
|
||||
<a:Active>true</a:Active>
|
||||
<a:Code>A</a:Code>
|
||||
<a:Description>Initial Claim Review/Screening</a:Description>
|
||||
</a:ClaimStatusCodeRecord>
|
||||
<a:ClaimStatusCodeRecord>
|
||||
<a:Active>true</a:Active>
|
||||
<a:Code>B</a:Code>
|
||||
<a:Description>Initial Contact Made w/ Provider</a:Description>
|
||||
</a:ClaimStatusCodeRecord>
|
||||
</GetClaimStatusCodesResult>
|
||||
</GetClaimStatusCodesResponse>
|
||||
</s:Body>
|
||||
</s:Envelope>
|
||||
`)
|
||||
|
||||
var xmlmsg2 = []byte(`<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
|
||||
<s:Body>
|
||||
<GetClaimStatusCodesResponse xmlns="http://tempuri.org/">
|
||||
<GetClaimStatusCodesResult xmlns:a="http://schemas.datacontract.org/2004/07/MRA.Claim.WebService.Domain" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<a:ClaimStatusCodeRecord>
|
||||
<a:Active>true</a:Active>
|
||||
<a:Code>A</a:Code>
|
||||
<a:Description>Initial Claim Review/Screening</a:Description>
|
||||
</a:ClaimStatusCodeRecord>
|
||||
</GetClaimStatusCodesResult>
|
||||
</GetClaimStatusCodesResponse>
|
||||
</s:Body>
|
||||
</s:Envelope>
|
||||
`)
|
||||
|
||||
var xmlmsg3 = []byte(`<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
|
||||
<s:Body>
|
||||
<GetClaimStatusCodesResponse xmlns="http://tempuri.org/">
|
||||
<GetClaimStatusCodesResult xmlns:a="http://schemas.datacontract.org/2004/07/MRA.Claim.WebService.Domain" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
|
||||
</GetClaimStatusCodesResult>
|
||||
</GetClaimStatusCodesResponse>
|
||||
</s:Body>
|
||||
</s:Envelope>
|
||||
`)
|
||||
|
||||
func main() {
|
||||
xmldata := [][]byte{xmlmsg1, xmlmsg2, xmlmsg3}
|
||||
fullPath(xmldata)
|
||||
partPath1(xmlmsg1)
|
||||
partPath2(xmlmsg1)
|
||||
partPath3(xmlmsg1)
|
||||
partPath4(xmlmsg1)
|
||||
partPath5(xmlmsg1)
|
||||
partPath6(xmlmsg1)
|
||||
}
|
||||
|
||||
func fullPath(xmldata [][]byte) {
|
||||
for i, msg := range xmldata {
|
||||
fmt.Println("\ndoc:", i)
|
||||
fmt.Println(string(msg))
|
||||
// decode the XML
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
|
||||
// get the value for the key path of interest
|
||||
path := "Envelope.Body.GetClaimStatusCodesResponse.GetClaimStatusCodesResult.ClaimStatusCodeRecord"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
return
|
||||
}
|
||||
if values == nil {
|
||||
fmt.Println("path:", path)
|
||||
fmt.Println("No ClaimStatusCodesResult code records.")
|
||||
continue
|
||||
}
|
||||
fmt.Println("\nPath:", path)
|
||||
fmt.Println("Number of code records:", len(values))
|
||||
fmt.Println("values:", values, "\n")
|
||||
for _, v := range values {
|
||||
switch v.(type) {
|
||||
case map[string]interface{}:
|
||||
fmt.Println("map[string]interface{}:", v.(map[string]interface{}))
|
||||
case []map[string]interface{}:
|
||||
fmt.Println("[]map[string]interface{}:", v.([]map[string]interface{}))
|
||||
case []interface{}:
|
||||
fmt.Println("[]interface{}:", v.([]interface{}))
|
||||
case interface{}:
|
||||
fmt.Println("interface{}:", v.(interface{}))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func partPath1(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
path := "Envelope.Body.*.*.ClaimStatusCodeRecord"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
return
|
||||
}
|
||||
if values == nil {
|
||||
fmt.Println("path:", path)
|
||||
fmt.Println("No ClaimStatusCodesResult code records.")
|
||||
return
|
||||
}
|
||||
fmt.Println("\nPath:", path)
|
||||
fmt.Println("Number of code records:", len(values))
|
||||
for n, v := range values {
|
||||
fmt.Printf("\t#%d: %v\n", n, v)
|
||||
}
|
||||
}
|
||||
|
||||
func partPath2(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
path := "Envelope.Body.*.*.*"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
return
|
||||
}
|
||||
if values == nil {
|
||||
fmt.Println("path:", path)
|
||||
fmt.Println("No ClaimStatusCodesResult code records.")
|
||||
return
|
||||
}
|
||||
fmt.Println("\nPath:", path)
|
||||
fmt.Println("Number of code records:", len(values))
|
||||
for n, v := range values {
|
||||
fmt.Printf("\t#%d: %v\n", n, v)
|
||||
}
|
||||
}
|
||||
|
||||
func partPath3(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
path := "*.*.*.*.*"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
return
|
||||
}
|
||||
if values == nil {
|
||||
fmt.Println("path:", path)
|
||||
fmt.Println("No ClaimStatusCodesResult code records.")
|
||||
return
|
||||
}
|
||||
fmt.Println("\nPath:", path)
|
||||
fmt.Println("Number of code records:", len(values))
|
||||
for n, v := range values {
|
||||
fmt.Printf("\t#%d: %v\n", n, v)
|
||||
}
|
||||
}
|
||||
|
||||
func partPath4(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
path := "*.*.*.*.*.Description"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
return
|
||||
}
|
||||
if values == nil {
|
||||
fmt.Println("path:", path)
|
||||
fmt.Println("No ClaimStatusCodesResult code records.")
|
||||
return
|
||||
}
|
||||
fmt.Println("\nPath:", path)
|
||||
fmt.Println("Number of code records:", len(values))
|
||||
for n, v := range values {
|
||||
fmt.Printf("\t#%d: %v\n", n, v)
|
||||
}
|
||||
}
|
||||
|
||||
func partPath5(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
path := "*.*.*.*.*.*"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
return
|
||||
}
|
||||
if values == nil {
|
||||
fmt.Println("path:", path)
|
||||
fmt.Println("No ClaimStatusCodesResult code records.")
|
||||
return
|
||||
}
|
||||
fmt.Println("\nPath:", path)
|
||||
fmt.Println("Number of code records:", len(values))
|
||||
for n, v := range values {
|
||||
fmt.Printf("\t#%d: %v\n", n, v)
|
||||
}
|
||||
}
|
||||
|
||||
func partPath6(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
path := "*.*.*.*.*.*.*"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
return
|
||||
}
|
||||
if values == nil {
|
||||
fmt.Println("path:", path)
|
||||
fmt.Println("No ClaimStatusCodesResult code records.")
|
||||
return
|
||||
}
|
||||
fmt.Println("\nPath:", path)
|
||||
fmt.Println("Number of code records:", len(values))
|
||||
for n, v := range values {
|
||||
fmt.Printf("\t#%d: %v\n", n, v)
|
||||
}
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
// https://groups.google.com/forum/#!topic/golang-nuts/cok6xasvI3w
|
||||
// retrieve 'src' values from 'image' tags
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
var xmldata = []byte(`
|
||||
<doc>
|
||||
<image src="something.png"></image>
|
||||
<something>
|
||||
<image src="something else.jpg"></image>
|
||||
<title>something else</title>
|
||||
</something>
|
||||
<more_stuff>
|
||||
<some_images>
|
||||
<image src="first.gif"></image>
|
||||
<image src="second.gif"></image>
|
||||
</some_images>
|
||||
</more_stuff>
|
||||
</doc>`)
|
||||
|
||||
func main() {
|
||||
fmt.Println("xmldata:", string(xmldata))
|
||||
|
||||
// get all image tag values - []interface{}
|
||||
m, merr := mxj.NewMapXml(xmldata)
|
||||
if merr != nil {
|
||||
fmt.Println("merr:", merr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// grab all values for attribute "src"
|
||||
// Note: attributes are prepended with a hyphen, '-'.
|
||||
sources, err := m.ValuesForKey("-src")
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
for _, src := range sources {
|
||||
fmt.Println(src)
|
||||
}
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
// https://groups.google.com/forum/#!topic/golang-nuts/-N9Toa6qlu8
|
||||
// shows that you can extract attribute values directly from tag/key path.
|
||||
// NOTE: attribute values are encoded by prepending a hyphen, '-'.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
var xmldata = []byte(`
|
||||
<doc>
|
||||
<some_tag>
|
||||
<geoInfo>
|
||||
<city name="SEATTLE"/>
|
||||
<state name="WA"/>
|
||||
<country name="USA"/>
|
||||
</geoInfo>
|
||||
<geoInfo>
|
||||
<city name="VANCOUVER"/>
|
||||
<state name="BC"/>
|
||||
<country name="CA"/>
|
||||
</geoInfo>
|
||||
<geoInfo>
|
||||
<city name="LONDON"/>
|
||||
<country name="UK"/>
|
||||
</geoInfo>
|
||||
</some_tag>
|
||||
</doc>`)
|
||||
|
||||
func main() {
|
||||
fmt.Println("xmldata:", string(xmldata))
|
||||
|
||||
m, merr := mxj.NewMapXml(xmldata)
|
||||
if merr != nil {
|
||||
fmt.Println("merr:", merr)
|
||||
return
|
||||
}
|
||||
|
||||
// Attributes are keys with prepended hyphen, '-'.
|
||||
values, err := m.ValuesForPath("doc.some_tag.geoInfo.country.-name")
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
}
|
||||
|
||||
for _, v := range values {
|
||||
fmt.Println("v:", v)
|
||||
}
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
// gonuts5.go - from https://groups.google.com/forum/#!topic/golang-nuts/MWoYY19of3o
|
||||
// problem is to extract entries from <lst name="list3-1-1-1"></lst> by "int name="
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
var xmlData = []byte(`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<response>
|
||||
<lst name="list1">
|
||||
</lst>
|
||||
<lst name="list2">
|
||||
</lst>
|
||||
<lst name="list3">
|
||||
<int name="docId">1</int>
|
||||
<lst name="list3-1">
|
||||
<lst name="list3-1-1">
|
||||
<lst name="list3-1-1-1">
|
||||
<int name="field1">1</int>
|
||||
<int name="field2">2</int>
|
||||
<int name="field3">3</int>
|
||||
<int name="field4">4</int>
|
||||
<int name="field5">5</int>
|
||||
</lst>
|
||||
</lst>
|
||||
<lst name="list3-1-2">
|
||||
<lst name="list3-1-2-1">
|
||||
<int name="field1">1</int>
|
||||
<int name="field2">2</int>
|
||||
<int name="field3">3</int>
|
||||
<int name="field4">4</int>
|
||||
<int name="field5">5</int>
|
||||
</lst>
|
||||
</lst>
|
||||
</lst>
|
||||
</lst>
|
||||
</response>`)
|
||||
|
||||
func main() {
|
||||
// parse XML into a Map
|
||||
m, merr := mxj.NewMapXml(xmlData)
|
||||
if merr != nil {
|
||||
fmt.Println("merr:", merr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// extract the 'list3-1-1-1' node - there'll be just 1?
|
||||
// NOTE: attribute keys are prepended with '-'
|
||||
lstVal, lerr := m.ValuesForPath("*.*.*.*.*", "-name:list3-1-1-1")
|
||||
if lerr != nil {
|
||||
fmt.Println("ierr:", lerr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// assuming just one value returned - create a new Map
|
||||
mv := mxj.Map(lstVal[0].(map[string]interface{}))
|
||||
|
||||
// extract the 'int' values by 'name' attribute: "-name"
|
||||
// interate over list of 'name' values of interest
|
||||
var names = []string{"field1", "field2", "field3", "field4", "field5"}
|
||||
for _, n := range names {
|
||||
vals, verr := mv.ValuesForKey("int", "-name:"+n)
|
||||
if verr != nil {
|
||||
fmt.Println("verr:", verr.Error(), len(vals))
|
||||
return
|
||||
}
|
||||
|
||||
// values for simple elements have key '#text'
|
||||
// NOTE: there can be only one value for key '#text'
|
||||
fmt.Println(n, ":", vals[0].(map[string]interface{})["#text"])
|
||||
}
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
// gonuts5.go - from https://groups.google.com/forum/#!topic/golang-nuts/MWoYY19of3o
|
||||
// problem is to extract entries from <lst name="list3-1-1-1"></lst> by "int name="
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
var xmlData = []byte(`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<response>
|
||||
<lst name="list1">
|
||||
</lst>
|
||||
<lst name="list2">
|
||||
</lst>
|
||||
<lst name="list3">
|
||||
<int name="docId">1</int>
|
||||
<lst name="list3-1">
|
||||
<lst name="list3-1-1">
|
||||
<lst name="list3-1-1-1">
|
||||
<int name="field1">1</int>
|
||||
<int name="field2">2</int>
|
||||
<int name="field3">3</int>
|
||||
<int name="field4">4</int>
|
||||
<int name="field5">5</int>
|
||||
</lst>
|
||||
</lst>
|
||||
<lst name="list3-1-2">
|
||||
<lst name="list3-1-2-1">
|
||||
<int name="field1">1</int>
|
||||
<int name="field2">2</int>
|
||||
<int name="field3">3</int>
|
||||
<int name="field4">4</int>
|
||||
<int name="field5">5</int>
|
||||
</lst>
|
||||
</lst>
|
||||
</lst>
|
||||
</lst>
|
||||
</response>`)
|
||||
|
||||
func main() {
|
||||
// parse XML into a Map
|
||||
m, merr := mxj.NewMapXml(xmlData)
|
||||
if merr != nil {
|
||||
fmt.Println("merr:", merr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// extract the 'list3-1-1-1' node - there'll be just 1?
|
||||
// NOTE: attribute keys are prepended with '-'
|
||||
lstVal, lerr := m.ValuesForPath("*.*.*.*.*", "-name:list3-1-1-1")
|
||||
if lerr != nil {
|
||||
fmt.Println("ierr:", lerr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// assuming just one value returned - create a new Map
|
||||
mv := mxj.Map(lstVal[0].(map[string]interface{}))
|
||||
|
||||
// extract the 'int' values by 'name' attribute: "-name"
|
||||
// interate over list of 'name' values of interest
|
||||
var names = []string{"field1", "field2", "field3", "field4", "field5"}
|
||||
for _, n := range names {
|
||||
vals, verr := mv.ValuesForKey("*", "-name:"+n)
|
||||
if verr != nil {
|
||||
fmt.Println("verr:", verr.Error(), len(vals))
|
||||
return
|
||||
}
|
||||
|
||||
// values for simple elements have key '#text'
|
||||
// NOTE: there can be only one value for key '#text'
|
||||
fmt.Println(n, ":", vals[0].(map[string]interface{})["#text"])
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
/* https://groups.google.com/forum/#!topic/golang-nuts/EMXHB1nJoBA
|
||||
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
import "encoding/json"
|
||||
|
||||
func main() {
|
||||
var v struct {
|
||||
DBInstances []struct {
|
||||
Endpoint struct {
|
||||
Address string
|
||||
}
|
||||
}
|
||||
}
|
||||
json.Unmarshal(s, &v)
|
||||
fmt.Println(v.DBInstances[0].Endpoint.Address)
|
||||
}
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
import "github.com/clbanning/mxj"
|
||||
|
||||
func main() {
|
||||
m, err := mxj.NewMapJson(s)
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
}
|
||||
v, err := m.ValuesForKey("Address")
|
||||
// v, err := m.ValuesForPath("DBInstances[0].Endpoint.Address")
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
}
|
||||
if len(v) > 0 {
|
||||
fmt.Println(v[0].(string))
|
||||
} else {
|
||||
fmt.Println("No value.")
|
||||
}
|
||||
}
|
||||
|
||||
var s = []byte(`{ "DBInstances": [ { "PubliclyAccessible": true, "MasterUsername": "postgres", "LicenseModel": "postgresql-license", "VpcSecurityGroups": [ { "Status": "active", "VpcSecurityGroupId": "sg-e72a4282" } ], "InstanceCreateTime": "2014-06-29T03:52:59.268Z", "OptionGroupMemberships": [ { "Status": "in-sync", "OptionGroupName": "default:postgres-9-3" } ], "PendingModifiedValues": {}, "Engine": "postgres", "MultiAZ": true, "LatestRestorableTime": "2014-06-29T12:00:34Z", "DBSecurityGroups": [ { "Status": "active", "DBSecurityGroupName": "production-dbsecuritygroup-q4f0ugxpjck8" } ], "DBParameterGroups": [ { "DBParameterGroupName": "default.postgres9.3", "ParameterApplyStatus": "in-sync" } ], "AutoMinorVersionUpgrade": true, "PreferredBackupWindow": "06:59-07:29", "DBSubnetGroup": { "Subnets": [ { "SubnetStatus": "Active", "SubnetIdentifier": "subnet-34e5d01c", "SubnetAvailabilityZone": { "Name": "us-east-1b", "ProvisionedIopsCapable": false } }, { "SubnetStatus": "Active", "SubnetIdentifier": "subnet-50759d27", "SubnetAvailabilityZone": { "Name": "us-east-1c", "ProvisionedIopsCapable": false } }, { "SubnetStatus": "Active", "SubnetIdentifier": "subnet-450a1f03", "SubnetAvailabilityZone": { "Name": "us-east-1d", "ProvisionedIopsCapable": false } } ], "DBSubnetGroupName": "default", "VpcId": "vpc-acb86cc9", "DBSubnetGroupDescription": "default", "SubnetGroupStatus": "Complete" }, "SecondaryAvailabilityZone": "us-east-1b", "ReadReplicaDBInstanceIdentifiers": [], "AllocatedStorage": 15, "BackupRetentionPeriod": 1, "DBName": "deis", "PreferredMaintenanceWindow": "fri:05:52-fri:06:22", "Endpoint": { "Port": 5432, "Address": "production.cfk8mskkbkeu.us-east-1.rds.amazonaws.com" }, "DBInstanceStatus": "available", "EngineVersion": "9.3.3", "AvailabilityZone": "us-east-1c", "DBInstanceClass": "db.m1.small", "DBInstanceIdentifier": "production" } ] }`)
|
||||
BIN
Binary file not shown.
-7
@@ -1,7 +0,0 @@
|
||||
package mxj
|
||||
|
||||
// Checks whether the path exists
|
||||
func (mv Map) Exists(path string) bool {
|
||||
v, err := mv.ValuesForPath(path)
|
||||
return err == nil && len(v) > 0
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package mxj
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestExists(t *testing.T) {
|
||||
m := map[string]interface{}{
|
||||
"Div": map[string]interface{}{
|
||||
"Colour": "blue",
|
||||
},
|
||||
}
|
||||
mv := Map(m)
|
||||
|
||||
if !mv.Exists("Div.Colour") {
|
||||
t.Fatal("Haven't found an existing element")
|
||||
}
|
||||
|
||||
if mv.Exists("Div.Color") {
|
||||
t.Fatal("Have found a non existing element")
|
||||
}
|
||||
}
|
||||
-299
@@ -1,299 +0,0 @@
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Maps []Map
|
||||
|
||||
func NewMaps() Maps {
|
||||
return make(Maps, 0)
|
||||
}
|
||||
|
||||
type MapRaw struct {
|
||||
M Map
|
||||
R []byte
|
||||
}
|
||||
|
||||
// NewMapsFromXmlFile - creates an array from a file of JSON values.
|
||||
func NewMapsFromJsonFile(name string) (Maps, error) {
|
||||
fi, err := os.Stat(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !fi.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("file %s is not a regular file", name)
|
||||
}
|
||||
|
||||
fh, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
am := make([]Map, 0)
|
||||
for {
|
||||
m, raw, err := NewMapJsonReaderRaw(fh)
|
||||
if err != nil && err != io.EOF {
|
||||
return am, fmt.Errorf("error: %s - reading: %s", err.Error(), string(raw))
|
||||
}
|
||||
if len(m) > 0 {
|
||||
am = append(am, m)
|
||||
}
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
}
|
||||
return am, nil
|
||||
}
|
||||
|
||||
// ReadMapsFromJsonFileRaw - creates an array of MapRaw from a file of JSON values.
|
||||
func NewMapsFromJsonFileRaw(name string) ([]MapRaw, error) {
|
||||
fi, err := os.Stat(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !fi.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("file %s is not a regular file", name)
|
||||
}
|
||||
|
||||
fh, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
am := make([]MapRaw, 0)
|
||||
for {
|
||||
mr := new(MapRaw)
|
||||
mr.M, mr.R, err = NewMapJsonReaderRaw(fh)
|
||||
if err != nil && err != io.EOF {
|
||||
return am, fmt.Errorf("error: %s - reading: %s", err.Error(), string(mr.R))
|
||||
}
|
||||
if len(mr.M) > 0 {
|
||||
am = append(am, *mr)
|
||||
}
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
}
|
||||
return am, nil
|
||||
}
|
||||
|
||||
// NewMapsFromXmlFile - creates an array from a file of XML values.
|
||||
func NewMapsFromXmlFile(name string) (Maps, error) {
|
||||
x := XmlWriterBufSize
|
||||
XmlWriterBufSize = 0
|
||||
defer func() {
|
||||
XmlWriterBufSize = x
|
||||
}()
|
||||
|
||||
fi, err := os.Stat(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !fi.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("file %s is not a regular file", name)
|
||||
}
|
||||
|
||||
fh, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
am := make([]Map, 0)
|
||||
for {
|
||||
m, raw, err := NewMapXmlReaderRaw(fh)
|
||||
if err != nil && err != io.EOF {
|
||||
return am, fmt.Errorf("error: %s - reading: %s", err.Error(), string(raw))
|
||||
}
|
||||
if len(m) > 0 {
|
||||
am = append(am, m)
|
||||
}
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
}
|
||||
return am, nil
|
||||
}
|
||||
|
||||
// NewMapsFromXmlFileRaw - creates an array of MapRaw from a file of XML values.
|
||||
// NOTE: the slice with the raw XML is clean with no extra capacity - unlike NewMapXmlReaderRaw().
|
||||
// It is slow at parsing a file from disk and is intended for relatively small utility files.
|
||||
func NewMapsFromXmlFileRaw(name string) ([]MapRaw, error) {
|
||||
x := XmlWriterBufSize
|
||||
XmlWriterBufSize = 0
|
||||
defer func() {
|
||||
XmlWriterBufSize = x
|
||||
}()
|
||||
|
||||
fi, err := os.Stat(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !fi.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("file %s is not a regular file", name)
|
||||
}
|
||||
|
||||
fh, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
am := make([]MapRaw, 0)
|
||||
for {
|
||||
mr := new(MapRaw)
|
||||
mr.M, mr.R, err = NewMapXmlReaderRaw(fh)
|
||||
if err != nil && err != io.EOF {
|
||||
return am, fmt.Errorf("error: %s - reading: %s", err.Error(), string(mr.R))
|
||||
}
|
||||
if len(mr.M) > 0 {
|
||||
am = append(am, *mr)
|
||||
}
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
}
|
||||
return am, nil
|
||||
}
|
||||
|
||||
// ------------------------ Maps writing -------------------------
|
||||
// These are handy-dandy methods for dumping configuration data, etc.
|
||||
|
||||
// JsonString - analogous to mv.Json()
|
||||
func (mvs Maps) JsonString(safeEncoding ...bool) (string, error) {
|
||||
var s string
|
||||
for _, v := range mvs {
|
||||
j, err := v.Json()
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
s += string(j)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// JsonStringIndent - analogous to mv.JsonIndent()
|
||||
func (mvs Maps) JsonStringIndent(prefix, indent string, safeEncoding ...bool) (string, error) {
|
||||
var s string
|
||||
var haveFirst bool
|
||||
for _, v := range mvs {
|
||||
j, err := v.JsonIndent(prefix, indent)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
if haveFirst {
|
||||
s += "\n"
|
||||
} else {
|
||||
haveFirst = true
|
||||
}
|
||||
s += string(j)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// XmlString - analogous to mv.Xml()
|
||||
func (mvs Maps) XmlString() (string, error) {
|
||||
var s string
|
||||
for _, v := range mvs {
|
||||
x, err := v.Xml()
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
s += string(x)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// XmlStringIndent - analogous to mv.XmlIndent()
|
||||
func (mvs Maps) XmlStringIndent(prefix, indent string) (string, error) {
|
||||
var s string
|
||||
for _, v := range mvs {
|
||||
x, err := v.XmlIndent(prefix, indent)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
s += string(x)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// JsonFile - write Maps to named file as JSON
|
||||
// Note: the file will be created, if necessary; if it exists it will be truncated.
|
||||
// If you need to append to a file, open it and use JsonWriter method.
|
||||
func (mvs Maps) JsonFile(file string, safeEncoding ...bool) error {
|
||||
var encoding bool
|
||||
if len(safeEncoding) == 1 {
|
||||
encoding = safeEncoding[0]
|
||||
}
|
||||
s, err := mvs.JsonString(encoding)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fh, err := os.Create(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fh.Close()
|
||||
fh.WriteString(s)
|
||||
return nil
|
||||
}
|
||||
|
||||
// JsonFileIndent - write Maps to named file as pretty JSON
|
||||
// Note: the file will be created, if necessary; if it exists it will be truncated.
|
||||
// If you need to append to a file, open it and use JsonIndentWriter method.
|
||||
func (mvs Maps) JsonFileIndent(file, prefix, indent string, safeEncoding ...bool) error {
|
||||
var encoding bool
|
||||
if len(safeEncoding) == 1 {
|
||||
encoding = safeEncoding[0]
|
||||
}
|
||||
s, err := mvs.JsonStringIndent(prefix, indent, encoding)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fh, err := os.Create(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fh.Close()
|
||||
fh.WriteString(s)
|
||||
return nil
|
||||
}
|
||||
|
||||
// XmlFile - write Maps to named file as XML
|
||||
// Note: the file will be created, if necessary; if it exists it will be truncated.
|
||||
// If you need to append to a file, open it and use XmlWriter method.
|
||||
func (mvs Maps) XmlFile(file string) error {
|
||||
s, err := mvs.XmlString()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fh, err := os.Create(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fh.Close()
|
||||
fh.WriteString(s)
|
||||
return nil
|
||||
}
|
||||
|
||||
// XmlFileIndent - write Maps to named file as pretty XML
|
||||
// Note: the file will be created,if necessary; if it exists it will be truncated.
|
||||
// If you need to append to a file, open it and use XmlIndentWriter method.
|
||||
func (mvs Maps) XmlFileIndent(file, prefix, indent string) error {
|
||||
s, err := mvs.XmlStringIndent(prefix, indent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fh, err := os.Create(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fh.Close()
|
||||
fh.WriteString(s)
|
||||
return nil
|
||||
}
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
{ "this":"is", "a":"test", "file":"for", "files_test.go":"case" }
|
||||
{ "with":"some", "bad":JSON, "in":"it" }
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
<doc>
|
||||
<some>test</some>
|
||||
<data>for files.go</data>
|
||||
</doc>
|
||||
<msg>
|
||||
<just>some</just>
|
||||
<another>doc</other>
|
||||
<for>test case</for>
|
||||
</msg>
|
||||
-168
@@ -1,168 +0,0 @@
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFilesHeader(t *testing.T) {
|
||||
fmt.Println("\n---------------- files_test.go ...\n")
|
||||
}
|
||||
|
||||
func TestNewJsonFile(t *testing.T) {
|
||||
fmt.Println("NewMapsFromJsonFile()")
|
||||
am, err := NewMapsFromJsonFile("files_test.json")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
for _, v := range am {
|
||||
fmt.Printf("%v\n", v)
|
||||
}
|
||||
|
||||
am, err = NewMapsFromJsonFile("nil")
|
||||
if err == nil {
|
||||
t.Fatal("no error returned for read of nil file")
|
||||
}
|
||||
fmt.Println("caught error: ", err.Error())
|
||||
|
||||
am, err = NewMapsFromJsonFile("files_test.badjson")
|
||||
if err == nil {
|
||||
t.Fatal("no error returned for read of badjson file")
|
||||
}
|
||||
fmt.Println("caught error: ", err.Error())
|
||||
}
|
||||
|
||||
func TestNewJsonFileRaw(t *testing.T) {
|
||||
fmt.Println("NewMapsFromJsonFileRaw()")
|
||||
mr, err := NewMapsFromJsonFileRaw("files_test.json")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
for _, v := range mr {
|
||||
fmt.Printf("%v\n", v)
|
||||
}
|
||||
|
||||
mr, err = NewMapsFromJsonFileRaw("nil")
|
||||
if err == nil {
|
||||
t.Fatal("no error returned for read of nil file")
|
||||
}
|
||||
fmt.Println("caught error: ", err.Error())
|
||||
|
||||
mr, err = NewMapsFromJsonFileRaw("files_test.badjson")
|
||||
if err == nil {
|
||||
t.Fatal("no error returned for read of badjson file")
|
||||
}
|
||||
fmt.Println("caught error: ", err.Error())
|
||||
}
|
||||
|
||||
func TestNewXmFile(t *testing.T) {
|
||||
fmt.Println("NewMapsFromXmlFile()")
|
||||
am, err := NewMapsFromXmlFile("files_test.xml")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
for _, v := range am {
|
||||
fmt.Printf("%v\n", v)
|
||||
}
|
||||
|
||||
am, err = NewMapsFromXmlFile("nil")
|
||||
if err == nil {
|
||||
t.Fatal("no error returned for read of nil file")
|
||||
}
|
||||
fmt.Println("caught error: ", err.Error())
|
||||
|
||||
am, err = NewMapsFromXmlFile("files_test.badxml")
|
||||
if err == nil {
|
||||
t.Fatal("no error returned for read of badjson file")
|
||||
}
|
||||
fmt.Println("caught error: ", err.Error())
|
||||
}
|
||||
|
||||
func TestNewXmFileRaw(t *testing.T) {
|
||||
fmt.Println("NewMapsFromXmlFileRaw()")
|
||||
mr, err := NewMapsFromXmlFileRaw("files_test.xml")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
for _, v := range mr {
|
||||
fmt.Printf("%v\n", v)
|
||||
}
|
||||
|
||||
mr, err = NewMapsFromXmlFileRaw("nil")
|
||||
if err == nil {
|
||||
t.Fatal("no error returned for read of nil file")
|
||||
}
|
||||
fmt.Println("caught error: ", err.Error())
|
||||
|
||||
mr, err = NewMapsFromXmlFileRaw("files_test.badxml")
|
||||
if err == nil {
|
||||
t.Fatal("no error returned for read of badjson file")
|
||||
}
|
||||
fmt.Println("caught error: ", err.Error())
|
||||
}
|
||||
|
||||
func TestMaps(t *testing.T) {
|
||||
fmt.Println("TestMaps()")
|
||||
mvs := NewMaps()
|
||||
for i := 0; i < 2; i++ {
|
||||
m, _ := NewMapJson([]byte(`{ "this":"is", "a":"test" }`))
|
||||
mvs = append(mvs, m)
|
||||
}
|
||||
fmt.Println("mvs:", mvs)
|
||||
|
||||
s, _ := mvs.JsonString()
|
||||
fmt.Println("JsonString():", s)
|
||||
|
||||
s, _ = mvs.JsonStringIndent("", " ")
|
||||
fmt.Println("JsonStringIndent():", s)
|
||||
|
||||
s, _ = mvs.XmlString()
|
||||
fmt.Println("XmlString():", s)
|
||||
|
||||
s, _ = mvs.XmlStringIndent("", " ")
|
||||
fmt.Println("XmlStringIndent():", s)
|
||||
}
|
||||
|
||||
func TestJsonFile(t *testing.T) {
|
||||
am, err := NewMapsFromJsonFile("files_test.json")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
for _, v := range am {
|
||||
fmt.Printf("%v\n", v)
|
||||
}
|
||||
|
||||
err = am.JsonFile("files_test_dup.json")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
fmt.Println("files_test_dup.json written")
|
||||
|
||||
err = am.JsonFileIndent("files_test_indent.json", "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
fmt.Println("files_test_indent.json written")
|
||||
}
|
||||
|
||||
func TestXmlFile(t *testing.T) {
|
||||
am, err := NewMapsFromXmlFile("files_test.xml")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
for _, v := range am {
|
||||
fmt.Printf("%v\n", v)
|
||||
}
|
||||
|
||||
err = am.XmlFile("files_test_dup.xml")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
fmt.Println("files_test_dup.xml written")
|
||||
|
||||
err = am.XmlFileIndent("files_test_indent.xml", "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
fmt.Println("files_test_indent.xml written")
|
||||
}
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
{ "this":"is", "a":"test", "file":"for", "files_test.go":"case" }
|
||||
{ "with":"just", "two":2, "JSON":"values", "true":true }
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
<doc>
|
||||
<some>test</some>
|
||||
<data>for files.go</data>
|
||||
</doc>
|
||||
<msg>
|
||||
<just>some</just>
|
||||
<another>doc</another>
|
||||
<for>test case</for>
|
||||
</msg>
|
||||
-1
@@ -1 +0,0 @@
|
||||
{"a":"test","file":"for","files_test.go":"case","this":"is"}{"JSON":"values","true":true,"two":2,"with":"just"}
|
||||
-1
@@ -1 +0,0 @@
|
||||
<doc><some>test</some><data>for files.go</data></doc><msg><just>some</just><another>doc</another><for>test case</for></msg>
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"a": "test",
|
||||
"file": "for",
|
||||
"files_test.go": "case",
|
||||
"this": "is"
|
||||
}
|
||||
{
|
||||
"JSON": "values",
|
||||
"true": true,
|
||||
"two": 2,
|
||||
"with": "just"
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
<doc>
|
||||
<some>test</some>
|
||||
<data>for files.go</data>
|
||||
</doc><msg>
|
||||
<just>some</just>
|
||||
<another>doc</another>
|
||||
<for>test case</for>
|
||||
</msg>
|
||||
-178
@@ -1,178 +0,0 @@
|
||||
// Copyright 2012-2014 Charles Banning. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file
|
||||
|
||||
// j2x.go - For (mostly) backwards compatibility with legacy j2x package.
|
||||
// Wrappers for end-to-end JSON to XML transformation and value manipulation.
|
||||
package j2x
|
||||
|
||||
import (
|
||||
. "github.com/clbanning/mxj"
|
||||
"io"
|
||||
)
|
||||
|
||||
// FromJson() --> map[string]interface{}
|
||||
func JsonToMap(jsonVal []byte) (map[string]interface{}, error) {
|
||||
return NewMapJson(jsonVal)
|
||||
}
|
||||
|
||||
// interface{} --> ToJson (w/o safe encoding, default) {
|
||||
func MapToJson(m map[string]interface{}, safeEncoding ...bool) ([]byte, error) {
|
||||
return Map(m).Json()
|
||||
}
|
||||
|
||||
// FromJson() --> ToXml().
|
||||
func JsonToXml(jsonVal []byte) ([]byte, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.Xml()
|
||||
}
|
||||
|
||||
// FromJson() --> ToXmlWriter().
|
||||
func JsonToXmlWriter(jsonVal []byte, xmlWriter io.Writer) ([]byte, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.XmlWriterRaw(xmlWriter)
|
||||
}
|
||||
|
||||
// FromJsonReader() --> ToXml().
|
||||
func JsonReaderToXml(jsonReader io.Reader) ([]byte, []byte, error) {
|
||||
m, jraw, err := NewMapJsonReaderRaw(jsonReader)
|
||||
if err != nil {
|
||||
return jraw, nil, err
|
||||
}
|
||||
x, xerr := m.Xml()
|
||||
return jraw, x, xerr
|
||||
}
|
||||
|
||||
// FromJsonReader() --> ToXmlWriter(). Handy for transforming bulk message sets.
|
||||
func JsonReaderToXmlWriter(jsonReader io.Reader, xmlWriter io.Writer) ([]byte, []byte, error) {
|
||||
m, jraw, err := NewMapJsonReaderRaw(jsonReader)
|
||||
if err != nil {
|
||||
return jraw, nil, err
|
||||
}
|
||||
xraw, xerr := m.XmlWriterRaw(xmlWriter)
|
||||
return jraw, xraw, xerr
|
||||
}
|
||||
|
||||
// JSON wrappers for Map methods implementing key path and value functions.
|
||||
|
||||
// Wrap PathsForKey for JSON.
|
||||
func JsonPathsForKey(jsonVal []byte, key string) ([]string, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
paths := m.PathsForKey(key)
|
||||
return paths, nil
|
||||
}
|
||||
|
||||
// Wrap PathForKeyShortest for JSON.
|
||||
func JsonPathForKeyShortest(jsonVal []byte, key string) (string, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path := m.PathForKeyShortest(key)
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// Wrap ValuesForKey for JSON.
|
||||
func JsonValuesForKey(jsonVal []byte, key string, subkeys ...string) ([]interface{}, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.ValuesForKey(key, subkeys...)
|
||||
}
|
||||
|
||||
// Wrap ValuesForKeyPath for JSON.
|
||||
func JsonValuesForKeyPath(jsonVal []byte, path string, subkeys ...string) ([]interface{}, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.ValuesForPath(path, subkeys...)
|
||||
}
|
||||
|
||||
// Wrap UpdateValuesForPath for JSON
|
||||
// 'jsonVal' is XML value
|
||||
// 'newKeyValue' is the value to replace an existing value at the end of 'path'
|
||||
// 'path' is the dot-notation path with the key whose value is to be replaced at the end
|
||||
// (can include wildcard character, '*')
|
||||
// 'subkeys' are key:value pairs of key:values that must match for the key
|
||||
func JsonUpdateValsForPath(jsonVal []byte, newKeyValue interface{}, path string, subkeys ...string) ([]byte, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = m.UpdateValuesForPath(newKeyValue, path, subkeys...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.Json()
|
||||
}
|
||||
|
||||
// Wrap NewMap for JSON and return as JSON
|
||||
// 'jsonVal' is an JSON value
|
||||
// 'keypairs' are "oldKey:newKey" values that conform to 'keypairs' in (Map)NewMap.
|
||||
func JsonNewJson(jsonVal []byte, keypairs ...string) ([]byte, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, err := m.NewMap(keypairs...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return n.Json()
|
||||
}
|
||||
|
||||
// Wrap NewMap for JSON and return as XML
|
||||
// 'jsonVal' is an JSON value
|
||||
// 'keypairs' are "oldKey:newKey" values that conform to 'keypairs' in (Map)NewMap.
|
||||
func JsonNewXml(jsonVal []byte, keypairs ...string) ([]byte, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, err := m.NewMap(keypairs...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return n.Xml()
|
||||
}
|
||||
|
||||
// Wrap LeafNodes for JSON.
|
||||
// 'jsonVal' is an JSON value
|
||||
func JsonLeafNodes(jsonVal []byte) ([]LeafNode, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.LeafNodes(), nil
|
||||
}
|
||||
|
||||
// Wrap LeafValues for JSON.
|
||||
// 'jsonVal' is an JSON value
|
||||
func JsonLeafValues(jsonVal []byte) ([]interface{}, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.LeafValues(), nil
|
||||
}
|
||||
|
||||
// Wrap LeafPath for JSON.
|
||||
// 'xmlVal' is an JSON value
|
||||
func JsonLeafPath(jsonVal []byte) ([]string, error) {
|
||||
m, err := NewMapJson(jsonVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.LeafPaths(), nil
|
||||
}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
// thanks to Chris Malek (chris.r.malek@gmail.com) for suggestion to handle JSON list docs.
|
||||
|
||||
package j2x
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestJsonToXml_1(t *testing.T) {
|
||||
// mimic a io.Reader
|
||||
// Body := bytes.NewReader([]byte(`{"some-null-value":"", "a-non-null-value":"bar"}`))
|
||||
Body := bytes.NewReader([]byte(`[{"some-null-value":"", "a-non-null-value":"bar"}]`))
|
||||
|
||||
//body, err := ioutil.ReadAll(req.Body)
|
||||
body, err := ioutil.ReadAll(Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println(string(body))
|
||||
//if err != nil {
|
||||
// t.Fatal(err)
|
||||
//}
|
||||
|
||||
var xmloutput []byte
|
||||
//xmloutput, err = j2x.JsonToXml(body)
|
||||
xmloutput, err = JsonToXml(body)
|
||||
|
||||
//log.Println(string(xmloutput))
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
// log.Println(err)
|
||||
// http.Error(rw, "Could not convert to xml", 400)
|
||||
}
|
||||
fmt.Println("xmloutput:", string(xmloutput))
|
||||
}
|
||||
|
||||
func TestJsonToXml_2(t *testing.T) {
|
||||
// mimic a io.Reader
|
||||
Body := bytes.NewReader([]byte(`{"somekey":[{"value":"1st"},{"value":"2nd"}]}`))
|
||||
|
||||
//body, err := ioutil.ReadAll(req.Body)
|
||||
body, err := ioutil.ReadAll(Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Println(string(body))
|
||||
//if err != nil {
|
||||
// t.Fatal(err)
|
||||
//}
|
||||
|
||||
var xmloutput []byte
|
||||
//xmloutput, err = j2x.JsonToXml(body)
|
||||
xmloutput, err = JsonToXml(body)
|
||||
|
||||
//log.Println(string(xmloutput))
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
// log.Println(err)
|
||||
// http.Error(rw, "Could not convert to xml", 400)
|
||||
}
|
||||
fmt.Println("xmloutput:", string(xmloutput))
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var jjdata = []byte(`{ "key1":"string", "key2":34, "key3":true, "key4":"unsafe: <>&", "key5":null }`)
|
||||
|
||||
func TestJ2XHeader(t *testing.T) {
|
||||
fmt.Println("\n---------------- j2x_test .go ...\n")
|
||||
}
|
||||
|
||||
func TestJ2X(t *testing.T) {
|
||||
|
||||
m, err := NewMapJson(jjdata)
|
||||
if err != nil {
|
||||
t.Fatal("NewMapJson, err:", err)
|
||||
}
|
||||
|
||||
x, err := m.Xml()
|
||||
if err != nil {
|
||||
t.Fatal("m.Xml(), err:", err)
|
||||
}
|
||||
|
||||
fmt.Println("j2x, jdata:", string(jjdata))
|
||||
fmt.Println("j2x, m :", m)
|
||||
fmt.Println("j2x, xml :", string(x))
|
||||
}
|
||||
-319
@@ -1,319 +0,0 @@
|
||||
// Copyright 2012-2014 Charles Banning. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file
|
||||
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ------------------------------ write JSON -----------------------
|
||||
|
||||
// Just a wrapper on json.Marshal.
|
||||
// If option safeEncoding is'true' then safe encoding of '<', '>' and '&'
|
||||
// is preserved. (see encoding/json#Marshal, encoding/json#Encode)
|
||||
func (mv Map) Json(safeEncoding ...bool) ([]byte, error) {
|
||||
var s bool
|
||||
if len(safeEncoding) == 1 {
|
||||
s = safeEncoding[0]
|
||||
}
|
||||
|
||||
b, err := json.Marshal(mv)
|
||||
|
||||
if !s {
|
||||
b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1)
|
||||
b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1)
|
||||
b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1)
|
||||
}
|
||||
return b, err
|
||||
}
|
||||
|
||||
// Just a wrapper on json.MarshalIndent.
|
||||
// If option safeEncoding is'true' then safe encoding of '<' , '>' and '&'
|
||||
// is preserved. (see encoding/json#Marshal, encoding/json#Encode)
|
||||
func (mv Map) JsonIndent(prefix, indent string, safeEncoding ...bool) ([]byte, error) {
|
||||
var s bool
|
||||
if len(safeEncoding) == 1 {
|
||||
s = safeEncoding[0]
|
||||
}
|
||||
|
||||
b, err := json.MarshalIndent(mv, prefix, indent)
|
||||
if !s {
|
||||
b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1)
|
||||
b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1)
|
||||
b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1)
|
||||
}
|
||||
return b, err
|
||||
}
|
||||
|
||||
// The following implementation is provided for symmetry with NewMapJsonReader[Raw]
|
||||
// The names will also provide a key for the number of return arguments.
|
||||
|
||||
// Writes the Map as JSON on the Writer.
|
||||
// If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved.
|
||||
func (mv Map) JsonWriter(jsonWriter io.Writer, safeEncoding ...bool) error {
|
||||
b, err := mv.Json(safeEncoding...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = jsonWriter.Write(b)
|
||||
return err
|
||||
}
|
||||
|
||||
// Writes the Map as JSON on the Writer. []byte is the raw JSON that was written.
|
||||
// If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved.
|
||||
func (mv Map) JsonWriterRaw(jsonWriter io.Writer, safeEncoding ...bool) ([]byte, error) {
|
||||
b, err := mv.Json(safeEncoding...)
|
||||
if err != nil {
|
||||
return b, err
|
||||
}
|
||||
|
||||
_, err = jsonWriter.Write(b)
|
||||
return b, err
|
||||
}
|
||||
|
||||
// Writes the Map as pretty JSON on the Writer.
|
||||
// If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved.
|
||||
func (mv Map) JsonIndentWriter(jsonWriter io.Writer, prefix, indent string, safeEncoding ...bool) error {
|
||||
b, err := mv.JsonIndent(prefix, indent, safeEncoding...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = jsonWriter.Write(b)
|
||||
return err
|
||||
}
|
||||
|
||||
// Writes the Map as pretty JSON on the Writer. []byte is the raw JSON that was written.
|
||||
// If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved.
|
||||
func (mv Map) JsonIndentWriterRaw(jsonWriter io.Writer, prefix, indent string, safeEncoding ...bool) ([]byte, error) {
|
||||
b, err := mv.JsonIndent(prefix, indent, safeEncoding...)
|
||||
if err != nil {
|
||||
return b, err
|
||||
}
|
||||
|
||||
_, err = jsonWriter.Write(b)
|
||||
return b, err
|
||||
}
|
||||
|
||||
// --------------------------- read JSON -----------------------------
|
||||
|
||||
// Parse numeric values as json.Number types - see encoding/json#Number
|
||||
var JsonUseNumber bool
|
||||
|
||||
// Just a wrapper on json.Unmarshal
|
||||
// Converting JSON to XML is a simple as:
|
||||
// ...
|
||||
// mapVal, merr := mxj.NewMapJson(jsonVal)
|
||||
// if merr != nil {
|
||||
// // handle error
|
||||
// }
|
||||
// xmlVal, xerr := mapVal.Xml()
|
||||
// if xerr != nil {
|
||||
// // handle error
|
||||
// }
|
||||
// NOTE: as a special case, passing a list, e.g., [{"some-null-value":"", "a-non-null-value":"bar"}],
|
||||
// will be interpreted as having the root key 'object' prepended - {"object":[ ... ]} - to unmarshal to a Map.
|
||||
// See mxj/j2x/j2x_test.go.
|
||||
func NewMapJson(jsonVal []byte) (Map, error) {
|
||||
// empty or nil begets empty
|
||||
if len(jsonVal) == 0 {
|
||||
m := make(map[string]interface{}, 0)
|
||||
return m, nil
|
||||
}
|
||||
// handle a goofy case ...
|
||||
if jsonVal[0] == '[' {
|
||||
jsonVal = []byte(`{"object":` + string(jsonVal) + `}`)
|
||||
}
|
||||
m := make(map[string]interface{})
|
||||
// err := json.Unmarshal(jsonVal, &m)
|
||||
buf := bytes.NewReader(jsonVal)
|
||||
dec := json.NewDecoder(buf)
|
||||
if JsonUseNumber {
|
||||
dec.UseNumber()
|
||||
}
|
||||
err := dec.Decode(&m)
|
||||
return m, err
|
||||
}
|
||||
|
||||
// Retrieve a Map value from an io.Reader.
|
||||
// NOTE: The raw JSON off the reader is buffered to []byte using a ByteReader. If the io.Reader is an
|
||||
// os.File, there may be significant performance impact. If the io.Reader is wrapping a []byte
|
||||
// value in-memory, however, such as http.Request.Body you CAN use it to efficiently unmarshal
|
||||
// a JSON object.
|
||||
func NewMapJsonReader(jsonReader io.Reader) (Map, error) {
|
||||
jb, err := getJson(jsonReader)
|
||||
if err != nil || len(*jb) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Unmarshal the 'presumed' JSON string
|
||||
return NewMapJson(*jb)
|
||||
}
|
||||
|
||||
// Retrieve a Map value and raw JSON - []byte - from an io.Reader.
|
||||
// NOTE: The raw JSON off the reader is buffered to []byte using a ByteReader. If the io.Reader is an
|
||||
// os.File, there may be significant performance impact. If the io.Reader is wrapping a []byte
|
||||
// value in-memory, however, such as http.Request.Body you CAN use it to efficiently unmarshal
|
||||
// a JSON object and retrieve the raw JSON in a single call.
|
||||
func NewMapJsonReaderRaw(jsonReader io.Reader) (Map, []byte, error) {
|
||||
jb, err := getJson(jsonReader)
|
||||
if err != nil || len(*jb) == 0 {
|
||||
return nil, *jb, err
|
||||
}
|
||||
|
||||
// Unmarshal the 'presumed' JSON string
|
||||
m, merr := NewMapJson(*jb)
|
||||
return m, *jb, merr
|
||||
}
|
||||
|
||||
// Pull the next JSON string off the stream: just read from first '{' to its closing '}'.
|
||||
// Returning a pointer to the slice saves 16 bytes - maybe unnecessary, but internal to package.
|
||||
func getJson(rdr io.Reader) (*[]byte, error) {
|
||||
bval := make([]byte, 1)
|
||||
jb := make([]byte, 0)
|
||||
var inQuote, inJson bool
|
||||
var parenCnt int
|
||||
var previous byte
|
||||
|
||||
// scan the input for a matched set of {...}
|
||||
// json.Unmarshal will handle syntax checking.
|
||||
for {
|
||||
_, err := rdr.Read(bval)
|
||||
if err != nil {
|
||||
if err == io.EOF && inJson && parenCnt > 0 {
|
||||
return &jb, fmt.Errorf("no closing } for JSON string: %s", string(jb))
|
||||
}
|
||||
return &jb, err
|
||||
}
|
||||
switch bval[0] {
|
||||
case '{':
|
||||
if !inQuote {
|
||||
parenCnt++
|
||||
inJson = true
|
||||
}
|
||||
case '}':
|
||||
if !inQuote {
|
||||
parenCnt--
|
||||
}
|
||||
if parenCnt < 0 {
|
||||
return nil, fmt.Errorf("closing } without opening {: %s", string(jb))
|
||||
}
|
||||
case '"':
|
||||
if inQuote {
|
||||
if previous == '\\' {
|
||||
break
|
||||
}
|
||||
inQuote = false
|
||||
} else {
|
||||
inQuote = true
|
||||
}
|
||||
case '\n', '\r', '\t', ' ':
|
||||
if !inQuote {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if inJson {
|
||||
jb = append(jb, bval[0])
|
||||
if parenCnt == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
previous = bval[0]
|
||||
}
|
||||
|
||||
return &jb, nil
|
||||
}
|
||||
|
||||
// ------------------------------- JSON Reader handler via Map values -----------------------
|
||||
|
||||
// Default poll delay to keep Handler from spinning on an open stream
|
||||
// like sitting on os.Stdin waiting for imput.
|
||||
var jhandlerPollInterval = time.Duration(1e6)
|
||||
|
||||
// While unnecessary, we make HandleJsonReader() have the same signature as HandleXmlReader().
|
||||
// This avoids treating one or other as a special case and discussing the underlying stdlib logic.
|
||||
|
||||
// Bulk process JSON using handlers that process a Map value.
|
||||
// 'rdr' is an io.Reader for the JSON (stream).
|
||||
// 'mapHandler' is the Map processing handler. Return of 'false' stops io.Reader processing.
|
||||
// 'errHandler' is the error processor. Return of 'false' stops io.Reader processing and returns the error.
|
||||
// Note: mapHandler() and errHandler() calls are blocking, so reading and processing of messages is serialized.
|
||||
// This means that you can stop reading the file on error or after processing a particular message.
|
||||
// To have reading and handling run concurrently, pass argument to a go routine in handler and return 'true'.
|
||||
func HandleJsonReader(jsonReader io.Reader, mapHandler func(Map) bool, errHandler func(error) bool) error {
|
||||
var n int
|
||||
for {
|
||||
m, merr := NewMapJsonReader(jsonReader)
|
||||
n++
|
||||
|
||||
// handle error condition with errhandler
|
||||
if merr != nil && merr != io.EOF {
|
||||
merr = fmt.Errorf("[jsonReader: %d] %s", n, merr.Error())
|
||||
if ok := errHandler(merr); !ok {
|
||||
// caused reader termination
|
||||
return merr
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// pass to maphandler
|
||||
if len(m) != 0 {
|
||||
if ok := mapHandler(m); !ok {
|
||||
break
|
||||
}
|
||||
} else if merr != io.EOF {
|
||||
<-time.After(jhandlerPollInterval)
|
||||
}
|
||||
|
||||
if merr == io.EOF {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Bulk process JSON using handlers that process a Map value and the raw JSON.
|
||||
// 'rdr' is an io.Reader for the JSON (stream).
|
||||
// 'mapHandler' is the Map and raw JSON - []byte - processor. Return of 'false' stops io.Reader processing.
|
||||
// 'errHandler' is the error and raw JSON processor. Return of 'false' stops io.Reader processing and returns the error.
|
||||
// Note: mapHandler() and errHandler() calls are blocking, so reading and processing of messages is serialized.
|
||||
// This means that you can stop reading the file on error or after processing a particular message.
|
||||
// To have reading and handling run concurrently, pass argument(s) to a go routine in handler and return 'true'.
|
||||
func HandleJsonReaderRaw(jsonReader io.Reader, mapHandler func(Map, []byte) bool, errHandler func(error, []byte) bool) error {
|
||||
var n int
|
||||
for {
|
||||
m, raw, merr := NewMapJsonReaderRaw(jsonReader)
|
||||
n++
|
||||
|
||||
// handle error condition with errhandler
|
||||
if merr != nil && merr != io.EOF {
|
||||
merr = fmt.Errorf("[jsonReader: %d] %s", n, merr.Error())
|
||||
if ok := errHandler(merr, raw); !ok {
|
||||
// caused reader termination
|
||||
return merr
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// pass to maphandler
|
||||
if len(m) != 0 {
|
||||
if ok := mapHandler(m, raw); !ok {
|
||||
break
|
||||
}
|
||||
} else if merr != io.EOF {
|
||||
<-time.After(jhandlerPollInterval)
|
||||
}
|
||||
|
||||
if merr == io.EOF {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
-137
@@ -1,137 +0,0 @@
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var jdata = []byte(`{ "key1":"string", "key2":34, "key3":true, "key4":"unsafe: <>&", "key5":null }`)
|
||||
var jdata2 = []byte(`{ "key1":"string", "key2":34, "key3":true, "key4":"unsafe: <>&" },
|
||||
{ "key":"value in new JSON string" }`)
|
||||
|
||||
func TestJsonHeader(t *testing.T) {
|
||||
fmt.Println("\n---------------- json_test.go ...\n")
|
||||
}
|
||||
|
||||
func TestNewMapJson(t *testing.T) {
|
||||
|
||||
m, merr := NewMapJson(jdata)
|
||||
if merr != nil {
|
||||
t.Fatal("NewMapJson, merr:", merr.Error())
|
||||
}
|
||||
|
||||
fmt.Println("NewMapJson, jdata:", string(jdata))
|
||||
fmt.Printf("NewMapJson, m : %#v\n", m)
|
||||
}
|
||||
|
||||
func TestNewMapJsonNumber(t *testing.T) {
|
||||
|
||||
JsonUseNumber = true
|
||||
|
||||
m, merr := NewMapJson(jdata)
|
||||
if merr != nil {
|
||||
t.Fatal("NewMapJson, merr:", merr.Error())
|
||||
}
|
||||
|
||||
fmt.Println("NewMapJson, jdata:", string(jdata))
|
||||
fmt.Printf("NewMapJson, m : %#v\n", m)
|
||||
|
||||
JsonUseNumber = false
|
||||
}
|
||||
|
||||
func TestNewMapJsonError(t *testing.T) {
|
||||
|
||||
m, merr := NewMapJson(jdata[:len(jdata)-2])
|
||||
if merr == nil {
|
||||
t.Fatal("NewMapJsonError, m:", m)
|
||||
}
|
||||
|
||||
fmt.Println("NewMapJsonError, jdata :", string(jdata[:len(jdata)-2]))
|
||||
fmt.Println("NewMapJsonError, merror:", merr.Error())
|
||||
|
||||
newData := []byte(`{ "this":"is", "in":error }`)
|
||||
m, merr = NewMapJson(newData)
|
||||
if merr == nil {
|
||||
t.Fatal("NewMapJsonError, m:", m)
|
||||
}
|
||||
|
||||
fmt.Println("NewMapJsonError, newData :", string(newData))
|
||||
fmt.Println("NewMapJsonError, merror :", merr.Error())
|
||||
}
|
||||
|
||||
func TestNewMapJsonReader(t *testing.T) {
|
||||
|
||||
rdr := bytes.NewBuffer(jdata2)
|
||||
|
||||
for {
|
||||
m, jb, merr := NewMapJsonReaderRaw(rdr)
|
||||
if merr != nil && merr != io.EOF {
|
||||
t.Fatal("NewMapJsonReader, merr:", merr.Error())
|
||||
}
|
||||
if merr == io.EOF {
|
||||
break
|
||||
}
|
||||
|
||||
fmt.Println("NewMapJsonReader, jb:", string(jb))
|
||||
fmt.Printf("NewMapJsonReader, m : %#v\n", m)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMapJsonReaderNumber(t *testing.T) {
|
||||
|
||||
JsonUseNumber = true
|
||||
|
||||
rdr := bytes.NewBuffer(jdata2)
|
||||
|
||||
for {
|
||||
m, jb, merr := NewMapJsonReaderRaw(rdr)
|
||||
if merr != nil && merr != io.EOF {
|
||||
t.Fatal("NewMapJsonReader, merr:", merr.Error())
|
||||
}
|
||||
if merr == io.EOF {
|
||||
break
|
||||
}
|
||||
|
||||
fmt.Println("NewMapJsonReader, jb:", string(jb))
|
||||
fmt.Printf("NewMapJsonReader, m : %#v\n", m)
|
||||
}
|
||||
|
||||
JsonUseNumber = false
|
||||
}
|
||||
|
||||
func TestJson(t *testing.T) {
|
||||
|
||||
m, _ := NewMapJson(jdata)
|
||||
|
||||
j, jerr := m.Json()
|
||||
if jerr != nil {
|
||||
t.Fatal("Json, jerr:", jerr.Error())
|
||||
}
|
||||
|
||||
fmt.Println("Json, jdata:", string(jdata))
|
||||
fmt.Println("Json, j :", string(j))
|
||||
|
||||
j, _ = m.Json(true)
|
||||
fmt.Println("Json, j safe:", string(j))
|
||||
}
|
||||
|
||||
func TestJsonWriter(t *testing.T) {
|
||||
mv := Map(map[string]interface{}{"this": "is a", "float": 3.14159, "and": "a", "bool": true})
|
||||
|
||||
w := new(bytes.Buffer)
|
||||
raw, err := mv.JsonWriterRaw(w)
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
}
|
||||
|
||||
b := make([]byte, w.Len())
|
||||
_, err = w.Read(b)
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
}
|
||||
|
||||
fmt.Println("JsonWriter, raw:", string(raw))
|
||||
fmt.Println("JsonWriter, b :", string(b))
|
||||
}
|
||||
-658
@@ -1,658 +0,0 @@
|
||||
// Copyright 2012-2014 Charles Banning. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file
|
||||
|
||||
// keyvalues.go: Extract values from an arbitrary XML doc. Tag path can include wildcard characters.
|
||||
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ----------------------------- get everything FOR a single key -------------------------
|
||||
|
||||
const (
|
||||
minArraySize = 32
|
||||
)
|
||||
|
||||
var defaultArraySize int = minArraySize
|
||||
|
||||
// Adjust the buffers for expected number of values to return from ValuesForKey() and ValuesForPath().
|
||||
// This can have the effect of significantly reducing memory allocation-copy functions for large data sets.
|
||||
// Returns the initial buffer size.
|
||||
func SetArraySize(size int) int {
|
||||
if size > minArraySize {
|
||||
defaultArraySize = size
|
||||
} else {
|
||||
defaultArraySize = minArraySize
|
||||
}
|
||||
return defaultArraySize
|
||||
}
|
||||
|
||||
// Return all values in Map, 'mv', associated with a 'key'. If len(returned_values) == 0, then no match.
|
||||
// On error, the returned array is 'nil'. NOTE: 'key' can be wildcard, "*".
|
||||
// 'subkeys' (optional) are "key:val[:type]" strings representing attributes or elements in a list.
|
||||
// - By default 'val' is of type string. "key:val:bool" and "key:val:float" to coerce them.
|
||||
// - For attributes prefix the label with a hyphen, '-', e.g., "-seq:3".
|
||||
// - If the 'key' refers to a list, then "key:value" could select a list member of the list.
|
||||
// - The subkey can be wildcarded - "key:*" - to require that it's there with some value.
|
||||
// - If a subkey is preceeded with the '!' character, the key:value[:type] entry is treated as an
|
||||
// exclusion critera - e.g., "!author:William T. Gaddis".
|
||||
func (mv Map) ValuesForKey(key string, subkeys ...string) ([]interface{}, error) {
|
||||
m := map[string]interface{}(mv)
|
||||
var subKeyMap map[string]interface{}
|
||||
if len(subkeys) > 0 {
|
||||
var err error
|
||||
subKeyMap, err = getSubKeyMap(subkeys...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
ret := make([]interface{}, 0, defaultArraySize)
|
||||
var cnt int
|
||||
hasKey(m, key, &ret, &cnt, subKeyMap)
|
||||
return ret[:cnt], nil
|
||||
// ret := make([]interface{}, 0)
|
||||
// hasKey(m, key, &ret, subKeyMap)
|
||||
// return ret, nil
|
||||
}
|
||||
|
||||
// hasKey - if the map 'key' exists append it to array
|
||||
// if it doesn't do nothing except scan array and map values
|
||||
func hasKey(iv interface{}, key string, ret *[]interface{}, cnt *int, subkeys map[string]interface{}) {
|
||||
// func hasKey(iv interface{}, key string, ret *[]interface{}, subkeys map[string]interface{}) {
|
||||
switch iv.(type) {
|
||||
case map[string]interface{}:
|
||||
vv := iv.(map[string]interface{})
|
||||
// see if the current value is of interest
|
||||
if v, ok := vv[key]; ok {
|
||||
switch v.(type) {
|
||||
case map[string]interface{}:
|
||||
if hasSubKeys(v, subkeys) {
|
||||
*ret = append(*ret, v)
|
||||
*cnt++
|
||||
}
|
||||
case []interface{}:
|
||||
for _, av := range v.([]interface{}) {
|
||||
if hasSubKeys(av, subkeys) {
|
||||
*ret = append(*ret, av)
|
||||
*cnt++
|
||||
}
|
||||
}
|
||||
default:
|
||||
if len(subkeys) == 0 {
|
||||
*ret = append(*ret, v)
|
||||
*cnt++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// wildcard case
|
||||
if key == "*" {
|
||||
for _, v := range vv {
|
||||
switch v.(type) {
|
||||
case map[string]interface{}:
|
||||
if hasSubKeys(v, subkeys) {
|
||||
*ret = append(*ret, v)
|
||||
*cnt++
|
||||
}
|
||||
case []interface{}:
|
||||
for _, av := range v.([]interface{}) {
|
||||
if hasSubKeys(av, subkeys) {
|
||||
*ret = append(*ret, av)
|
||||
*cnt++
|
||||
}
|
||||
}
|
||||
default:
|
||||
if len(subkeys) == 0 {
|
||||
*ret = append(*ret, v)
|
||||
*cnt++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// scan the rest
|
||||
for _, v := range vv {
|
||||
hasKey(v, key, ret, cnt, subkeys)
|
||||
// hasKey(v, key, ret, subkeys)
|
||||
}
|
||||
case []interface{}:
|
||||
for _, v := range iv.([]interface{}) {
|
||||
hasKey(v, key, ret, cnt, subkeys)
|
||||
// hasKey(v, key, ret, subkeys)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------- get everything for a node in the Map ---------------------------
|
||||
|
||||
// Allow indexed arrays in "path" specification. (Request from Abhijit Kadam - abhijitk100@gmail.com.)
|
||||
// 2014.04.28 - implementation note.
|
||||
// Implemented as a wrapper of (old)ValuesForPath() because we need look-ahead logic to handle expansion
|
||||
// of wildcards and unindexed arrays. Embedding such logic into valuesForKeyPath() would have made the
|
||||
// code much more complicated; this wrapper is straightforward, easy to debug, and doesn't add significant overhead.
|
||||
|
||||
// Retrieve all values for a path from the Map. If len(returned_values) == 0, then no match.
|
||||
// On error, the returned array is 'nil'.
|
||||
// 'path' is a dot-separated path of key values.
|
||||
// - If a node in the path is '*', then everything beyond is walked.
|
||||
// - 'path' can contain indexed array references, such as, "*.data[1]" and "msgs[2].data[0].field" -
|
||||
// even "*[2].*[0].field".
|
||||
// 'subkeys' (optional) are "key:val[:type]" strings representing attributes or elements in a list.
|
||||
// - By default 'val' is of type string. "key:val:bool" and "key:val:float" to coerce them.
|
||||
// - For attributes prefix the label with a hyphen, '-', e.g., "-seq:3".
|
||||
// - If the 'path' refers to a list, then "tag:value" would return member of the list.
|
||||
// - The subkey can be wildcarded - "key:*" - to require that it's there with some value.
|
||||
// - If a subkey is preceeded with the '!' character, the key:value[:type] entry is treated as an
|
||||
// exclusion critera - e.g., "!author:William T. Gaddis".
|
||||
func (mv Map) ValuesForPath(path string, subkeys ...string) ([]interface{}, error) {
|
||||
// If there are no array indexes in path, use legacy ValuesForPath() logic.
|
||||
if strings.Index(path, "[") < 0 {
|
||||
return mv.oldValuesForPath(path, subkeys...)
|
||||
}
|
||||
|
||||
var subKeyMap map[string]interface{}
|
||||
if len(subkeys) > 0 {
|
||||
var err error
|
||||
subKeyMap, err = getSubKeyMap(subkeys...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
keys, kerr := parsePath(path)
|
||||
if kerr != nil {
|
||||
return nil, kerr
|
||||
}
|
||||
|
||||
vals, verr := valuesForArray(keys, mv)
|
||||
if verr != nil {
|
||||
return nil, verr // Vals may be nil, but return empty array.
|
||||
}
|
||||
|
||||
// Need to handle subkeys ... only return members of vals that satisfy conditions.
|
||||
retvals := make([]interface{}, 0)
|
||||
for _, v := range vals {
|
||||
if hasSubKeys(v, subKeyMap) {
|
||||
retvals = append(retvals, v)
|
||||
}
|
||||
}
|
||||
return retvals, nil
|
||||
}
|
||||
|
||||
func valuesForArray(keys []*key, m Map) ([]interface{}, error) {
|
||||
var tmppath string
|
||||
var haveFirst bool
|
||||
var vals []interface{}
|
||||
var verr error
|
||||
|
||||
lastkey := len(keys) - 1
|
||||
for i := 0; i <= lastkey; i++ {
|
||||
if !haveFirst {
|
||||
tmppath = keys[i].name
|
||||
haveFirst = true
|
||||
} else {
|
||||
tmppath += "." + keys[i].name
|
||||
}
|
||||
|
||||
// Look-ahead: explode wildcards and unindexed arrays.
|
||||
// Need to handle un-indexed list recursively:
|
||||
// e.g., path is "stuff.data[0]" rather than "stuff[0].data[0]".
|
||||
// Need to treat it as "stuff[0].data[0]", "stuff[1].data[0]", ...
|
||||
if !keys[i].isArray && i < lastkey && keys[i+1].isArray {
|
||||
// Can't pass subkeys because we may not be at literal end of path.
|
||||
vv, vverr := m.oldValuesForPath(tmppath)
|
||||
if vverr != nil {
|
||||
return nil, vverr
|
||||
}
|
||||
for _, v := range vv {
|
||||
// See if we can walk the value.
|
||||
am, ok := v.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// Work the backend.
|
||||
nvals, nvalserr := valuesForArray(keys[i+1:], Map(am))
|
||||
if nvalserr != nil {
|
||||
return nil, nvalserr
|
||||
}
|
||||
vals = append(vals, nvals...)
|
||||
}
|
||||
break // have recursed the whole path - return
|
||||
}
|
||||
|
||||
if keys[i].isArray || i == lastkey {
|
||||
// Don't pass subkeys because may not be at literal end of path.
|
||||
vals, verr = m.oldValuesForPath(tmppath)
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
if verr != nil {
|
||||
return nil, verr
|
||||
}
|
||||
|
||||
if i == lastkey && !keys[i].isArray {
|
||||
break
|
||||
}
|
||||
|
||||
// Now we're looking at an array - supposedly.
|
||||
// Is index in range of vals?
|
||||
if len(vals) <= keys[i].position {
|
||||
vals = nil
|
||||
break
|
||||
}
|
||||
|
||||
// Return the array member of interest, if at end of path.
|
||||
if i == lastkey {
|
||||
vals = vals[keys[i].position:(keys[i].position + 1)]
|
||||
break
|
||||
}
|
||||
|
||||
// Extract the array member of interest.
|
||||
am := vals[keys[i].position:(keys[i].position + 1)]
|
||||
|
||||
// must be a map[string]interface{} value so we can keep walking the path
|
||||
amm, ok := am[0].(map[string]interface{})
|
||||
if !ok {
|
||||
vals = nil
|
||||
break
|
||||
}
|
||||
|
||||
m = Map(amm)
|
||||
haveFirst = false
|
||||
}
|
||||
|
||||
return vals, nil
|
||||
}
|
||||
|
||||
type key struct {
|
||||
name string
|
||||
isArray bool
|
||||
position int
|
||||
}
|
||||
|
||||
func parsePath(s string) ([]*key, error) {
|
||||
keys := strings.Split(s, ".")
|
||||
|
||||
ret := make([]*key, 0)
|
||||
|
||||
for i := 0; i < len(keys); i++ {
|
||||
if keys[i] == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
newkey := new(key)
|
||||
if strings.Index(keys[i], "[") < 0 {
|
||||
newkey.name = keys[i]
|
||||
ret = append(ret, newkey)
|
||||
continue
|
||||
}
|
||||
|
||||
p := strings.Split(keys[i], "[")
|
||||
newkey.name = p[0]
|
||||
p = strings.Split(p[1], "]")
|
||||
if p[0] == "" { // no right bracket
|
||||
return nil, fmt.Errorf("no right bracket on key index: %s", keys[i])
|
||||
}
|
||||
// convert p[0] to a int value
|
||||
pos, nerr := strconv.ParseInt(p[0], 10, 32)
|
||||
if nerr != nil {
|
||||
return nil, fmt.Errorf("cannot convert index to int value: %s", p[0])
|
||||
}
|
||||
newkey.position = int(pos)
|
||||
newkey.isArray = true
|
||||
ret = append(ret, newkey)
|
||||
}
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
// legacy ValuesForPath() - now wrapped to handle special case of indexed arrays in 'path'.
|
||||
func (mv Map) oldValuesForPath(path string, subkeys ...string) ([]interface{}, error) {
|
||||
m := map[string]interface{}(mv)
|
||||
var subKeyMap map[string]interface{}
|
||||
if len(subkeys) > 0 {
|
||||
var err error
|
||||
subKeyMap, err = getSubKeyMap(subkeys...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
keys := strings.Split(path, ".")
|
||||
if keys[len(keys)-1] == "" {
|
||||
keys = keys[:len(keys)-1]
|
||||
}
|
||||
// ivals := make([]interface{}, 0)
|
||||
// valuesForKeyPath(&ivals, m, keys, subKeyMap)
|
||||
// return ivals, nil
|
||||
ivals := make([]interface{}, 0, defaultArraySize)
|
||||
var cnt int
|
||||
valuesForKeyPath(&ivals, &cnt, m, keys, subKeyMap)
|
||||
return ivals[:cnt], nil
|
||||
}
|
||||
|
||||
func valuesForKeyPath(ret *[]interface{}, cnt *int, m interface{}, keys []string, subkeys map[string]interface{}) {
|
||||
lenKeys := len(keys)
|
||||
|
||||
// load 'm' values into 'ret'
|
||||
// expand any lists
|
||||
if lenKeys == 0 {
|
||||
switch m.(type) {
|
||||
case map[string]interface{}:
|
||||
if subkeys != nil {
|
||||
if ok := hasSubKeys(m, subkeys); !ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
*ret = append(*ret, m)
|
||||
*cnt++
|
||||
case []interface{}:
|
||||
for i, v := range m.([]interface{}) {
|
||||
if subkeys != nil {
|
||||
if ok := hasSubKeys(v, subkeys); !ok {
|
||||
continue // only load list members with subkeys
|
||||
}
|
||||
}
|
||||
*ret = append(*ret, (m.([]interface{}))[i])
|
||||
*cnt++
|
||||
}
|
||||
default:
|
||||
if subkeys != nil {
|
||||
return // must be map[string]interface{} if there are subkeys
|
||||
}
|
||||
*ret = append(*ret, m)
|
||||
*cnt++
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// key of interest
|
||||
key := keys[0]
|
||||
switch key {
|
||||
case "*": // wildcard - scan all values
|
||||
switch m.(type) {
|
||||
case map[string]interface{}:
|
||||
for _, v := range m.(map[string]interface{}) {
|
||||
// valuesForKeyPath(ret, v, keys[1:], subkeys)
|
||||
valuesForKeyPath(ret, cnt, v, keys[1:], subkeys)
|
||||
}
|
||||
case []interface{}:
|
||||
for _, v := range m.([]interface{}) {
|
||||
switch v.(type) {
|
||||
// flatten out a list of maps - keys are processed
|
||||
case map[string]interface{}:
|
||||
for _, vv := range v.(map[string]interface{}) {
|
||||
// valuesForKeyPath(ret, vv, keys[1:], subkeys)
|
||||
valuesForKeyPath(ret, cnt, vv, keys[1:], subkeys)
|
||||
}
|
||||
default:
|
||||
// valuesForKeyPath(ret, v, keys[1:], subkeys)
|
||||
valuesForKeyPath(ret, cnt, v, keys[1:], subkeys)
|
||||
}
|
||||
}
|
||||
}
|
||||
default: // key - must be map[string]interface{}
|
||||
switch m.(type) {
|
||||
case map[string]interface{}:
|
||||
if v, ok := m.(map[string]interface{})[key]; ok {
|
||||
// valuesForKeyPath(ret, v, keys[1:], subkeys)
|
||||
valuesForKeyPath(ret, cnt, v, keys[1:], subkeys)
|
||||
}
|
||||
case []interface{}: // may be buried in list
|
||||
for _, v := range m.([]interface{}) {
|
||||
switch v.(type) {
|
||||
case map[string]interface{}:
|
||||
if vv, ok := v.(map[string]interface{})[key]; ok {
|
||||
// valuesForKeyPath(ret, vv, keys[1:], subkeys)
|
||||
valuesForKeyPath(ret, cnt, vv, keys[1:], subkeys)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// hasSubKeys() - interface{} equality works for string, float64, bool
|
||||
// 'v' must be a map[string]interface{} value to have subkeys
|
||||
// 'a' can have k:v pairs with v.(string) == "*", which is treated like a wildcard.
|
||||
func hasSubKeys(v interface{}, subkeys map[string]interface{}) bool {
|
||||
if len(subkeys) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
switch v.(type) {
|
||||
case map[string]interface{}:
|
||||
// do all subKey name:value pairs match?
|
||||
mv := v.(map[string]interface{})
|
||||
for skey, sval := range subkeys {
|
||||
isNotKey := false
|
||||
if skey[:1] == "!" { // a NOT-key
|
||||
skey = skey[1:]
|
||||
isNotKey = true
|
||||
}
|
||||
vv, ok := mv[skey]
|
||||
if !ok { // key doesn't exist
|
||||
if isNotKey { // key not there, but that's what we want
|
||||
if kv, ok := sval.(string); ok && kv == "*" {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
// wildcard check
|
||||
if kv, ok := sval.(string); ok && kv == "*" {
|
||||
if isNotKey { // key is there, and we don't want it
|
||||
return false
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch sval.(type) {
|
||||
case string:
|
||||
if s, ok := vv.(string); ok && s == sval.(string) {
|
||||
if isNotKey {
|
||||
return false
|
||||
}
|
||||
continue
|
||||
}
|
||||
case bool:
|
||||
if b, ok := vv.(bool); ok && b == sval.(bool) {
|
||||
if isNotKey {
|
||||
return false
|
||||
}
|
||||
continue
|
||||
}
|
||||
case float64:
|
||||
if f, ok := vv.(float64); ok && f == sval.(float64) {
|
||||
if isNotKey {
|
||||
return false
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
// key there but didn't match subkey value
|
||||
if isNotKey { // that's what we want
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
// all subkeys matched
|
||||
return true
|
||||
}
|
||||
|
||||
// not a map[string]interface{} value, can't have subkeys
|
||||
return false
|
||||
}
|
||||
|
||||
// Generate map of key:value entries as map[string]string.
|
||||
// 'kv' arguments are "name:value" pairs: attribute keys are designated with prepended hyphen, '-'.
|
||||
// If len(kv) == 0, the return is (nil, nil).
|
||||
func getSubKeyMap(kv ...string) (map[string]interface{}, error) {
|
||||
if len(kv) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
m := make(map[string]interface{}, 0)
|
||||
for _, v := range kv {
|
||||
vv := strings.Split(v, ":")
|
||||
switch len(vv) {
|
||||
case 2:
|
||||
m[vv[0]] = interface{}(vv[1])
|
||||
case 3:
|
||||
switch vv[3] {
|
||||
case "string", "char", "text":
|
||||
m[vv[0]] = interface{}(vv[1])
|
||||
case "bool", "boolean":
|
||||
// ParseBool treats "1"==true & "0"==false
|
||||
b, err := strconv.ParseBool(vv[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't convert subkey value to bool: %s", vv[1])
|
||||
}
|
||||
m[vv[0]] = interface{}(b)
|
||||
case "float", "float64", "num", "number", "numeric":
|
||||
f, err := strconv.ParseFloat(vv[1], 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't convert subkey value to float: %s", vv[1])
|
||||
}
|
||||
m[vv[0]] = interface{}(f)
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown subkey conversion spec: %s", v)
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown subkey spec: %s", v)
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// ------------------------------- END of valuesFor ... ----------------------------
|
||||
|
||||
// ----------------------- locate where a key value is in the tree -------------------
|
||||
|
||||
//----------------------------- find all paths to a key --------------------------------
|
||||
|
||||
// Get all paths through Map, 'mv', (in dot-notation) that terminate with the specified key.
|
||||
// Results can be used with ValuesForPath.
|
||||
func (mv Map) PathsForKey(key string) []string {
|
||||
m := map[string]interface{}(mv)
|
||||
breadbasket := make(map[string]bool, 0)
|
||||
breadcrumbs := ""
|
||||
|
||||
hasKeyPath(breadcrumbs, m, key, breadbasket)
|
||||
if len(breadbasket) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// unpack map keys to return
|
||||
res := make([]string, len(breadbasket))
|
||||
var i int
|
||||
for k := range breadbasket {
|
||||
res[i] = k
|
||||
i++
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// Extract the shortest path from all possible paths - from PathsForKey() - in Map, 'mv'..
|
||||
// Paths are strings using dot-notation.
|
||||
func (mv Map) PathForKeyShortest(key string) string {
|
||||
paths := mv.PathsForKey(key)
|
||||
|
||||
lp := len(paths)
|
||||
if lp == 0 {
|
||||
return ""
|
||||
}
|
||||
if lp == 1 {
|
||||
return paths[0]
|
||||
}
|
||||
|
||||
shortest := paths[0]
|
||||
shortestLen := len(strings.Split(shortest, "."))
|
||||
|
||||
for i := 1; i < len(paths); i++ {
|
||||
vlen := len(strings.Split(paths[i], "."))
|
||||
if vlen < shortestLen {
|
||||
shortest = paths[i]
|
||||
shortestLen = vlen
|
||||
}
|
||||
}
|
||||
|
||||
return shortest
|
||||
}
|
||||
|
||||
// hasKeyPath - if the map 'key' exists append it to KeyPath.path and increment KeyPath.depth
|
||||
// This is really just a breadcrumber that saves all trails that hit the prescribed 'key'.
|
||||
func hasKeyPath(crumbs string, iv interface{}, key string, basket map[string]bool) {
|
||||
switch iv.(type) {
|
||||
case map[string]interface{}:
|
||||
vv := iv.(map[string]interface{})
|
||||
if _, ok := vv[key]; ok {
|
||||
if crumbs == "" {
|
||||
crumbs = key
|
||||
} else {
|
||||
crumbs += "." + key
|
||||
}
|
||||
// *basket = append(*basket, crumb)
|
||||
basket[crumbs] = true
|
||||
}
|
||||
// walk on down the path, key could occur again at deeper node
|
||||
for k, v := range vv {
|
||||
// create a new breadcrumb, intialized with the one we have
|
||||
var nbc string
|
||||
if crumbs == "" {
|
||||
nbc = k
|
||||
} else {
|
||||
nbc = crumbs + "." + k
|
||||
}
|
||||
hasKeyPath(nbc, v, key, basket)
|
||||
}
|
||||
case []interface{}:
|
||||
// crumb-trail doesn't change, pass it on
|
||||
for _, v := range iv.([]interface{}) {
|
||||
hasKeyPath(crumbs, v, key, basket)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the first found value for the path.
|
||||
func (mv Map) ValueForPath(path string) (interface{}, error) {
|
||||
vals, err := mv.ValuesForPath(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(vals) == 0 {
|
||||
return nil, errors.New("ValueForPath: path not found")
|
||||
}
|
||||
return vals[0], nil
|
||||
}
|
||||
|
||||
// Returns the first found value for the path as a string.
|
||||
func (mv Map) ValueForPathString(path string) (string, error) {
|
||||
vals, err := mv.ValuesForPath(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(vals) == 0 {
|
||||
return "", errors.New("ValueForPath: path not found")
|
||||
}
|
||||
val := vals[0]
|
||||
switch str := val.(type) {
|
||||
case string:
|
||||
return str, nil
|
||||
default:
|
||||
return "", fmt.Errorf("ValueForPath: unsupported type: %T", str)
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the first found value for the path as a string.
|
||||
// If the path is not found then it returns an empty string.
|
||||
func (mv Map) ValueOrEmptyForPathString(path string) string {
|
||||
str, _ := mv.ValueForPathString(path)
|
||||
return str
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user