Skip to content

Commit

Permalink
Unstable version with channels, context and verbose mode
Browse files Browse the repository at this point in the history
  • Loading branch information
jaavier committed Jul 26, 2023
1 parent d8ba89e commit 432b89a
Showing 1 changed file with 53 additions and 12 deletions.
65 changes: 53 additions & 12 deletions geval.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,80 @@ package geval

import (
"context"
"log"
"fmt"
"runtime"
)

type Params struct {
Err error
Success func(ctx context.Context)
Failed func(ctx context.Context)
Handler func() (context.Context, error)
Success func(ctx *Context)
Failed func(ctx *Context)
Handler func(ctx *Context) error
Panic func(v any) error
Verbose int
Context context.Context
Context *Context
Verbose bool
}

type Context struct {
Context context.Context
CancelFunc context.CancelFunc
Channel chan interface{}
}

func (cc *Context) Update(key interface{}, val interface{}) {
cc.Context = context.WithValue(cc.Context, key, val)
}

func (cc *Context) Read(key interface{}) interface{} {
return (cc.Context).Value(key)
}

func CreateContext() *Context {
ctx, cancel := context.WithCancel(context.Background())

return &Context{
Context: ctx,
CancelFunc: cancel,
Channel: make(chan interface{}),
}
}

func Run(params *Params) {
var err error
var ctx = context.TODO()
var err error = params.Err
var template string
var ctx = params.Context

if (ctx) == nil {
panic("Cannot Run wihout Context")
}

_, file, line, ok := runtime.Caller(1)
if ok {
template = fmt.Sprintf("%s:%d %%s\n", file, line)
}

if params.Err == nil && params.Handler != nil {
ctx, err = params.Handler()
err = params.Handler(ctx)
}

if err != nil {
if params.Verbose > 0 {
log.Println(err.Error())
}
if params.Panic != nil {
if params.Verbose {
fmt.Printf("[VERBOSE] %s", fmt.Sprintf(template, "(Panic)"))
}
panic(params.Panic(err))
}
if params.Failed != nil {
if params.Verbose {
fmt.Printf("[VERBOSE] %s", fmt.Sprintf(template, "(Failed)"))
}
params.Failed(ctx)
}
} else {
if params.Success != nil {
if params.Verbose {
fmt.Printf("[VERBOSE] %s", fmt.Sprintf(template, "(Success)"))
}
params.Success(ctx)
}
}
Expand Down

0 comments on commit 432b89a

Please sign in to comment.