Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active February 24, 2024 00:07
Show Gist options
  • Save miguelmota/5bfa2b6ab88f439fe0da0bfb1faca763 to your computer and use it in GitHub Desktop.
Save miguelmota/5bfa2b6ab88f439fe0da0bfb1faca763 to your computer and use it in GitHub Desktop.
Golang interface to bytes using gob encoder
package main
import (
"encoding/gob"
"bytes"
)
func GetBytes(key interface{}) ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(key)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
@leucos
Copy link

leucos commented Aug 17, 2020

func GetBytes(key interface{}) ([]byte, error) {
	buf, ok := key.([]byte)
	if !ok {
		return nil, fmt.Errorf("ooops, did not work")
	}

	return buf, nil
}

https://play.golang.org/p/lwvIZgF3hhF

@alecholmez
Copy link

func GetBytes(key interface{}) ([]byte, error) {
	buf, ok := key.([]byte)
	if !ok {
		return nil, fmt.Errorf("ooops, did not work")
	}

	return buf, nil
}

https://play.golang.org/p/lwvIZgF3hhF

This only works if the inputed interface was originally bytes. If this were to be a string, etc... you would receive something like this from a panic:

2021/10/06 21:05:39 http: panic serving [::1]:50999: interface conversion: interface {} is string, not []uint8

@notalentgeek
Copy link

This only works if the inputted interface was originally bytes. If this were to be a string, etc... you would receive something like this from a panic:

I solve this by converting the interface{} to string and then to []byte :

json.Unmarshal([]byte(value.(string)), &j)

@EmeraldLS
Copy link

This only works if the inputted interface was originally bytes. If this were to be a string, etc... you would receive something like this from a panic:

I solve this by converting the interface{} to string and then to []byte :

json.Unmarshal([]byte(value.(string)), &j)

This doesnt work also.
Unable to unmarshal: invalid character 'e' looking for beginning of value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment