当前位置: 首页>>代码示例>>Golang>>正文


Golang jsonutil.DecodeJSON函数代码示例

本文整理汇总了Golang中github.com/hashicorp/vault/helper/jsonutil.DecodeJSON函数的典型用法代码示例。如果您正苦于以下问题:Golang DecodeJSON函数的具体用法?Golang DecodeJSON怎么用?Golang DecodeJSON使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了DecodeJSON函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: getDuoAuthClient

func getDuoAuthClient(data *MockClientData) AuthClient {
	var c MockAuthClient
	// set default response to be successful
	preauthSuccessJSON := `
	{
	  "Stat": "OK",
	  "Response": {
	    "Result": "auth",
	    "Status_Msg": "Needs authentication",
	    "Devices": []
	  }
	}`
	if data.PreauthData == nil {
		data.PreauthData = &authapi.PreauthResult{}
		jsonutil.DecodeJSON([]byte(preauthSuccessJSON), data.PreauthData)
	}

	authSuccessJSON := `
	{
	  "Stat": "OK",
	  "Response": {
	    "Result": "allow"
	  }
	}`
	if data.AuthData == nil {
		data.AuthData = &authapi.AuthResult{}
		jsonutil.DecodeJSON([]byte(authSuccessJSON), data.AuthData)
	}

	c.MockData = data
	return &c
}
开发者ID:quixoten,项目名称:vault,代码行数:32,代码来源:duo_test.go

示例2: TestFormatJSON_formatRequest

func TestFormatJSON_formatRequest(t *testing.T) {
	cases := map[string]struct {
		Auth   *logical.Auth
		Req    *logical.Request
		Err    error
		Result string
	}{
		"auth, request": {
			&logical.Auth{ClientToken: "foo", Policies: []string{"root"}},
			&logical.Request{
				Operation: logical.UpdateOperation,
				Path:      "/foo",
				Connection: &logical.Connection{
					RemoteAddr: "127.0.0.1",
				},
				WrapTTL: 60 * time.Second,
			},
			errors.New("this is an error"),
			testFormatJSONReqBasicStr,
		},
	}

	for name, tc := range cases {
		var buf bytes.Buffer
		formatter := AuditFormatter{
			AuditFormatWriter: &JSONFormatWriter{},
		}
		salter, _ := salt.NewSalt(nil, nil)
		config := FormatterConfig{
			Salt: salter,
		}
		if err := formatter.FormatRequest(&buf, config, tc.Auth, tc.Req, tc.Err); err != nil {
			t.Fatalf("bad: %s\nerr: %s", name, err)
		}

		var expectedjson = new(AuditRequestEntry)
		if err := jsonutil.DecodeJSON([]byte(tc.Result), &expectedjson); err != nil {
			t.Fatalf("bad json: %s", err)
		}

		var actualjson = new(AuditRequestEntry)
		if err := jsonutil.DecodeJSON([]byte(buf.String()), &actualjson); err != nil {
			t.Fatalf("bad json: %s", err)
		}

		expectedjson.Time = actualjson.Time

		expectedBytes, err := json.Marshal(expectedjson)
		if err != nil {
			t.Fatalf("unable to marshal json: %s", err)
		}

		if strings.TrimSpace(buf.String()) != string(expectedBytes) {
			t.Fatalf(
				"bad: %s\nResult:\n\n'%s'\n\nExpected:\n\n'%s'",
				name, buf.String(), string(expectedBytes))
		}
	}
}
开发者ID:quixoten,项目名称:vault,代码行数:59,代码来源:format_json_test.go

示例3: DeserializeKey

// DeserializeKey is used to deserialize and return a new key
func DeserializeKey(buf []byte) (*Key, error) {
	k := new(Key)
	if err := jsonutil.DecodeJSON(buf, k); err != nil {
		return nil, fmt.Errorf("deserialization failed: %v", err)
	}
	return k, nil
}
开发者ID:quixoten,项目名称:vault,代码行数:8,代码来源:keyring.go

示例4: handleRead

