func handler(conn net.Conn, s *coelacanth.Server) { defer conn.Close() buf := s.GetPrefixedBuf() defer s.PutPrefixedBuf(buf) _, err := buf.ReadFrom(conn) if err != nil { s.Logger.Print(err) // TODO send error return } req := organizations.GetRootAsOrganization(buf.Bytes(), 0) b := s.GetBuilder() defer s.PutBuilder(b) switch req.Action() { case organizations.ActionIndex: orgs, err := allOrganizations(s.DB) if err != nil { s.Logger.Print(err) // TODO send error return } for _, o := range orgs { if _, err := prefixedio.WriteBytes(conn, o.toFlatBufferBytes(b)); err != nil { s.Logger.Print(err) } } case organizations.ActionNew: org := organizationFromFlatBuffer(req) if err := org.save(s.DB); err != nil { s.Logger.Print(err) // TODO send error return } if _, err := prefixedio.WriteBytes(conn, org.toFlatBufferBytes(b)); err != nil { s.Logger.Print(err) } case organizations.ActionRead: org, err := organizationByName(s.DB, string(req.Name())) if err != nil { // Do something return } if _, err := prefixedio.WriteBytes(conn, org.toFlatBufferBytes(b)); err != nil { s.Logger.Print(err) } } return }
func TestWriteBytes(t *testing.T) { t.Parallel() in := []byte("foo") buf := &bytes.Buffer{} n, err := prefixedio.WriteBytes(buf, in) if err != nil { t.Fatalf("Error returned: %v\n", err) } if n != len(in) { t.Fatalf("Wrong number of bytes returned. Expected: %v. Actual: %v\n", n, len(in)) } sizeBuf := make([]byte, 8) if _, err = buf.Read(sizeBuf); err != nil { t.Fatalf("Error reading size: %v\n", err) } size := binary.BigEndian.Uint64(sizeBuf) if int(size) != len(in) { t.Fatalf("Mismatched size. Expected: %v. Actual: %v\n", n, len(in)) } out := make([]byte, size) if _, err := buf.Read(out); err != nil { t.Fatalf("Error reading message: %v\n", err) } for i, c := range out { if in[i] != c { t.Fatalf("Written value doesn't match input. Expected: %q. Actual: %q\n", in[i], c) } } }
func BenchmarkWriteBytes(b *testing.B) { testBytes := make([]byte, 1000) for i := range testBytes { testBytes[i] = byte(rand.Int()) } testBuf := &bytes.Buffer{} b.ResetTimer() for i := 0; i < b.N; i++ { prefixedio.WriteBytes(testBuf, testBytes) testBuf.Reset() } }