Category: Language

Install gosec

$ go get -u github.com/securego/gosec/v2/cmd/gosec $ gosec ./…

[Go] Get the network info for a network interface

func GetNetwork(ifname string) string { if interfaces, err := net.Interfaces(); err == nil { for _, iface := range interfaces { if iface.Name == ifname { addrs, err := iface.Addrs() if err != nil { panic(err) } ipaddr := strings.Split(addrs[0].String(), “/”)[1] return ipaddr } } } return “” }

[Go] Get the IP address assigned to a network interface

func GetIPAddr(ifname string) string { if interfaces, err := net.Interfaces(); err == nil { for _, iface := range interfaces { if iface.Name == ifname { if addrs, err := iface.Addrs(); err == nil { ipaddr := strings.Split(addrs[0].String(), “/”)[0] return ipaddr } return “” } } } return “” }

[Go] Get the network interface for the external access

func GetExternalInterface() string { route := “” res := exec.Command(“ip”, []string{“route”}…) if out, err := res.Output(); err == nil { route = string(out) } routeData := strings.Split(strings.Split(route, “\n”)[0], ” “) for idx, word := range routeData { if word == “dev” { return routeData[idx+1] } } return “” }

[Go] Read all contents from a file

func ReadAllFromPath(path string, doStrip bool) (string, error) { if _, err := os.Stat(path); err != nil { return “”, err } data, err := ioutil.ReadFile(path) if err != nil { return “”, err } ret := string(data) if doStrip { ret = strings.TrimSpace(ret) } return ret, nil }

[Go] Get the current UTC datetime

const ( TimeFormUTC string = “2006-01-02T15:04:05.000000Z” ) func GetDateTimeNow() (int64, string) { utc := time.Now().UTC() ret := utc.Format(TimeFormUTC) return utc.Unix(), ret }

[Go] Check if an element exists in a list of structures

func ContainsElement(slice interface{}, element interface{}) bool { switch reflect.TypeOf(slice).Kind() { case reflect.Slice: s := reflect.ValueOf(slice) for i := 0; i < s.Len(); i++ { val := s.Index(i).Interface() if reflect.DeepEqual(val, element) { return true } } } return false }

[Go] Create an empty file (like touch)

package main import ( “log” “os” ) func main() { emptyFile, err := os.Create(“empty.txt”) if err != nil { log.Fatal(err) } emptyFile.Close() }

[Go] Create Directories (like mkdir -p)

package main import ( “log” “os” ) func main() { if err := os.MkdirAll(“path1/path2”, 0775); err != nil { log.Fatal(err) } }

Customize Go Path

go mod init github.com/xxx/yyy