title: json.Marshal custom type as base64 string
body: <p>I have a custom type (Hash [64]byte) and I'm trying to implement MarshalJSON/UnmarshalJSON for it to have it encoded/decoded in JSON as a base64 string. Instead I'm getting an error about an invalid character in the beginning.</p>
  
  <pre><code>package main
  
  import (
      "encoding/base64"
      "encoding/json"
      "fmt"
  )
  
  type Hash [64]byte
  
  func FromString(data string) (Hash, error) {
      decoded, err := base64.StdEncoding.DecodeString(string(data))
      if err != nil {
          return Hash{}, err
      }
  
      hash := Hash{}
      for index := 0; index &lt; 64; index++ {
          hash[index] = decoded[index]
      }
  
      return hash, nil
  }
  
  func (hash Hash) String() string {
      return base64.StdEncoding.EncodeToString([]byte(hash[:64]))
  }
  
  func (hash Hash) MarshalJSON() ([]byte, error) {
      return []byte(hash.String()), nil
  }
  
  func (hash *Hash) UnmarshalJSON(data []byte) error {
      decoded, err := FromString(string(data))
      if err != nil {
          return err
      }
  
      for index := 0; index &lt; 64; index++ {
          hash[index] = decoded[index]
      }
  
      return nil
  }
  
  
  func main() {
      type TestStructure struct {
          Hash Hash
          Type string
      }
  
      object := TestStructure{
          Hash: Hash{0xbd, 0xfe, 0xe0, 0xb1, 0x6c, 0xff, 0xb4, 0x51, 0x4c, 0x7b, 0xed, 0x33, 0xc1, 0x6d, 0xac, 0x5e, 0x80, 0x51, 0xec, 0xcb, 0x31, 0x21, 0x8c, 0x54, 0xb, 0xec, 0xbc, 0x7e, 0xbf, 0x4a, 0xce, 0x92, 0x3b, 0xcb, 0xf8, 0xdd, 0x82, 0x45, 0x34, 0xae, 0x58, 0x5, 0x3a, 0x7b, 0x18, 0xdd, 0x30, 0x5c, 0x7e, 0xed, 0xc9, 0xaa, 0x1e, 0x3a, 0x9a, 0x95, 0x30, 0xc3, 0x6b, 0xf8, 0xf9, 0x92, 0x43, 0xc6},
          Type: "I'm a type",
      }
  
      data, err := json.Marshal(object)
      fmt.Println(data, err)
  }
  </code></pre>
  
  <p>I got the following error:</p>
  
  <pre><code>$ go run hash.go 
  [] json: error calling MarshalJSON for type main.Hash: invalid character 'v' looking for beginning of value
  </code></pre>
  
  <p>What am I doing wrong?</p>