Skip to content

Instantly share code, notes, and snippets.

@cannium
Created February 24, 2020 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cannium/7faa36ea70a767dba78307316a4a53b4 to your computer and use it in GitHub Desktop.
Save cannium/7faa36ea70a767dba78307316a4a53b4 to your computer and use it in GitHub Desktop.
DB JSON type
package model
import (
"database/sql/driver"
"encoding/json"
"errors"
)
type JSON []byte
func (j JSON) Value() (driver.Value, error) {
return []byte(j), nil
}
func (j *JSON) Scan(value interface{}) error {
if value == nil {
*j = nil
return nil
}
b, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
*j = b
return nil
}
func (j JSON) Unmarshal(value interface{}) error {
if j == nil {
return nil
}
return json.Unmarshal(j, value)
}
func Marshal(value interface{}) (JSON, error) {
if value == nil {
return nil, nil
}
return json.Marshal(value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment