Created
February 24, 2020 10:33
-
-
Save cannium/7faa36ea70a767dba78307316a4a53b4 to your computer and use it in GitHub Desktop.
DB JSON type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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