Skip to content

Instantly share code, notes, and snippets.

@zamicol
Created July 23, 2021 22:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zamicol/3c306b0734f819fb44b18fac1fc752d1 to your computer and use it in GitHub Desktop.
Save zamicol/3c306b0734f819fb44b18fac1fc752d1 to your computer and use it in GitHub Desktop.
Hex for golang
package hex
import (
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
)
// Hex is useful for
// marshaling and unmarshaing structs that have a Hex type. Hex is stored in
// memory/disk as []byte, and represented in JSON as upper case Hexadecimal. Hex
// should never be trimmed or padded.
type Hex []byte
// UnmarshalJSON implements JSON.UnmarshalJSON. It is a custom unmarshaler for
// binary data in JSON, which should always be represented as upper case hex.
func (h *Hex) UnmarshalJSON(b []byte) error {
// JSON.Unmarshal will send b encapsulated in quote characters. Quotes
// characters are invalid hex and need to be stripped. // TODO: do this
// efficiently.
trimmed := strings.Trim(string(b), "\"")
s, err := hex.DecodeString(trimmed)
if err != nil {
return err
}
*h = Hex(s)
return nil
}
// MarshalJSON implements JSON.UnmarshalJSON. Converts bytes to upper case Hex
// string. []byte(string(Hex))) error is always nil.
func (t Hex) MarshalJSON() ([]byte, error) {
// JSON expects stings to be wrapped with double quote character.
return []byte(fmt.Sprintf("\"%v\"", t)), nil
}
// String implements fmt.Stringer.
func (t Hex) String() string {
return fmt.Sprintf("%X", []byte(t))
}
// String implements fmt.GoString.
// Use `%#v` to get this form
func (t Hex) GoString() string {
// // Base256 representation
// return fmt.Sprintf("%s", []byte(t))
// Base64 Representation
return base64.StdEncoding.EncodeToString([]byte(t))
}
// Format implements fmt.Formatter
// func (t Hex) Format(f fmt.State, verb rune) {
// fmt.Println(f, verb)
// fmt.Println(string(verb))
// }
// HexEncodeToString converts bytes to upper case hex string.
func HexEncodeToString(b []byte) string {
return Hex(b).String()
}
// HexDecodeString is a convenience function
func HexDecodeString(s string) ([]byte, error) {
return hex.DecodeString(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment