Western that was Vietnam allegory?

I vaguely recall catching part of a western on TV some years ago. What I recall of the plot was that a marshall rode into a border town that was being attacked by bandits, only to discover that most of the people in the town hated the town’s corrupt mayor and sheriff, and were secretly rooting for the bandits. It ended with the bandits hanging the mayor and his cronies while the townspeople cheered. Can anyone give me the name of the movie?