func (b *CubbyholeBackend) handleRead(
	req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	if req.ClientToken == "" {
		return nil, fmt.Errorf("cubbyhole read: client token empty")
	}

	// Read the path
	out, err := req.Storage.Get(req.ClientToken + "/" + req.Path)
	if err != nil {
		return nil, fmt.Errorf("read failed: %v", err)
	}

	// Fast-path the no data case
	if out == nil {
		return nil, nil
	}

	// Decode the data
	var rawData map[string]interface{}
	if err := jsonutil.DecodeJSON(out.Value, &rawData); err != nil {
		return nil, fmt.Errorf("json decoding failed: %v", err)
	}

	// Generate the response
	resp := &logical.Response{
		Data: rawData,
	}

	return resp, nil
}
开发者ID:quixoten,项目名称:vault,代码行数:30,代码来源:logical_cubbyhole.go

示例5: TestDuoHandlerReject

func TestDuoHandlerReject(t *testing.T) {
	AuthData := &authapi.AuthResult{}
	authRejectJSON := `
	{
	  "Stat": "OK",
	  "Response": {
	    "Result": "deny",
	    "Status_Msg": "Invalid auth"
	  }
	}`
	jsonutil.DecodeJSON([]byte(authRejectJSON), AuthData)
	successResp := &logical.Response{
		Auth: &logical.Auth{},
	}
	expectedError := AuthData.Response.Status_Msg
	duoConfig := &DuoConfig{
		UsernameFormat: "%s",
	}
	duoAuthClient := getDuoAuthClient(&MockClientData{
		AuthData: AuthData,
	})
	resp, err := duoHandler(duoConfig, duoAuthClient, &duoAuthRequest{
		successResp: successResp,
		username:    "user",
	})
	if err != nil {
		t.Fatalf(err.Error())
	}
	error, ok := resp.Data["error"].(string)
	if !ok || !strings.Contains(error, expectedError) {
		t.Fatalf("Testing Duo authentication gave incorrect response (expected deny, got: %v)", error)
	}
}
开发者ID:quixoten,项目名称:vault,代码行数:33,代码来源:duo_test.go

示例6: pathRoleUpdate

// Registers a new role with the backend
func (b *backend) pathRoleUpdate(req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	name := d.Get("name").(string)
	if name == "" {
		return logical.ErrorResponse("missing name"), nil
	}

	tags := d.Get("tags").(string)
	rawVHosts := d.Get("vhosts").(string)

	if tags == "" && rawVHosts == "" {
		return logical.ErrorResponse("both tags and vhosts not specified"), nil
	}

	var vhosts map[string]vhostPermission
	if len(rawVHosts) > 0 {
		if err := jsonutil.DecodeJSON([]byte(rawVHosts), &vhosts); err != nil {
			return logical.ErrorResponse(fmt.Sprintf("failed to unmarshal vhosts: %s", err)), nil
		}
	}

	// Store it
	entry, err := logical.StorageEntryJSON("role/"+name, &roleEntry{
		Tags:   tags,
		VHosts: vhosts,
	})
	if err != nil {
		return nil, err
	}
	if err := req.Storage.Put(entry); err != nil {
		return nil, err
	}

	return nil, nil
}
开发者ID:quixoten,项目名称:vault,代码行数:35,代码来源:path_roles.go

示例7: loadCredentials

// loadCredentials is invoked as part of postUnseal to load the auth table
func (c *Core) loadCredentials() error {
	authTable := &MountTable{}
	// Load the existing mount table
	raw, err := c.barrier.Get(coreAuthConfigPath)
	if err != nil {
		c.logger.Printf("[ERR] core: failed to read auth table: %v", err)
		return errLoadAuthFailed
	}

	c.authLock.Lock()
	defer c.authLock.Unlock()

	if raw != nil {
		if err := jsonutil.DecodeJSON(raw.Value, authTable); err != nil {
			c.logger.Printf("[ERR] core: failed to decode auth table: %v", err)
			return errLoadAuthFailed
		}
		c.auth = authTable
	}

	// Done if we have restored the auth table
	if c.auth != nil {
		needPersist := false

		// Upgrade to typed auth table
		if c.auth.Type == "" {
			c.auth.Type = credentialTableType
			needPersist = true
		}

		// Upgrade to table-scoped entries
		for _, entry := range c.auth.Entries {
			// The auth backend "aws-ec2" was named "aws" in the master.
			// This is to support upgrade procedure from "aws" to "aws-ec2".
			if entry.Type == "aws" {
				entry.Type = "aws-ec2"
				needPersist = true
			}

			if entry.Table == "" {
				entry.Table = c.auth.Type
				needPersist = true
			}
		}

		if needPersist {
			return c.persistAuth(c.auth)
		}

		return nil
	}

	// Create and persist the default auth table
	c.auth = defaultAuthTable()
	if err := c.persistAuth(c.auth); err != nil {
		c.logger.Printf("[ERR] core: failed to persist auth table: %v", err)
		return errLoadAuthFailed
	}
	return nil
}
开发者ID:mhurne,项目名称:vault,代码行数:61,代码来源:auth.go

