I have a Go program which accepts and uses format strings supplied by the user at runtime. The specification for these would be something like "a format string which accepts three ints", etc.
If the user gives me a string which doesn't meet my specification, I would like to return/output an error. I don't believe there is a simple way to do this with the fmt
library: is this correct? How should I do this?
I can think of three potential approaches, but I have problems with all of them:
Call
fmt.Sprintf(inputFmt, args...)
and search it for the"!%"
substrings that are produced when the formatter encounters a problem. This doesn't work if the user actually wants a string with"!%"
somewhere in it. I think the likelihood of this is small for my application, but I'd really prefer not to make this restriction if I didn't have to.Write code that inspects the input string prior to formatting to see if it complies with my specification. For the example above, I'd check if there were exactly three valid integer verbs (complete with checking all the flags that those verbs could take). Looking at
doPrintf()
infmt/print.go
, this seems like a lot of work.Don't explicitly check that formatting succeeded, but report an error later when the misformatted string is unsuccessfully used. (E.g.
the file %!s(int=1).dat%!(EXTRA int=2, int=3) does not exist or is misformatted
). I think this type of error message might be confusing to non Go programmers who use my program and will also not work in all cases where a format string is needed.