github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/common/hexutil/json_example_test.go (about)

     1  // This file is part of the go-sberex library. The go-sberex library is 
     2  // free software: you can redistribute it and/or modify it under the terms 
     3  // of the GNU Lesser General Public License as published by the Free 
     4  // Software Foundation, either version 3 of the License, or (at your option)
     5  // any later version.
     6  //
     7  // The go-sberex library is distributed in the hope that it will be useful, 
     8  // but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
    10  // General Public License <http://www.gnu.org/licenses/> for more details.
    11  
    12  package hexutil_test
    13  
    14  import (
    15  	"encoding/json"
    16  	"fmt"
    17  
    18  	"github.com/Sberex/go-sberex/common/hexutil"
    19  )
    20  
    21  type MyType [5]byte
    22  
    23  func (v *MyType) UnmarshalText(input []byte) error {
    24  	return hexutil.UnmarshalFixedText("MyType", input, v[:])
    25  }
    26  
    27  func (v MyType) String() string {
    28  	return hexutil.Bytes(v[:]).String()
    29  }
    30  
    31  func ExampleUnmarshalFixedText() {
    32  	var v1, v2 MyType
    33  	fmt.Println("v1 error:", json.Unmarshal([]byte(`"0x01"`), &v1))
    34  	fmt.Println("v2 error:", json.Unmarshal([]byte(`"0x0101010101"`), &v2))
    35  	fmt.Println("v2:", v2)
    36  	// Output:
    37  	// v1 error: hex string has length 2, want 10 for MyType
    38  	// v2 error: <nil>
    39  	// v2: 0x0101010101
    40  }