Tag: go

  • golang: Check if key exists in map

    You can easily check if a key exists in a go map by using the ok result:


    value, ok := myMap[key]

    Or in an one line check:


    if val, ok := myMap[key]; ok {
    // do something
    }

     

     

  • Golang: Reverse ISOWeek, get the date of the first day of ISO week

    If you work with weeknummers, you can find the weeknumber of a date with the Golang function time.ISOWeek. However you wish to get the first date of a week, there is no such function in Google Go. So let’s write it our selfs:

    func FirstDayOfISOWeek(year int, week int, timezone *time.Location) time.Time {
    date := time.Date(year, 0, 0, 0, 0, 0, 0, timezone)
    isoYear, isoWeek := date.ISOWeek()

    // iterate back to Monday
    for date.Weekday() != time.Monday {
    date = date.AddDate(0, 0, -1)
    isoYear, isoWeek = date.ISOWeek()
    }

    // iterate forward to the first day of the first week
    for isoYear < year {
    date = date.AddDate(0, 0, 7)
    isoYear, isoWeek = date.ISOWeek()
    }

    // iterate forward to the first day of the given week
    for isoWeek < week {
    date = date.AddDate(0, 0, 7)
    isoYear, isoWeek = date.ISOWeek()
    }

    return date
    }

  • Golang create directory

    Creating a directory from Google Go is simple with the “os” package. See the example below.

    Golang create directory example

    path := "/folder/to/create"
    err := os.MkdirAll(path,0711)
    
    if err != nil {
     log.Println("Error creating directory")
     log.Println(err)
     return
    }
  • Golang delete file

    Deleting a file from Google Go (Golang) is simple with the “os” package. See the example below.

    Golang delete file example

    path := "/path/to/file/to/delete"
    err := os.Remove(path)
    
    if err != nil {
      fmt.Println(err)
      return
    }