Created
March 17, 2017 01:57
-
-
Save nametake/1e4d92b6ba4ce27d3207d32b3466c26d to your computer and use it in GitHub Desktop.
ReadWriterのテストコード
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
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
func main() { | |
u := &user{ | |
Name: "nameki", | |
Age: 23, | |
} | |
// read | |
b := make([]byte, 1024) | |
n, err := u.Read(b) | |
fmt.Printf("n : %d\n", n) | |
fmt.Printf("err: %s\n", err) | |
fmt.Printf("string: %+s\n", b) | |
// Write | |
d := `{"name":"tanaka","age":10}` | |
u.Write([]byte(d)) | |
fmt.Printf("%+v\n", u) | |
} | |
type user struct { | |
Name string `json:"name"` | |
Age int `json:"age"` | |
} | |
func (u *user) Read(p []byte) (n int, err error) { | |
p, err := json.Marshal(u) | |
for i, t := range b { | |
p[i] = t | |
} | |
return len(p), err | |
} | |
func (u *user) Write(b []byte) (n int, err error) { | |
err = json.Unmarshal(b, u) | |
if err != nil { | |
return 0, err | |
} | |
return len(b), err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment