Backend Development 8 min read

Unlock Go’s gobox Framework: Exception Handling, Utilities & Practical Examples

This article introduces the lightweight Go framework gobox, demonstrating its exception definition, common utility functions such as slice deduplication, file and directory existence checks, recursive file listing, JSON file saving and parsing, substring extraction, time formatting constants, and random number generation based on timestamps, all with clear code examples.

360 Zhihui Cloud Developer
360 Zhihui Cloud Developer
360 Zhihui Cloud Developer
Unlock Go’s gobox Framework: Exception Handling, Utilities & Practical Examples

Introduction Today we introduce our self‑developed Go lightweight framework gobox . Each module is a "box" and the collection of boxes forms gobox, which can be imported via Go's package management.

Exception Handling

Go lacks a built‑in exception mechanism; we can simulate it with panic / recover , but it is not recommended. The gobox exception package wraps an error code (errno) and message (msg).

<code>package main

import (
    "github.com/goinbox/exception"
    "fmt"
)

func main() {
    e := exception.New(101, "test exception")
    fmt.Println(e.Errno(), e.Msg())
    fmt.Println(e.Error())
}
</code>

Utility Functions (gomisc)

The gomisc package provides various helpers.

Slice Deduplication

<code>package main

import (
    "github.com/goinbox/gomisc"
    "fmt"
)

func main() {
    is := []int{1,2,2,3,3,3,4,4,4,4}
    fmt.Println("origin slice is:", is)
    is = gomisc.IntSliceUnique(is)
    fmt.Println("after call slice is:", is)

    ss := []string{"a","ab","ab","abc","abc","abc","abcd","abcd","abcd","abcd","abcd"}
    fmt.Println("origin slice is:", ss)
    ss = gomisc.StringSliceUnique(ss)
    fmt.Println("after call slice is:", ss)
}
</code>

File/Directory Existence

<code>package main

import (
    "github.com/goinbox/gomisc"
    "fmt"
)

func main() {
    f := "/etc/passwd"
    if gomisc.FileExist(f) {
        fmt.Println(f, "is exist")
    } else {
        fmt.Println(f, "is not exist")
    }

    d := "/home/ligang/devspace"
    if gomisc.DirExist(d) {
        fmt.Println(d, "is exist")
    } else {
        fmt.Println(d, "is not exist")
    }
}
</code>

Recursive File Listing

<code>package main

import (
    "github.com/goinbox/gomisc"
    "fmt"
    "time"
)

func main() {
    fileList, err := gomisc.ListFilesInDir("/home/ligang/tmp")
    if err != nil {
        fmt.Println(err)
        return
    }
    for _, path := range fileList {
        fmt.Println(path)
    }
}
</code>

JSON Save & Parse

<code>package main

import (
    "github.com/goinbox/gomisc"
    "fmt"
)

func main() {
    filePath := "/tmp/test_save_parse_json_file.json"
    v1 := map[string]string{"k1": "a", "k2": "b", "k3": "c"}
    if err := gomisc.SaveJsonFile(filePath, v1); err != nil {
        fmt.Println("save json file failed:", err.Error())
    } else {
        fmt.Println("save json file success")
    }

    var v2 map[string]string
    if err := gomisc.ParseJsonFile(filePath, &v2); err != nil {
        fmt.Println("parse json file failed:", err.Error())
    } else {
        fmt.Println("parse json file success")
        for k, v := range v2 {
            if v != v1[k] {
                fmt.Println("save parse json file error, k:", k, "not equal")
            } else {
                fmt.Println("save parse json file k:", k, "equal")
            }
        }
    }
}
</code>

Substring Extraction

<code>package main

import (
    "github.com/goinbox/gomisc"
    "fmt"
)

func main() {
    s := "abcdefg"
    if sub, err := gomisc.SubString(s, 3, 20); err == nil {
        fmt.Println("substr", sub)
    }
    if sub, err := gomisc.SubString(s, 10, 3); err == nil {
        fmt.Println("substr", sub)
    }
    if ss, err := gomisc.SubString(s, 3, 4); err == nil {
        fmt.Println(s, "substr", ss)
    }
}
</code>

Time Formatting Constants

<code>const (
    TIME_FMT_STR_YEAR   = "2006"
    TIME_FMT_STR_MONTH  = "01"
    TIME_FMT_STR_DAY    = "02"
    TIME_FMT_STR_HOUR   = "15"
    TIME_FMT_STR_MINUTE = "04"
    TIME_FMT_STR_SECOND = "05"
)
</code>

Using gomisc.TimeGeneralLayout() returns the layout 2006-01-02 15:04:05 , which can format the current time. <code>layout := gomisc.TimeGeneralLayout() fmt.Println("fmt layout is", layout) fmt.Println("not time is", time.Now().Format(layout)) </code>

Random Number Generation by Time

<code>package main

import (
    "github.com/goinbox/gomisc"
    "fmt"
    "time"
)

func main() {
    tm := time.Now()
    fmt.Println(gomisc.RandByTime(&tm), gomisc.RandByTime(&tm), gomisc.RandByTime(nil))
}
</code>

Note: identical timestamps produce identical random results.

backend developmentexception handlingGoJSONutility functionsgoboxtime formatting
360 Zhihui Cloud Developer
Written by

360 Zhihui Cloud Developer

360 Zhihui Cloud is an enterprise open service platform that aims to "aggregate data value and empower an intelligent future," leveraging 360's extensive product and technology resources to deliver platform services to customers.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.