I want to run gofmt on save on vim without installing any plugin. This is what I have tried (inspired by https://gist.github.com/tbrisbout/a91ac3419440cde40c5f54dc32c94427):
function! GoFmt()
let file = expand('%')
silent execute "!gofmt -w " . file
edit!
endfunction
command! GoFmt call GoFmt()
augroup go_autocmd
autocmd BufWritePost *.go GoFmt
augroup END
This just works when there is no format error. However, if the code contains error, it shows error message at the bottom of the screen and (it seems like) it appears on the buffer as text, so the whole code gets broken. Is there an simple way to handle this kind of work on vim?

You can update the script as below:
Gofmtis a tool that automatically formats Go source code.Gofmtis both a code formatter and a linter.From doc
The above script will update the file if there are no errors
If applicable, create a quickfix list with the errors reported by gofmt.
cexprto create a quickfix list read more about it using vim help dochelp :cexpr,systemto run system command read more about it using vim help dochelp :system,expandExpand wildcards and special keywords into string read more about it using vim help dochelp :expand,%is a special keyword which refer to current file.edit!is used to reload file contents.Then you can quickly jump over the errors using quickfix list you can learn more about it from this
blogpost.