2016-06-25 22:39
浏览 87


I'm trying to open a log file with os package using os.OpenFile function, which should with proper flag create file if such file does not exists. But it returns non nil error: No such file or directory. BTW I'm using linux and go 1.6. Log file opening happens in init function. Heres my code:

package main

import (


// Structs holds server configuration data from config json.
type serverConfiguration struct {
    port                    string
    logFileName             string
    sessionStorePhrase      string
    resourceFilesPath       string
    resourceFilesPathPrefix string

// Server global variables.
var (
    serverConfig serverConfiguration
    logFile      *os.File
    router       *mux.Router
    sessionStore *sessions.CookieStore

func init() {
    // temporary variables.
    var (
        configFile                                   *os.File
        serverConfErr, configDecodingErr, logFileErr error

    // Loads json config file.
    configFile, serverConfErr = os.Open("server-conf.json")
    defer configFile.Close()

    if serverConfErr != nil {
        log.Fatal("SERVER-CONFIG-ERROR: ", serverConfErr)

    // Decodes json to serverConfig struct.
    decoder := json.NewDecoder(configFile)
    serverConfig = serverConfiguration{}
    configDecodingErr = decoder.Decode(&serverConfig)

    if configDecodingErr != nil {
        log.Fatal("CONFIGURATION-DECODING-ERROR: ", configDecodingErr)

    // Opens log file in app root directory.
    logFile, logFileErr = os.OpenFile(serverConfig.logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)

    if logFileErr != nil {
        log.Fatal("LOG-FILE-ERROR: ", logFileErr)

    // Creates session store.
    sessionStore = sessions.NewCookieStore([]byte(serverConfig.sessionStorePhrase))

// Home page handler.
func homePageHandler(writer http.ResponseWriter, request *http.Request) {
    fmt.Fprint(writer, "asdasdasdasd")

func main() {
    defer logFile.Close()
    router = mux.NewRouter().StrictSlash(false)
    resourceFileServer := http.FileServer(http.Dir(serverConfig.resourceFilesPath))
    router.PathPrefix(serverConfig.resourceFilesPathPrefix).Handler(http.StripPrefix(serverConfig.resourceFilesPathPrefix, resourceFileServer))

    router.HandleFunc("/", homePageHandler)

    server := &http.Server{
        Addr:    serverConfig.port,
        Handler: router,

    log.Println("Server listening on port ", serverConfig.port)
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • doulang6695 2016-06-25 23:05

    The error is most likely that the path you want to create your file in doesn't exist. it will create the logfile, but not the parent directories if they don't exist. To create the necessary directory structure, you could use os.MkdirAll

    解决 无用
    打赏 举报

相关推荐 更多相似问题