示例8: RekeyRetrieveBackup

// RekeyRetrieveBackup is used to retrieve any backed-up PGP-encrypted unseal
// keys
func (c *Core) RekeyRetrieveBackup(recovery bool) (*RekeyBackup, error) {
	c.stateLock.RLock()
	defer c.stateLock.RUnlock()
	if c.sealed {
		return nil, ErrSealed
	}
	if c.standby {
		return nil, ErrStandby
	}

	c.rekeyLock.RLock()
	defer c.rekeyLock.RUnlock()

	var entry *physical.Entry
	var err error
	if recovery {
		entry, err = c.physical.Get(coreRecoveryUnsealKeysBackupPath)
	} else {
		entry, err = c.physical.Get(coreBarrierUnsealKeysBackupPath)
	}
	if err != nil {
		return nil, err
	}
	if entry == nil {
		return nil, nil
	}

	ret := &RekeyBackup{}
	err = jsonutil.DecodeJSON(entry.Value, ret)
	if err != nil {
		return nil, err
	}

	return ret, nil
}
开发者ID:mhurne,项目名称:vault,代码行数:37,代码来源:rekey.go

示例9: ParseForwardedRequest

// ParseForwardedRequest generates a new http.Request that is comprised of the
// values in the given request's body, assuming it correctly parses into a
// ForwardedRequest.
func ParseForwardedRequest(req *http.Request) (*http.Request, error) {
	buf := bufCloser{
		Buffer: bytes.NewBuffer(nil),
	}
	_, err := buf.ReadFrom(req.Body)
	if err != nil {
		return nil, err
	}

	var fq ForwardedRequest
	err = jsonutil.DecodeJSON(buf.Bytes(), &fq)
	if err != nil {
		return nil, err
	}

	buf.Reset()
	_, err = buf.Write(fq.Body)
	if err != nil {
		return nil, err
	}

	ret := &http.Request{
		Method:     fq.Method,
		URL:        fq.URL,
		Header:     fq.Header,
		Body:       buf,
		Host:       fq.Host,
		RemoteAddr: fq.RemoteAddr,
		TLS:        fq.ConnectionState,
	}

	return ret, nil
}
开发者ID:mhurne,项目名称:vault,代码行数:36,代码来源:forwarded_request.go

示例10: ParsePKIJSON

// ParsePKIJSON takes a JSON-encoded string and returns a ParsedCertBundle.
//
// This can be either the output of an
// issue call from the PKI backend or just its data member; or,
// JSON not coming from the PKI backend.
func ParsePKIJSON(input []byte) (*ParsedCertBundle, error) {
	result := &CertBundle{}
	err := jsonutil.DecodeJSON(input, &result)

	if err == nil {
		return result.ToParsedCertBundle()
	}

	var secret Secret
	err = jsonutil.DecodeJSON(input, &secret)

	if err == nil {
		return ParsePKIMap(secret.Data)
	}

	return nil, errutil.UserError{"unable to parse out of either secret data or a secret object"}
}
开发者ID:quixoten,项目名称:vault,代码行数:22,代码来源:helpers.go

示例11: handleRead

