Skip to content

Instantly share code, notes, and snippets.

@nametake
Created March 17, 2017 01:57
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 nametake/1e4d92b6ba4ce27d3207d32b3466c26d to your computer and use it in GitHub Desktop.
Save nametake/1e4d92b6ba4ce27d3207d32b3466c26d to your computer and use it in GitHub Desktop.
ReadWriterのテストコード
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