os.Open 讀取檔案和 vim 編輯的問題

stillfox發表於2020-02-23

寫了一個函式,用來讀取配置檔案。函式跑在 goroutine 裡面,一直不斷載入新的配置。發現一個問題:用 vim 編輯檔案之後,儲存不退出(w)的話,程式報錯: no such file or directory。編輯之後儲存退出(wq)則不會出現該問題。不知道儲存不退出的操作為什麼會使得 os.Open 無法找到檔案,有沒有大牛幫忙指點一下?謝謝~~~ 程式碼如下:

package main

import (
    "encoding/json"
    "fmt"
    "os"
    "time"
)

const subscriptionFile = "subscription.json"

type Subscription struct {
    Id  uint8   `json:"id"`
    Name    string  `json:"name"`
    Url []string    `json:"url"`
}


func (sub Subscription) IsEqual(sub2 Subscription) bool {
    if sub.Id == sub2.Id && sub.Name == sub2.Name {
        if len(sub.Url) == len(sub2.Url) {
            for i, url := range sub.Url {
                if url != sub2.Url[i] {
                    return false
                }
            }
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}


// 從 json 檔案裡讀取配置
func loadSubscription() []Subscription {
    file, err := os.Open(subscriptionFile)
    if err != nil {
        fmt.Println(err)
        os.Exit(-1)
    }

    defer file.Close()

    var subscriptions []Subscription
    _ = json.NewDecoder(file).Decode(&subscriptions)
    return subscriptions
}


var Subscriptions []Subscription


func init() {
    // load subscription.json
    Subscriptions = loadSubscription()
}

func checkSubscription() {
    newSubscriptions := loadSubscription()
    // check subscription.json has changed
    if len(newSubscriptions) == len(Subscriptions) {
        for i, sub := range newSubscriptions {
            if !(sub.IsEqual(Subscriptions[i])) {
                Subscriptions = newSubscriptions
                return
            }
        }
    } else {
        Subscriptions = newSubscriptions
    }
}

func main() {
    wait := make(chan struct{}, 1)
    go func() {
        for {
            checkSubscription()
        }
    }()

    go func() {
        for {
            fmt.Println(Subscriptions)
            time.Sleep(time.Second * 10)
        }
    }()
    <-wait
}

更多原創文章乾貨分享,請關注公眾號
  • os.Open 讀取檔案和 vim 編輯的問題
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章