func (b *PassthroughBackend) handleRead(
	req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	// Read the path
	out, err := req.Storage.Get(req.Path)
	if err != nil {
		return nil, fmt.Errorf("read failed: %v", err)
	}

	// Fast-path the no data case
	if out == nil {
		return nil, nil
	}

	// Decode the data
	var rawData map[string]interface{}

	if err := jsonutil.DecodeJSON(out.Value, &rawData); err != nil {
		return nil, fmt.Errorf("json decoding failed: %v", err)
	}

	var resp *logical.Response
	if b.generateLeases {
		// Generate the response
		resp = b.Secret("generic").Response(rawData, nil)
		resp.Secret.Renewable = false
	} else {
		resp = &logical.Response{
			Secret: &logical.Secret{},
			Data:   rawData,
		}
	}

	// Check if there is a ttl key
	var ttl string
	ttl, _ = rawData["ttl"].(string)
	if len(ttl) == 0 {
		ttl, _ = rawData["lease"].(string)
	}
	ttlDuration := b.System().DefaultLeaseTTL()
	if len(ttl) != 0 {
		dur, err := duration.ParseDurationSecond(ttl)
		if err == nil {
			ttlDuration = dur
		}

		if b.generateLeases {
			resp.Secret.Renewable = true
		}
	}

	resp.Secret.TTL = ttlDuration

	return resp, nil
}
开发者ID:quixoten,项目名称:vault,代码行数:54,代码来源:logical_passthrough.go

示例12: loadAudits

// loadAudits is invoked as part of postUnseal to load the audit table
func (c *Core) loadAudits() error {
	auditTable := &MountTable{}

	// Load the existing audit table
	raw, err := c.barrier.Get(coreAuditConfigPath)
	if err != nil {
		c.logger.Error("core: failed to read audit table", "error", err)
		return errLoadAuditFailed
	}

	c.auditLock.Lock()
	defer c.auditLock.Unlock()

	if raw != nil {
		if err := jsonutil.DecodeJSON(raw.Value, auditTable); err != nil {
			c.logger.Error("core: failed to decode audit table", "error", err)
			return errLoadAuditFailed
		}
		c.audit = auditTable
	}

	// Done if we have restored the audit table
	if c.audit != nil {
		needPersist := false

		// Upgrade to typed auth table
		if c.audit.Type == "" {
			c.audit.Type = auditTableType
			needPersist = true
		}

		// Upgrade to table-scoped entries
		for _, entry := range c.audit.Entries {
			if entry.Table == "" {
				entry.Table = c.audit.Type
				needPersist = true
			}
		}

		if needPersist {
			return c.persistAudit(c.audit)
		}

		return nil
	}

	// Create and persist the default audit table
	c.audit = defaultAuditTable()
	if err := c.persistAudit(c.audit); err != nil {
		return errLoadAuditFailed
	}
	return nil
}
开发者ID:nawien-sharma,项目名称:vault,代码行数:54,代码来源:audit.go

示例13: testAccStepReadRole

func testAccStepReadRole(t *testing.T, name, tags, rawVHosts string) logicaltest.TestStep {
	return logicaltest.TestStep{
		Operation: logical.ReadOperation,
		Path:      "roles/" + name,
		Check: func(resp *logical.Response) error {
			if resp == nil {
				if tags == "" && rawVHosts == "" {
					return nil
				}

				return fmt.Errorf("bad: %#v", resp)
			}

			var d struct {
				Tags   string                     `mapstructure:"tags"`
				VHosts map[string]vhostPermission `mapstructure:"vhosts"`
			}
			if err := mapstructure.Decode(resp.Data, &d); err != nil {
				return err
			}

			if d.Tags != tags {
				return fmt.Errorf("bad: %#v", resp)
			}

			var vhosts map[string]vhostPermission
			if err := jsonutil.DecodeJSON([]byte(rawVHosts), &vhosts); err != nil {
				return fmt.Errorf("bad expected vhosts %#v: %s", vhosts, err)
			}

			for host, permission := range vhosts {
				actualPermission, ok := d.VHosts[host]
				if !ok {
					return fmt.Errorf("expected vhost: %s", host)
				}

				if actualPermission.Configure != permission.Configure {
					return fmt.Errorf("expected permission %s to be %s, got %s", "configure", permission.Configure, actualPermission.Configure)
				}

				if actualPermission.Write != permission.Write {
					return fmt.Errorf("expected permission %s to be %s, got %s", "write", permission.Write, actualPermission.Write)
				}

				if actualPermission.Read != permission.Read {
					return fmt.Errorf("expected permission %s to be %s, got %s", "read", permission.Read, actualPermission.Read)
				}
			}

			return nil
		},
	}
}
开发者ID:quixoten,项目名称:vault,代码行数:53,代码来源:backend_test.go

示例14: parseIdentityDocument

