server/peer: wrap 'defer pool.Put()' in a closure

This commit is contained in:
CPunch 2023-03-11 15:02:01 -06:00
parent cbe308a0bd
commit 7a26ffdcf7

View File

@ -119,32 +119,33 @@ func (peer *Peer) Handler() {
} }
// grab buffer && read packet body // grab buffer && read packet body
buf := pool.Get() if err := func() error { // we wrap this in a closure so we can easily defer the buffer return to pool
defer pool.Put(buf) buf := pool.Get()
if _, err := buf.ReadFrom(io.LimitReader(peer.conn, int64(sz))); err != nil { defer pool.Put(buf)
log.Printf("[FATAL] failed to read packet body! %v", err) if _, err := buf.ReadFrom(io.LimitReader(peer.conn, int64(sz))); err != nil {
return return fmt.Errorf("failed to read packet body! %v", err)
} }
// decrypt // decrypt
protocol.DecryptData(buf.Bytes(), peer.E_key) protocol.DecryptData(buf.Bytes(), peer.E_key)
pkt := protocol.NewPacket(buf) pkt := protocol.NewPacket(buf)
// create packet && read typeID // create packet && read typeID
var typeID uint32 var typeID uint32
if err := pkt.Decode(&typeID); err != nil { if err := pkt.Decode(&typeID); err != nil {
log.Printf("[FATAL] failed to read packet type! %v", err) return fmt.Errorf("failed to read packet type! %v", err)
return }
}
// dispatch packet // dispatch packet
log.Printf("Got packet ID: %x, with a sizeof: %d\n", typeID, sz) log.Printf("Got packet ID: %x, with a sizeof: %d\n", typeID, sz)
if err := peer.handler.HandlePacket(peer, typeID, pkt); err != nil { if err := peer.handler.HandlePacket(peer, typeID, pkt); err != nil {
return err
}
return nil
}(); err != nil {
log.Printf("[FATAL] %v", err) log.Printf("[FATAL] %v", err)
return return
} }
// restore buffer to pool
pool.Put(buf)
} }
} }