Created
June 15, 2016 14:41
-
-
Save deadcheat/63ec042b4a21247a145198360e4a3479 to your computer and use it in GitHub Desktop.
sql.NullStringをjsonにきれいに入れたり出したりするための何か
This file contains 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
// localtype パッケージ | |
// アプリケーションローカルの型はここに格納したい | |
package localtype | |
import ( | |
"database/sql" | |
"database/sql/driver" | |
"encoding/json" | |
) | |
// type OptionalString | |
// sql.NullStringのラッパー | |
type OptionalString sql.NullString | |
// func (o *OptionalString) Scan(value interface{}) error | |
// Implements Scan for settting value from database Row | |
func (o *OptionalString) Scan(value interface{}) error { | |
if value == nil { | |
o.String, o.Valid = "", false | |
return nil | |
} else { | |
o.String, o.Valid = string(value.([]byte)), true | |
return nil | |
} | |
return nil | |
} | |
// func Convert(s string) OptionalString | |
// convert OptionalString from simple string | |
func ConvertOptionalString(s string) *OptionalString { | |
var valided = false | |
if len(s) > 0 { | |
valided = true | |
} | |
return &OptionalString{ | |
Valid: valided, | |
String: s, | |
} | |
} | |
// func (o *OptionalString) Convert() *sql.NullString | |
// convert from OptionalString to NullString | |
func (o *OptionalString) Convert() *sql.NullString { | |
return &sql.NullString{ | |
Valid: o.Valid, | |
String: o.String, | |
} | |
} | |
// func (o *OptionalString) Value() (driver.Value, error) | |
// Value is needed such as func Scan | |
func (o *OptionalString) Value() (driver.Value, error) { | |
if o.Valid { | |
return o.String, nil | |
} | |
return "", nil | |
} | |
// func (o *OptionalString) GetString() string | |
// return string for safe | |
// ofcourse, you're ok to access OptionalString.String directly | |
func (o *OptionalString) SafeString() string { | |
if o.Valid { | |
return o.String | |
} | |
return "" | |
} | |
// func (o *OptionalString) MarshalJSON() ([]byte, error) | |
// convert to Json value | |
func (o *OptionalString) MarshalJSON() ([]byte, error) { | |
if o.Valid { | |
return json.Marshal(o.String) | |
} | |
return json.Marshal("") | |
} | |
// func (o *OptionalString) UnmarshalJSON(data []byte) error | |
// convert from string in Json | |
func (o *OptionalString) UnmarshalJSON(data []byte) error { | |
ns := ConvertOptionalString(string(data)).Convert() | |
d, err := json.Marshal(ns) | |
if err != nil { | |
return err | |
} | |
return json.Unmarshal(d, &sql.NullString{}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/guregu/null/blob/master/string.go