[verb ます-stem] + に行く [verb ます-stem] + に来る [verb ます-stem] + に帰る
The structure V[masu stem] + に行く is used to express going somewhere in order to do something. The masu stem of the verb describes the purpose, and に marks that purpose. いく行く means "to go," so the overall meaning is "to go (in order) to do ~."
The masu stem is formed by removing ます from the polite form of the verb (e.g. たべます食べます → たべ食べ; かいます買います → かい買い).
The same structure works with other movement verbs. Use に来る to express "come to do ~" and に帰る to express "go/come home to do ~."
You can include a destination using へ or に before the purpose phrase. When a destination is included, the sentence will have two に particles – one for the destination and one for the purpose – which is perfectly natural.
For する compound verbs like かいもの買い物する or べんきょう勉強する, the masu stem is し, so they become ~しに行く.