I always have a unit of crack infantry, usually two, waiting RIGHT inside the gate. I place them so there's no room to actually come out of the gate into the city without having to punch through my infantry. Preferably, this unit of infantry is something with long weapons like pikes or halberds (Janissary Heavies *wink wink*) that can push the attackers back and hold them in the gatehouse.

Usually, you can defeat an entire attacking army with only a couple units of infantry this way. A better way to do it is have the infantry hold the attackers in the gateway while you circle around with cavalry to throw them into the attacker's rear. They'll be cornered in the gatehouse, and all of them will instantly turn to 'fighting to the death' and get killed fast.