goext/ginext/appcontext.go

60 lines
1.1 KiB
Go
Raw Normal View History

2023-07-18 15:12:06 +02:00
package ginext
import (
"context"
"github.com/gin-gonic/gin"
"time"
)
type AppContext struct {
inner context.Context
cancelFunc context.CancelFunc
cancelled bool
ginContext *gin.Context
}
func CreateAppContext(g *gin.Context, innerCtx context.Context, cancelFn context.CancelFunc) *AppContext {
return &AppContext{
inner: innerCtx,
cancelFunc: cancelFn,
cancelled: false,
ginContext: g,
}
}
func (ac *AppContext) Deadline() (deadline time.Time, ok bool) {
return ac.inner.Deadline()
}
func (ac *AppContext) Done() <-chan struct{} {
return ac.inner.Done()
}
func (ac *AppContext) Err() error {
return ac.inner.Err()
}
func (ac *AppContext) Value(key any) any {
return ac.inner.Value(key)
}
func (ac *AppContext) Cancel() {
ac.cancelled = true
ac.cancelFunc()
}
func (ac *AppContext) RequestURI() string {
if ac.ginContext != nil && ac.ginContext.Request != nil {
return ac.ginContext.Request.Method + " :: " + ac.ginContext.Request.RequestURI
} else {
return ""
}
}
func (ac *AppContext) FinishSuccess(res HTTPResponse) HTTPResponse {
if ac.cancelled {
panic("Cannot finish a cancelled request")
}
return res
}