// Verifies the correctness of the authenticated attributes present in the PKCS#7
// signature. After verification, extracts the instance identity document from the
// signature, parses it and returns it.
func (b *backend) parseIdentityDocument(s logical.Storage, pkcs7B64 string) (*identityDocument, error) {
	// Insert the header and footer for the signature to be able to pem decode it
	pkcs7B64 = fmt.Sprintf("-----BEGIN PKCS7-----\n%s\n-----END PKCS7-----", pkcs7B64)

	// Decode the PEM encoded signature
	pkcs7BER, pkcs7Rest := pem.Decode([]byte(pkcs7B64))
	if len(pkcs7Rest) != 0 {
		return nil, fmt.Errorf("failed to decode the PEM encoded PKCS#7 signature")
	}

	// Parse the signature from asn1 format into a struct
	pkcs7Data, err := pkcs7.Parse(pkcs7BER.Bytes)
	if err != nil {
		return nil, fmt.Errorf("failed to parse the BER encoded PKCS#7 signature: %v\n", err)
	}

	// Get the public certificates that are used to verify the signature.
	// This returns a slice of certificates containing the default certificate
	// and all the registered certificates via 'config/certificate/<cert_name>' endpoint
	publicCerts, err := b.awsPublicCertificates(s, true)
	if err != nil {
		return nil, err
	}
	if publicCerts == nil || len(publicCerts) == 0 {
		return nil, fmt.Errorf("certificates to verify the signature are not found")
	}

	// Before calling Verify() on the PKCS#7 struct, set the certificates to be used
	// to verify the contents in the signer information.
	pkcs7Data.Certificates = publicCerts

	// Verify extracts the authenticated attributes in the PKCS#7 signature, and verifies
	// the authenticity of the content using 'dsa.PublicKey' embedded in the public certificate.
	if pkcs7Data.Verify() != nil {
		return nil, fmt.Errorf("failed to verify the signature")
	}

	// Check if the signature has content inside of it
	if len(pkcs7Data.Content) == 0 {
		return nil, fmt.Errorf("instance identity document could not be found in the signature")
	}

	var identityDoc identityDocument
	if err := jsonutil.DecodeJSON(pkcs7Data.Content, &identityDoc); err != nil {
		return nil, err
	}

	return &identityDoc, nil
}
开发者ID:quixoten,项目名称:vault,代码行数:52,代码来源:path_login.go

示例15: BarrierConfig

func (d *DefaultSeal) BarrierConfig() (*SealConfig, error) {
	if d.config != nil {
		return d.config.Clone(), nil
	}

	if err := d.checkCore(); err != nil {
		return nil, err
	}

	// Fetch the core configuration
	pe, err := d.core.physical.Get(barrierSealConfigPath)
	if err != nil {
		d.core.logger.Error("core: failed to read seal configuration", "error", err)
		return nil, fmt.Errorf("failed to check seal configuration: %v", err)
	}

	// If the seal configuration is missing, we are not initialized
	if pe == nil {
		d.core.logger.Info("core: seal configuration missing, not initialized")
		return nil, nil
	}

	var conf SealConfig

	// Decode the barrier entry
	if err := jsonutil.DecodeJSON(pe.Value, &conf); err != nil {
		d.core.logger.Error("core: failed to decode seal configuration", "error", err)
		return nil, fmt.Errorf("failed to decode seal configuration: %v", err)
	}

	switch conf.Type {
	// This case should not be valid for other types as only this is the default
	case "":
		conf.Type = d.BarrierType()
	case d.BarrierType():
	default:
		d.core.logger.Error("core: barrier seal type does not match loaded type", "barrier_seal_type", conf.Type, "loaded_seal_type", d.BarrierType())
		return nil, fmt.Errorf("barrier seal type of %s does not match loaded type of %s", conf.Type, d.BarrierType())
	}

	// Check for a valid seal configuration
	if err := conf.Validate(); err != nil {
		d.core.logger.Error("core: invalid seal configuration", "error", err)
		return nil, fmt.Errorf("seal validation failed: %v", err)
	}

	d.config = &conf
	return d.config.Clone(), nil
}
开发者ID:nawien-sharma,项目名称:vault,代码行数:49,代码来源:seal.go


注:本文中的github.com/hashicorp/vault/helper/jsonutil.DecodeJSON函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。