How to get the exe file path

please,i want to get the exe’s path that comes from go build.
but,i don’t use os.Args[0] and cmd. i want to click exe file and it can show path. so how to write my code.

A properly written executable is agnostic about its actual location and only cares about its working directory.

So to be honest, the best way to write the code you asked is to not write it at all.

Anyway, if you really have to, inspecting os.Args[0] is probably the only way. It should contain the exact string that was used to start your application without its arguments (as those are in os.Args[1:]. To get the actual location of your binary, you then only need to:

  1. Check if it is drive absolut, so it should be the real path of your binary
  2. Check if it is drive relative, so you need to join with your current working dir, normalize it and then you have the location
  3. check if it is simply the name of your application, then you need to iterate over %PATH% to find the used executable

Easy, isn’t it?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.