Compare commits
16 Commits
Author | SHA1 | Date | |
---|---|---|---|
2f1b784dc2
|
|||
190584e0e6
|
|||
b7003b9ec9
|
|||
4f871271e8
|
|||
91f4793678
|
|||
3b30bb049e | |||
f0c5b36ea9 | |||
647ec64c3b
|
|||
b5f9b6b638
|
|||
c7949febf2
|
|||
15a4b2a713 | |||
493c6ebae8 | |||
fb847b03af | |||
f826633e6e
|
|||
edeae23bf1
|
|||
a038b86147
|
@@ -31,13 +31,13 @@ type EnumDef struct {
|
||||
Values []EnumDefVal
|
||||
}
|
||||
|
||||
var rexPackage = rext.W(regexp.MustCompile("^package\\s+(?P<name>[A-Za-z0-9_]+)\\s*$"))
|
||||
var rexPackage = rext.W(regexp.MustCompile(`^package\s+(?P<name>[A-Za-z0-9_]+)\s*$`))
|
||||
|
||||
var rexEnumDef = rext.W(regexp.MustCompile("^\\s*type\\s+(?P<name>[A-Za-z0-9_]+)\\s+(?P<type>[A-Za-z0-9_]+)\\s*//\\s*(@enum:type).*$"))
|
||||
var rexEnumDef = rext.W(regexp.MustCompile(`^\s*type\s+(?P<name>[A-Za-z0-9_]+)\s+(?P<type>[A-Za-z0-9_]+)\s*//\s*(@enum:type).*$`))
|
||||
|
||||
var rexValueDef = rext.W(regexp.MustCompile("^\\s*(?P<name>[A-Za-z0-9_]+)\\s+(?P<type>[A-Za-z0-9_]+)\\s*=\\s*(?P<value>(\"[A-Za-z0-9_:]+\"|[0-9]+))\\s*(//(?P<descr>.*))?.*$"))
|
||||
var rexValueDef = rext.W(regexp.MustCompile(`^\s*(?P<name>[A-Za-z0-9_]+)\s+(?P<type>[A-Za-z0-9_]+)\s*=\s*(?P<value>("[A-Za-z0-9_:]+"|[0-9]+))\s*(//(?P<descr>.*))?.*$`))
|
||||
|
||||
var rexChecksumConst = rext.W(regexp.MustCompile("const ChecksumGenerator = \"(?P<cs>[A-Za-z0-9_]*)\""))
|
||||
var rexChecksumConst = rext.W(regexp.MustCompile(`const ChecksumGenerator = "(?P<cs>[A-Za-z0-9_]*)"`))
|
||||
|
||||
func GenerateEnumSpecs(sourceDir string, destFile string) error {
|
||||
|
||||
|
@@ -22,7 +22,7 @@ type ExErr struct {
|
||||
WrappedErrType string `json:"wrappedErrType"`
|
||||
Caller string `json:"caller"`
|
||||
|
||||
OriginalError *ExErr
|
||||
OriginalError *ExErr `json:"originalError"`
|
||||
|
||||
Meta MetaMap `json:"meta"`
|
||||
}
|
||||
@@ -31,10 +31,16 @@ func (ee *ExErr) Error() string {
|
||||
return ee.Message
|
||||
}
|
||||
|
||||
// Unwrap must be implemented so that some error.XXX methods work
|
||||
func (ee *ExErr) Unwrap() error {
|
||||
return ee.OriginalError
|
||||
}
|
||||
|
||||
// Is must be implemented so that error.Is(x) works
|
||||
func (ee *ExErr) Is(e error) bool {
|
||||
return IsFrom(ee, e)
|
||||
}
|
||||
|
||||
func (ee *ExErr) Log(evt *zerolog.Event) {
|
||||
evt.Msg(ee.FormatLog(LogPrintFull))
|
||||
}
|
||||
|
56
exerr/gin.go
56
exerr/gin.go
@@ -3,12 +3,13 @@ package exerr
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
json "gogs.mikescher.com/BlackForestBytes/goext/gojson"
|
||||
"gogs.mikescher.com/BlackForestBytes/goext/langext"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (ee *ExErr) toJson(depth int) gin.H {
|
||||
ginJson := gin.H{}
|
||||
func (ee *ExErr) toJson(depth int, applyExtendListener bool) langext.H {
|
||||
ginJson := langext.H{}
|
||||
|
||||
if ee.UniqueID != "" {
|
||||
ginJson["id"] = ee.UniqueID
|
||||
@@ -38,21 +39,51 @@ func (ee *ExErr) toJson(depth int) gin.H {
|
||||
ginJson["wrappedErrType"] = ee.WrappedErrType
|
||||
}
|
||||
if ee.OriginalError != nil {
|
||||
ginJson["original"] = ee.OriginalError.toJson(depth + 1)
|
||||
ginJson["original"] = ee.OriginalError.toJson(depth+1, applyExtendListener)
|
||||
}
|
||||
|
||||
pkgconfig.ExtendGinDataOutput(ee, depth, ginJson)
|
||||
if applyExtendListener {
|
||||
pkgconfig.ExtendGinDataOutput(ee, depth, ginJson)
|
||||
}
|
||||
|
||||
return ginJson
|
||||
}
|
||||
|
||||
// ToAPIJson converts the ExError to a json object
|
||||
// (the same object as used in the Output(gin) method)
|
||||
//
|
||||
// Parameters:
|
||||
// - [applyExtendListener]: if false the pkgconfig.ExtendGinOutput / pkgconfig.ExtendGinDataOutput will not be applied
|
||||
// - [includeWrappedErrors]: if false we do not include the recursive/wrapped errors in `__data`
|
||||
func (ee *ExErr) ToAPIJson(applyExtendListener bool, includeWrappedErrors bool) langext.H {
|
||||
|
||||
apiOutput := langext.H{
|
||||
"errorid": ee.UniqueID,
|
||||
"message": ee.RecursiveMessage(),
|
||||
"errorcode": ee.RecursiveType().Key,
|
||||
"category": ee.RecursiveCategory().Category,
|
||||
}
|
||||
|
||||
if includeWrappedErrors {
|
||||
apiOutput["__data"] = ee.toJson(0, applyExtendListener)
|
||||
}
|
||||
|
||||
if applyExtendListener {
|
||||
pkgconfig.ExtendGinOutput(ee, apiOutput)
|
||||
}
|
||||
|
||||
return apiOutput
|
||||
}
|
||||
|
||||
func (ee *ExErr) Output(g *gin.Context) {
|
||||
|
||||
warnOnPkgConfigNotInitialized()
|
||||
|
||||
var statuscode = http.StatusInternalServerError
|
||||
|
||||
var baseCat = ee.RecursiveCategory()
|
||||
var baseType = ee.RecursiveType()
|
||||
var baseStatuscode = ee.RecursiveStatuscode()
|
||||
var baseMessage = ee.RecursiveMessage()
|
||||
|
||||
if baseCat == CatUser {
|
||||
statuscode = http.StatusBadRequest
|
||||
@@ -66,20 +97,7 @@ func (ee *ExErr) Output(g *gin.Context) {
|
||||
statuscode = *baseType.DefaultStatusCode
|
||||
}
|
||||
|
||||
warnOnPkgConfigNotInitialized()
|
||||
|
||||
ginOutput := gin.H{
|
||||
"errorid": ee.UniqueID,
|
||||
"message": baseMessage,
|
||||
"errorcode": baseType.Key,
|
||||
"category": baseCat.Category,
|
||||
}
|
||||
|
||||
if pkgconfig.ExtendedGinOutput {
|
||||
ginOutput["__data"] = ee.toJson(0)
|
||||
}
|
||||
|
||||
pkgconfig.ExtendGinOutput(ee, ginOutput)
|
||||
ginOutput := ee.ToAPIJson(true, pkgconfig.ExtendedGinOutput)
|
||||
|
||||
g.Render(statuscode, json.GoJsonRender{Data: ginOutput, NilSafeSlices: true, NilSafeMaps: true})
|
||||
}
|
||||
|
@@ -24,6 +24,8 @@ func IsFrom(e error, original error) bool {
|
||||
if e == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
//goland:noinspection GoDirectComparisonOfErrors
|
||||
if e == original {
|
||||
return true
|
||||
}
|
||||
|
@@ -14,6 +14,9 @@ type AppContext struct {
|
||||
}
|
||||
|
||||
func CreateAppContext(g *gin.Context, innerCtx context.Context, cancelFn context.CancelFunc) *AppContext {
|
||||
for key, value := range g.Keys {
|
||||
innerCtx = context.WithValue(innerCtx, key, value)
|
||||
}
|
||||
return &AppContext{
|
||||
inner: innerCtx,
|
||||
cancelFunc: cancelFn,
|
||||
@@ -38,6 +41,10 @@ func (ac *AppContext) Value(key any) any {
|
||||
return ac.inner.Value(key)
|
||||
}
|
||||
|
||||
func (ac *AppContext) Set(key, value any) {
|
||||
ac.inner = context.WithValue(ac.inner, key, value)
|
||||
}
|
||||
|
||||
func (ac *AppContext) Cancel() {
|
||||
ac.cancelled = true
|
||||
ac.cancelFunc()
|
||||
|
@@ -118,8 +118,8 @@ func (w *GinWrapper) DebugPrintRoutes() {
|
||||
line := [4]string{
|
||||
spec.Method,
|
||||
spec.URL,
|
||||
strings.Join(spec.Middlewares, " --> "),
|
||||
spec.Method,
|
||||
strings.Join(spec.Middlewares, " -> "),
|
||||
spec.Handler,
|
||||
}
|
||||
|
||||
lines = append(lines, line)
|
||||
@@ -132,8 +132,8 @@ func (w *GinWrapper) DebugPrintRoutes() {
|
||||
|
||||
for _, line := range lines {
|
||||
|
||||
fmt.Printf("Gin-Route: [%s] @ %s --> %s --> %s\n",
|
||||
langext.StrPadRight(line[0], " ", pad[0]),
|
||||
fmt.Printf("Gin-Route: %s %s --> %s --> %s\n",
|
||||
langext.StrPadRight("["+line[0]+"]", " ", pad[0]+2),
|
||||
langext.StrPadRight(line[1], " ", pad[1]),
|
||||
langext.StrPadRight(line[2], " ", pad[2]),
|
||||
langext.StrPadRight(line[3], " ", pad[3]))
|
||||
|
@@ -25,7 +25,7 @@ func Wrap(w *GinWrapper, fn WHandlerFunc) gin.HandlerFunc {
|
||||
Str("trace", stackTrace).
|
||||
Build()
|
||||
|
||||
wrap = APIError(g, err)
|
||||
wrap = Error(err)
|
||||
}
|
||||
|
||||
if g.Writer.Written() {
|
||||
|
@@ -52,7 +52,7 @@ func (pctx PreContext) Start() (*AppContext, *gin.Context, *HTTPResponse) {
|
||||
WithType(exerr.TypeBindFailURI).
|
||||
Str("struct_type", fmt.Sprintf("%T", pctx.uri)).
|
||||
Build()
|
||||
return nil, nil, langext.Ptr(APIError(pctx.ginCtx, err))
|
||||
return nil, nil, langext.Ptr(Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ func (pctx PreContext) Start() (*AppContext, *gin.Context, *HTTPResponse) {
|
||||
WithType(exerr.TypeBindFailQuery).
|
||||
Str("struct_type", fmt.Sprintf("%T", pctx.query)).
|
||||
Build()
|
||||
return nil, nil, langext.Ptr(APIError(pctx.ginCtx, err))
|
||||
return nil, nil, langext.Ptr(Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,13 +73,13 @@ func (pctx PreContext) Start() (*AppContext, *gin.Context, *HTTPResponse) {
|
||||
WithType(exerr.TypeBindFailJSON).
|
||||
Str("struct_type", fmt.Sprintf("%T", pctx.body)).
|
||||
Build()
|
||||
return nil, nil, langext.Ptr(APIError(pctx.ginCtx, err))
|
||||
return nil, nil, langext.Ptr(Error(err))
|
||||
}
|
||||
} else {
|
||||
err := exerr.New(exerr.TypeBindFailJSON, "missing JSON body").
|
||||
Str("struct_type", fmt.Sprintf("%T", pctx.body)).
|
||||
Build()
|
||||
return nil, nil, langext.Ptr(APIError(pctx.ginCtx, err))
|
||||
return nil, nil, langext.Ptr(Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,13 +90,13 @@ func (pctx PreContext) Start() (*AppContext, *gin.Context, *HTTPResponse) {
|
||||
WithType(exerr.TypeBindFailFormData).
|
||||
Str("struct_type", fmt.Sprintf("%T", pctx.form)).
|
||||
Build()
|
||||
return nil, nil, langext.Ptr(APIError(pctx.ginCtx, err))
|
||||
return nil, nil, langext.Ptr(Error(err))
|
||||
}
|
||||
} else {
|
||||
err := exerr.New(exerr.TypeBindFailFormData, "missing form body").
|
||||
Str("struct_type", fmt.Sprintf("%T", pctx.form)).
|
||||
Build()
|
||||
return nil, nil, langext.Ptr(APIError(pctx.ginCtx, err))
|
||||
return nil, nil, langext.Ptr(Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ func (pctx PreContext) Start() (*AppContext, *gin.Context, *HTTPResponse) {
|
||||
WithType(exerr.TypeBindFailHeader).
|
||||
Str("struct_type", fmt.Sprintf("%T", pctx.query)).
|
||||
Build()
|
||||
return nil, nil, langext.Ptr(APIError(pctx.ginCtx, err))
|
||||
return nil, nil, langext.Ptr(Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -170,12 +170,18 @@ func Redirect(sc int, newURL string) HTTPResponse {
|
||||
return &redirectHTTPResponse{statusCode: sc, url: newURL}
|
||||
}
|
||||
|
||||
func APIError(g *gin.Context, e error) HTTPResponse {
|
||||
func Error(e error) HTTPResponse {
|
||||
return &jsonAPIErrResponse{
|
||||
err: exerr.FromError(e),
|
||||
}
|
||||
}
|
||||
|
||||
func NotImplemented(g *gin.Context) HTTPResponse {
|
||||
return APIError(g, exerr.New(exerr.TypeNotImplemented, "").Build())
|
||||
func ErrWrap(e error, errorType exerr.ErrorType, msg string) HTTPResponse {
|
||||
return &jsonAPIErrResponse{
|
||||
err: exerr.FromError(exerr.Wrap(e, msg).WithType(errorType).Build()),
|
||||
}
|
||||
}
|
||||
|
||||
func NotImplemented() HTTPResponse {
|
||||
return Error(exerr.New(exerr.TypeNotImplemented, "").Build())
|
||||
}
|
||||
|
@@ -3,8 +3,11 @@ package ginext
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gogs.mikescher.com/BlackForestBytes/goext/langext"
|
||||
"gogs.mikescher.com/BlackForestBytes/goext/rext"
|
||||
"net/http"
|
||||
"path"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
@@ -18,6 +21,7 @@ var anyMethods = []string{
|
||||
type GinRoutesWrapper struct {
|
||||
wrapper *GinWrapper
|
||||
routes gin.IRouter
|
||||
absPath string
|
||||
defaultHandler []gin.HandlerFunc
|
||||
}
|
||||
|
||||
@@ -26,15 +30,26 @@ type GinRouteBuilder struct {
|
||||
|
||||
method string
|
||||
relPath string
|
||||
absPath string
|
||||
handlers []gin.HandlerFunc
|
||||
}
|
||||
|
||||
func (w *GinWrapper) Routes() *GinRoutesWrapper {
|
||||
return &GinRoutesWrapper{wrapper: w, routes: w.engine}
|
||||
return &GinRoutesWrapper{
|
||||
wrapper: w,
|
||||
routes: w.engine,
|
||||
absPath: "",
|
||||
defaultHandler: make([]gin.HandlerFunc, 0),
|
||||
}
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) Group(relativePath string) *GinRoutesWrapper {
|
||||
return &GinRoutesWrapper{wrapper: w.wrapper, routes: w.routes.Group(relativePath), defaultHandler: langext.ArrCopy(w.defaultHandler)}
|
||||
return &GinRoutesWrapper{
|
||||
wrapper: w.wrapper,
|
||||
routes: w.routes.Group(relativePath),
|
||||
defaultHandler: langext.ArrCopy(w.defaultHandler),
|
||||
absPath: joinPaths(w.absPath, relativePath),
|
||||
}
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) Use(middleware ...gin.HandlerFunc) *GinRoutesWrapper {
|
||||
@@ -44,39 +59,49 @@ func (w *GinRoutesWrapper) Use(middleware ...gin.HandlerFunc) *GinRoutesWrapper
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) GET(relativePath string) *GinRouteBuilder {
|
||||
return &GinRouteBuilder{routes: w, method: http.MethodGet, relPath: relativePath, handlers: langext.ArrCopy(w.defaultHandler)}
|
||||
return w._route(http.MethodGet, relativePath)
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) POST(relativePath string) *GinRouteBuilder {
|
||||
return &GinRouteBuilder{routes: w, method: http.MethodPost, relPath: relativePath, handlers: langext.ArrCopy(w.defaultHandler)}
|
||||
return w._route(http.MethodPost, relativePath)
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) DELETE(relativePath string) *GinRouteBuilder {
|
||||
return &GinRouteBuilder{routes: w, method: http.MethodDelete, relPath: relativePath, handlers: langext.ArrCopy(w.defaultHandler)}
|
||||
return w._route(http.MethodDelete, relativePath)
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) PATCH(relativePath string) *GinRouteBuilder {
|
||||
return &GinRouteBuilder{routes: w, method: http.MethodPatch, relPath: relativePath, handlers: langext.ArrCopy(w.defaultHandler)}
|
||||
return w._route(http.MethodPatch, relativePath)
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) PUT(relativePath string) *GinRouteBuilder {
|
||||
return &GinRouteBuilder{routes: w, method: http.MethodPut, relPath: relativePath, handlers: langext.ArrCopy(w.defaultHandler)}
|
||||
return w._route(http.MethodPut, relativePath)
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) OPTIONS(relativePath string) *GinRouteBuilder {
|
||||
return &GinRouteBuilder{routes: w, method: http.MethodOptions, relPath: relativePath, handlers: langext.ArrCopy(w.defaultHandler)}
|
||||
return w._route(http.MethodOptions, relativePath)
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) HEAD(relativePath string) *GinRouteBuilder {
|
||||
return &GinRouteBuilder{routes: w, method: http.MethodHead, relPath: relativePath, handlers: langext.ArrCopy(w.defaultHandler)}
|
||||
return w._route(http.MethodHead, relativePath)
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) COUNT(relativePath string) *GinRouteBuilder {
|
||||
return &GinRouteBuilder{routes: w, method: "COUNT", relPath: relativePath, handlers: langext.ArrCopy(w.defaultHandler)}
|
||||
return w._route("COUNT", relativePath)
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) Any(relativePath string) *GinRouteBuilder {
|
||||
return &GinRouteBuilder{routes: w, method: "*", relPath: relativePath, handlers: langext.ArrCopy(w.defaultHandler)}
|
||||
return w._route("*", relativePath)
|
||||
}
|
||||
|
||||
func (w *GinRoutesWrapper) _route(method string, relativePath string) *GinRouteBuilder {
|
||||
return &GinRouteBuilder{
|
||||
routes: w,
|
||||
method: method,
|
||||
relPath: relativePath,
|
||||
absPath: joinPaths(w.absPath, relativePath),
|
||||
handlers: langext.ArrCopy(w.defaultHandler),
|
||||
}
|
||||
}
|
||||
|
||||
func (w *GinRouteBuilder) Use(middleware ...gin.HandlerFunc) *GinRouteBuilder {
|
||||
@@ -104,7 +129,7 @@ func (w *GinRouteBuilder) Handle(handler WHandlerFunc) {
|
||||
|
||||
w.routes.wrapper.routeSpecs = append(w.routes.wrapper.routeSpecs, ginRouteSpec{
|
||||
Method: methodName,
|
||||
URL: w.relPath,
|
||||
URL: w.absPath,
|
||||
Middlewares: middlewareNames,
|
||||
Handler: handlerName,
|
||||
})
|
||||
@@ -123,12 +148,45 @@ func (w *GinWrapper) NoRoute(handler WHandlerFunc) {
|
||||
|
||||
func nameOfFunction(f any) string {
|
||||
|
||||
n := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
|
||||
fname := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
|
||||
|
||||
split := strings.Split(n, "/")
|
||||
split := strings.Split(fname, "/")
|
||||
if len(split) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
return split[len(split)-1]
|
||||
fname = split[len(split)-1]
|
||||
|
||||
// https://stackoverflow.com/a/32925345/1761622
|
||||
if strings.HasSuffix(fname, "-fm") {
|
||||
fname = fname[:len(fname)-len("-fm")]
|
||||
}
|
||||
|
||||
suffix := rext.W(regexp.MustCompile(`\.func[0-9]+(?:\.[0-9]+)*$`))
|
||||
|
||||
if match, ok := suffix.MatchFirst(fname); ok {
|
||||
fname = fname[:len(fname)-match.FullMatch().Length()]
|
||||
}
|
||||
|
||||
return fname
|
||||
}
|
||||
|
||||
// joinPaths is copied verbatim from gin@v1.9.1/gin.go
|
||||
func joinPaths(absolutePath, relativePath string) string {
|
||||
if relativePath == "" {
|
||||
return absolutePath
|
||||
}
|
||||
|
||||
finalPath := path.Join(absolutePath, relativePath)
|
||||
if lastChar(relativePath) == '/' && lastChar(finalPath) != '/' {
|
||||
return finalPath + "/"
|
||||
}
|
||||
return finalPath
|
||||
}
|
||||
|
||||
func lastChar(str string) uint8 {
|
||||
if str == "" {
|
||||
panic("The length of the string can't be 0")
|
||||
}
|
||||
return str[len(str)-1]
|
||||
}
|
||||
|
2
go.mod
2
go.mod
@@ -14,7 +14,7 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.10.0-rc2 // indirect
|
||||
github.com/bytedance/sonic v1.10.0-rc3 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
|
||||
github.com/chenzhuoyu/iasm v0.9.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
|
2
go.sum
2
go.sum
@@ -2,6 +2,8 @@ github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1
|
||||
github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
|
||||
github.com/bytedance/sonic v1.10.0-rc2 h1:oDfRZ+4m6AYCOC0GFeOCeYqvBmucy1isvouS2K0cPzo=
|
||||
github.com/bytedance/sonic v1.10.0-rc2/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
|
||||
github.com/bytedance/sonic v1.10.0-rc3 h1:uNSnscRapXTwUgTyOF0GVljYD08p9X/Lbr9MweSV3V0=
|
||||
github.com/bytedance/sonic v1.10.0-rc3/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0=
|
||||
|
@@ -1,5 +1,5 @@
|
||||
package goext
|
||||
|
||||
const GoextVersion = "0.0.203"
|
||||
const GoextVersion = "0.0.219"
|
||||
|
||||
const GoextVersionTimestamp = "2023-07-24T18:38:04+0200"
|
||||
const GoextVersionTimestamp = "2023-07-28T15:42:12+0200"
|
||||
|
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
func TestGroupByNameOrEmpty1(t *testing.T) {
|
||||
|
||||
regex1 := W(regexp.MustCompile("0(?P<group1>A+)B(?P<group2>C+)0"))
|
||||
regex1 := W(regexp.MustCompile(`0(?P<group1>A+)B(?P<group2>C+)0`))
|
||||
|
||||
match1, ok1 := regex1.MatchFirst("Hello 0AAAABCCC0 Bye.")
|
||||
|
||||
@@ -26,7 +26,7 @@ func TestGroupByNameOrEmpty1(t *testing.T) {
|
||||
|
||||
func TestGroupByNameOrEmpty2(t *testing.T) {
|
||||
|
||||
regex1 := W(regexp.MustCompile("0(?P<group1>A+)B(?P<group2>C+)(?P<group3>C+)?0"))
|
||||
regex1 := W(regexp.MustCompile(`0(?P<group1>A+)B(?P<group2>C+)(?P<group3>C+)?0`))
|
||||
|
||||
match1, ok1 := regex1.MatchFirst("Hello 0AAAABCCC0 Bye.")
|
||||
|
||||
|
@@ -39,7 +39,7 @@ func HashSqliteSchema(ctx context.Context, schemaStr string) (string, error) {
|
||||
return HashSqliteDatabase(ctx, db)
|
||||
}
|
||||
|
||||
func HashSqliteDatabase(ctx context.Context, db DB) (string, error) {
|
||||
func HashSqliteDatabase(ctx context.Context, db Queryable) (string, error) {
|
||||
ss, err := CreateSqliteDatabaseSchemaString(ctx, db)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -50,7 +50,7 @@ func HashSqliteDatabase(ctx context.Context, db DB) (string, error) {
|
||||
return hex.EncodeToString(cs[:]), nil
|
||||
}
|
||||
|
||||
func CreateSqliteDatabaseSchemaString(ctx context.Context, db DB) (string, error) {
|
||||
func CreateSqliteDatabaseSchemaString(ctx context.Context, db Queryable) (string, error) {
|
||||
|
||||
type colInfo struct {
|
||||
Name string `db:"name"`
|
||||
|
@@ -7,24 +7,40 @@ import (
|
||||
"gogs.mikescher.com/BlackForestBytes/goext/langext"
|
||||
)
|
||||
|
||||
type TxStatus string
|
||||
|
||||
const (
|
||||
TxStatusInitial TxStatus = "INITIAL"
|
||||
TxStatusActive TxStatus = "ACTIVE"
|
||||
TxStatusComitted TxStatus = "COMMITTED"
|
||||
TxStatusRollback TxStatus = "ROLLBACK"
|
||||
)
|
||||
|
||||
type Tx interface {
|
||||
Rollback() error
|
||||
Commit() error
|
||||
Status() TxStatus
|
||||
Exec(ctx context.Context, sql string, prep PP) (sql.Result, error)
|
||||
Query(ctx context.Context, sql string, prep PP) (*sqlx.Rows, error)
|
||||
}
|
||||
|
||||
type transaction struct {
|
||||
tx *sqlx.Tx
|
||||
id uint16
|
||||
lstr []Listener
|
||||
tx *sqlx.Tx
|
||||
id uint16
|
||||
lstr []Listener
|
||||
status TxStatus
|
||||
execCtr int
|
||||
queryCtr int
|
||||
}
|
||||
|
||||
func NewTransaction(xtx *sqlx.Tx, txid uint16, lstr []Listener) Tx {
|
||||
return &transaction{
|
||||
tx: xtx,
|
||||
id: txid,
|
||||
lstr: lstr,
|
||||
tx: xtx,
|
||||
id: txid,
|
||||
lstr: lstr,
|
||||
status: TxStatusInitial,
|
||||
execCtr: 0,
|
||||
queryCtr: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +54,10 @@ func (tx *transaction) Rollback() error {
|
||||
|
||||
result := tx.tx.Rollback()
|
||||
|
||||
if result == nil {
|
||||
tx.status = TxStatusRollback
|
||||
}
|
||||
|
||||
for _, v := range tx.lstr {
|
||||
v.PostTxRollback(tx.id, result)
|
||||
}
|
||||
@@ -55,6 +75,10 @@ func (tx *transaction) Commit() error {
|
||||
|
||||
result := tx.tx.Commit()
|
||||
|
||||
if result == nil {
|
||||
tx.status = TxStatusComitted
|
||||
}
|
||||
|
||||
for _, v := range tx.lstr {
|
||||
v.PostTxRollback(tx.id, result)
|
||||
}
|
||||
@@ -73,6 +97,10 @@ func (tx *transaction) Exec(ctx context.Context, sqlstr string, prep PP) (sql.Re
|
||||
|
||||
res, err := tx.tx.NamedExecContext(ctx, sqlstr, prep)
|
||||
|
||||
if tx.status == TxStatusInitial && err == nil {
|
||||
tx.status = TxStatusActive
|
||||
}
|
||||
|
||||
for _, v := range tx.lstr {
|
||||
v.PostExec(langext.Ptr(tx.id), origsql, sqlstr, prep)
|
||||
}
|
||||
@@ -94,6 +122,10 @@ func (tx *transaction) Query(ctx context.Context, sqlstr string, prep PP) (*sqlx
|
||||
|
||||
rows, err := sqlx.NamedQueryContext(ctx, tx.tx, sqlstr, prep)
|
||||
|
||||
if tx.status == TxStatusInitial && err == nil {
|
||||
tx.status = TxStatusActive
|
||||
}
|
||||
|
||||
for _, v := range tx.lstr {
|
||||
v.PostQuery(langext.Ptr(tx.id), origsql, sqlstr, prep)
|
||||
}
|
||||
@@ -103,3 +135,11 @@ func (tx *transaction) Query(ctx context.Context, sqlstr string, prep PP) (*sqlx
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (tx *transaction) Status() TxStatus {
|
||||
return tx.status
|
||||
}
|
||||
|
||||
func (tx *transaction) Traffic() (int, int) {
|
||||
return tx.execCtr, tx.queryCtr
|
||||
}
|
||||
|
@@ -71,12 +71,12 @@ func SupportsColors() bool {
|
||||
}
|
||||
}
|
||||
|
||||
var term256Regex = regexp.MustCompile("(?i)-256(color)?$")
|
||||
var term256Regex = regexp.MustCompile(`(?i)-256(color)?$`)
|
||||
if term256Regex.MatchString(termenv) {
|
||||
return true
|
||||
}
|
||||
|
||||
var termBasicRegex = regexp.MustCompile("(?i)^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux")
|
||||
var termBasicRegex = regexp.MustCompile(`(?i)^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux`)
|
||||
|
||||
if termBasicRegex.MatchString(termenv) {
|
||||
return true
|
||||
|
Reference in New Issue
Block a user