M
M
MOTORIST2015-02-02 19:14:20
go
MOTORIST, 2015-02-02 19:14:20

How to set the path to the file to run the program from different locations?

t, err := template.ParseFiles("www/index.html")
If you run the program from the program directory, then everything is ok. If you run it from any other place, then the error cannot find index.html (c:\>f:\...\program).
OS Windows7 64

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Damir Makhmutov, 2015-02-02
@MOTORIST

Maybe you just need to write the absolute path to the file? Something like this:
or for unix-like

t, err := template.ParseFiles("/path/to/www/index.html")

Try like this:
import (
    "fmt"
    "log"
    "os"
    "path/filepath"
)

func main() {
    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
            log.Fatal(err)
    }
    fmt.Println(dir)
}

S
Sergey Lerg, 2015-02-02
@Lerg

There is a package with the desired function https://bitbucket.org/kardianos/osext/src
godoc.org/bitbucket.org/kardianos/osext
Should work cross-platform.

package main

import (
    "bitbucket.org/kardianos/osext"
    "fmt"
)

func main() {
    filename, _ := osext.Executable()
    fmt.Println(filename)
}

S
SilentFl, 2015-02-03
@SilentFl

put relative links "./www/index.html" (relative to the binary being run), or use the power of go generate to include html code in the code (and then only the binary is needed for the program to work)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question