File: struct.go

package info (click to toggle)
golang-github-clbanning-mxj 2.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,200 kB
  • sloc: xml: 176; makefile: 4
file content (54 lines) | stat: -rw-r--r-- 1,710 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright 2012-2017 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 (
	"encoding/json"
	"errors"
	"reflect"

	// "github.com/fatih/structs"
)

// Create a new Map value from a structure.  Error returned if argument is not a structure.
// Only public structure fields are decoded in the Map value. See github.com/fatih/structs#Map
// for handling of "structs" tags.

// DEPRECATED - import github.com/fatih/structs and cast result of structs.Map to mxj.Map.
//	import "github.com/fatih/structs"
//	...
//	   sm, err := structs.Map(<some struct>)
//	   if err != nil {
//	      // handle error
//	   }
//	   m := mxj.Map(sm)
// Alernatively uncomment the old source and import in struct.go.
func NewMapStruct(structVal interface{}) (Map, error) {
	return nil, errors.New("deprecated - see package documentation")
	/*
		if !structs.IsStruct(structVal) {
			return nil, errors.New("NewMapStruct() error: argument is not type Struct")
		}
		return structs.Map(structVal), nil
	*/
}

// Marshal a map[string]interface{} into a structure referenced by 'structPtr'. Error returned
// if argument is not a pointer or if json.Unmarshal returns an error.
//	json.Unmarshal structure encoding rules are followed to encode public structure fields.
func (mv Map) Struct(structPtr interface{}) error {
	// should check that we're getting a pointer.
	if reflect.ValueOf(structPtr).Kind() != reflect.Ptr {
		return errors.New("mv.Struct() error: argument is not type Ptr")
	}

	m := map[string]interface{}(mv)
	j, err := json.Marshal(m)
	if err != nil {
		return err
	}

	return json.Unmarshal(j, structPtr)
}