vowlink: A Lightweight Go Functional Programming Library for Simplifying Complex if‑else Logic
This article introduces vowlink, a Go library that adopts JavaScript‑style Promise concepts to replace tangled if‑else statements with chainable, error‑handled functional constructs, providing a concise, efficient solution for backend developers facing growing business logic complexity.
I'm Lee, a veteran with 17 years in the IT industry, and I start this discussion by examining typical if‑else code that becomes increasingly complex as business logic grows, reducing readability and maintainability.
Using the Gin framework, a common pattern is to parse request parameters, validate them, and then execute different database updates based on those parameters, often relying on nested if‑else statements.
func UpdateData(c *gin.Context) {
var req struct {
ID int `json:"id"`
Name string `json:"name"`
}
// Parse request JSON
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Validate parameters
if req.ID == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})
return
}
if req.Name == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
return
}
// Execute business logic
if result, err := db.UpdateName(req.ID, req.Name); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
} else {
c.JSON(http.StatusOK, gin.H{"message": "success", "result": result})
}
}The above code illustrates typical Gin Handle logic, where repeated if‑else structures degrade code quality.
To address these pain points—code complexity, duplication, tangled logic, and hidden risks—I designed vowlink, a Go library inspired by JavaScript Promise that provides chainable calls, dependency handling, error handling, finalization, and race control.
vowlink’s core features include:
Chainable Calls : Replace nested if‑else with Then() chains.
Dependency Handling : Use Then().Then() to pass results forward.
Error Handling : Catch() processes failures.
Finalization : Finally() runs cleanup logic.
Race Control : Race(), All(), Any(), AllSettled() manage concurrent promise flows.
The library defines a PromiseState enum (Pending, Fulfilled, Rejected) and a Promise struct holding state, value, and error reason.
// Define Promise states
const (
// Pending – waiting for result
Pending PromiseState = iota
// Fulfilled – completed with a value
Fulfilled
// Rejected – completed with an error
Rejected
) type Promise struct {
// Current state
state PromiseState
// Resolved value
value interface{}
// Rejection reason
reason error
}Typical usage creates a new promise, attaches Then for success, Catch for failure, and optionally Finally for cleanup, then retrieves the result via GetValue or the error via GetReason.
func main() {
// Resolve example
result := vl.NewPromise(func(resolve func(interface{}, error), reject func(interface{}, error)) {
resolve("hello world", nil)
}).Then(func(value interface{}) (interface{}, error) {
return value.(string) + " vowlink !!", nil
}, func(err error) (interface{}, error) {
return nil, fmt.Errorf("rejected.")
})
fmt.Println("Resolve:", result.GetValue())
// Reject example
result = vl.NewPromise(func(resolve func(interface{}, error), reject func(interface{}, error)) {
reject(nil, fmt.Errorf("error"))
}).Then(func(value interface{}) (interface{}, error) {
return value.(string) + " vowlink", nil
}, func(err error) (interface{}, error) {
return nil, fmt.Errorf("rejected.")
})
fmt.Println("Rejected:", result.GetReason().Error())
}The output demonstrates how vowlink cleanly separates success and failure paths while keeping the code concise.
In summary, vowlink offers a lightweight, easy‑to‑learn functional programming model for Go developers, enabling clearer, more maintainable business logic without the boilerplate of traditional if‑else structures.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
