关闭延迟关闭的文件

In my main function, I open a logging text file for writing with a defer close method to close it once the application quits. However, at the beginning of each new day I wish to start writing to the next day's log file, and I don't know how to close the previous day's file and start writing to the current one.

In my main function:

func main() {

f, err := os.OpenFile("2019-07-24.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0644)
    if err != nil {
        log.Fatalf("Error opening log file: %v", err)
    }
    defer f.Close()

    log.SetOutput(f)

}

Now when I receive a message on a new day in another package:

func gateway() {

f, err := os.OpenFile("2019-07-25.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0644)
    if err != nil {
        log.Fatalf("Error opening log file: %v", err)
    }
    defer f.Close()

    log.SetOutput(f)

}

How do I get a pointer to the previous day's log file from another package, and then close it (when a defer call will not be invoked unless the application completely closes?

Create a package that that manages the log output.

package logoutput

package main

import (
    "io"
    "log"
    "sync"
)

var (
    mu            sync.Mutex
    curr io.WriteCloser
)

func Set(w io.WriteCloser) {
    mu.Lock()
    defer mu.Unlock()
    prev := curr
    curr = w
    log.SetOutput(curr)
    if prev != nil {
       prev.Close()
    }
}

func Close() {
    mu.Lock()
    defer mu.Unlock()
    log.SetOutput(os.Stderr) // revert to default
    if curr != nil {
       curr.Close()
    }
    curr = nil
}

Call the package from main and the gateway package.

f, err := os.OpenFile("2019-07-24.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0644)
if err != nil {
    log.Fatalf("Error opening log file: %v", err)
}
logoutput.Set(f)
defer logoutput.Close() // call from main only