Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/refine sentry #40

Merged
merged 10 commits into from
Feb 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
.vscode
.idea
golangci-lint
bean
bean$
main
internal/project/go.mod
internal/project/go.sum
Expand Down
12 changes: 5 additions & 7 deletions internal/project/commands/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ package commands
import (
"log"
"os"
"runtime/debug"

/**#bean*/
"demo/framework/internals/helpers"
/*#bean.replace("{{ .PkgPath }}/framework/internals/helpers")**/

"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand Down Expand Up @@ -34,12 +37,7 @@ func init() {
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.CompletionOptions.DisableDefaultCmd = true

if bi, ok := debug.ReadBuildInfo(); ok {
rootCmd.Version = bi.Main.Version
} else {
log.Fatalln("Failed to read build info")
}
rootCmd.Version = helpers.CurrVersion()

viper.AddConfigPath(".")
viper.SetConfigType("json")
Expand Down
65 changes: 39 additions & 26 deletions internal/project/commands/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import (
"demo/framework/bean"
/*#bean.replace("{{ .PkgPath }}/framework/bean")**/
/**#bean*/
berror "demo/framework/internals/error"
/*#bean.replace(berror "{{ .PkgPath }}/framework/internals/error")**/
/**#bean*/
beanValidator "demo/framework/internals/validator"
/*#bean.replace(beanValidator "{{ .PkgPath }}/framework/internals/validator")**/
/**#bean*/
Expand Down Expand Up @@ -35,15 +38,6 @@ var (

func init() {
rootCmd.AddCommand(startCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// startCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
defaultHost := viper.GetString("http.host")
defaultPort := viper.GetString("http.port")
startCmd.Flags().StringVar(&host, "host", defaultHost, "host address")
Expand All @@ -58,31 +52,50 @@ func start(cmd *cobra.Command, args []string) {
// Create a bean object
b := bean.New()

b.BeforeServe = func() {
// Init global middleware if you need
// middlerwares.Init()

// Init DB dependency.
b.InitDB()

// Init different routes.
routers.Init(b)
}

// Below is an example of how you can initialize your own validator. Just create a new directory
// as `packages/validator` and create a validator package inside the directory. Then initialize your
// own validation function here, such as; `validator.MyTestValidationFunction(c, vd)`.
b.Validate = func(c echo.Context, vd *validator.Validate) {
beanValidator.TestUserIdValidation(c, vd)

// Add your own validation function here.
}

// Below is an example of how you can set custom error handler middleware
// bean can call `UseErrorHandlerMiddleware` multiple times
b.UseErrorHandlerMiddleware(func(e error, c echo.Context) (bool, error) {
return false, nil
})
// Set custom middleware in here.
b.UseMiddlewares(
// Example:
// func(arg string) echo.MiddlewareFunc {
// return func(next echo.HandlerFunc) echo.HandlerFunc {
// return func(c echo.Context) error {
// c.Logger().Info(arg)
// return next(c)
// }
// }
// }("example"),
)

// Set custom error handler function here.
// Bean use a error function chain inside the default http error handler,
// so that it can easily add or remove the different kind of error handling.
b.UseErrorHandlerFuncs(
berror.ValidationErrorHanderFunc,
berror.APIErrorHanderFunc,
berror.EchoHTTPErrorHanderFunc,
// Set your custom error handler func here, for example:
// func(e error, c echo.Context) (bool, error) {
// return false, nil
// },
)

b.BeforeServe = func() {
// Init DB dependency.
b.InitDB()

// Init different routes.
routers.Init(b)

// You can also replace the default error handler.
// b.Echo.HTTPErrorHandler = YourErrorHandler()
}

b.ServeAt(host, port)
}
9 changes: 4 additions & 5 deletions internal/project/env.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@
"skipEndpoints": ["/ping", "/route/stats"]
},
"http": {
"port": 8888,
"port": "8888",
"host": "0.0.0.0",
"bodyLimit": "1M",
"isHttpsRedirect": false,
"uriLatencyIntervals": [5, 10, 15],
"timeout": "24s",
"keepAlive": true
},
Expand Down Expand Up @@ -66,14 +65,14 @@
"redis": {
"password": "64vc7632-62dc-482e-67fg-046c7faec493",
"host": "127.0.0.1",
"port": 6379,
"port": "6379",
"name": 3,
"prefix": "{{ .PkgName }}_queue",
"poolsize": 100,
"maxidle": 2
},
"health": {
"port": 7777,
"port": "7777",
"host": "0.0.0.0"
}
},
Expand All @@ -83,9 +82,9 @@
},
"sentry": {
"on": true,
"debug": true,
"dsn": "",
"timeout": "5s",
"attachStacktrace": true,
"tracesSampleRate": 1.0
},
"security": {
Expand Down
78 changes: 52 additions & 26 deletions internal/project/framework/bean/bean.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package bean

import (
"net/http"

/**#bean*/
"demo/framework/kernel"
/*#bean.replace("{{ .PkgPath }}/framework/kernel")**/
Expand All @@ -18,8 +19,12 @@ import (
/**#bean*/
validate "demo/framework/internals/validator"
/*#bean.replace(validate "{{ .PkgPath }}/framework/internals/validator")**/
/**#bean*/
"demo/packages/options"
/*#bean.replace("{{ .PkgPath }}/packages/options")**/

"github.com/dgraph-io/badger/v3"
"github.com/getsentry/sentry-go"
"github.com/go-playground/validator/v10"
"github.com/go-redis/redis/v8"
"github.com/labstack/echo/v4"
Expand All @@ -46,12 +51,12 @@ type DBDeps struct {
}

type Bean struct {
DBConn *DBDeps
Echo *echo.Echo
Environment string
Validate func(c echo.Context, vd *validator.Validate)
BeforeServe func()
errorHandlerMiddlewares []berror.ErrorHandlerMiddleware
DBConn *DBDeps
Echo *echo.Echo
Environment string
Validate func(c echo.Context, vd *validator.Validate)
BeforeServe func()
errorHandlerFuncs []berror.ErrorHandlerFunc
}

func New() (b *Bean) {
Expand All @@ -69,27 +74,16 @@ func New() (b *Bean) {
}

func (b *Bean) ServeAt(host, port string) {
// before bean bootstrap
if b.BeforeServe != nil {
b.BeforeServe()
}

b.UseErrorHandlerMiddleware(
berror.ValidationErrorHanderMiddleware,
berror.APIErrorHanderMiddleware,
berror.HTTPErrorHanderMiddleware,
berror.DefaultErrorHanderMiddleware,
)
projectName := viper.GetString("projectName")
env := viper.GetString("environment")
b.Echo.Logger.Info("Starting " + projectName + " at " + env + "...🚀")

b.Echo.HTTPErrorHandler = berror.ErrorHandlerChain(b.errorHandlerMiddlewares...)
b.UseErrorHandlerFuncs(berror.DefaultErrorHanderFunc)
b.Echo.HTTPErrorHandler = DefaultHTTPErrorHandler(b.errorHandlerFuncs...)

// Initialize and bind the validator to echo instance
validate.BindCustomValidator(b.Echo, b.Validate)

projectName := viper.GetString("name")

b.Echo.Logger.Info(`Starting ` + projectName + ` server...🚀`)

s := http.Server{
Addr: host + ":" + port,
Handler: b.Echo,
Expand All @@ -99,17 +93,49 @@ func (b *Bean) ServeAt(host, port string) {
// for it :)
s.SetKeepAlivesEnabled(viper.GetBool("http.keepAlive"))

// before bean bootstrap
if b.BeforeServe != nil {
b.BeforeServe()
}

// Start the server
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
b.Echo.Logger.Fatal(err)
}
}

func (b *Bean) UseErrorHandlerMiddleware(errorHandlerMiddleware ...berror.ErrorHandlerMiddleware) {
if b.errorHandlerMiddlewares == nil {
b.errorHandlerMiddlewares = []berror.ErrorHandlerMiddleware{}
func (b *Bean) UseMiddlewares(middlewares ...echo.MiddlewareFunc) {
b.Echo.Use(middlewares...)
}

func (b *Bean) UseErrorHandlerFuncs(errHdlrFuncs ...berror.ErrorHandlerFunc) {
if b.errorHandlerFuncs == nil {
b.errorHandlerFuncs = []berror.ErrorHandlerFunc{}
}
b.errorHandlerFuncs = append(b.errorHandlerFuncs, errHdlrFuncs...)
}

func DefaultHTTPErrorHandler(errHdlrFuncs ...berror.ErrorHandlerFunc) echo.HTTPErrorHandler {
return func(err error, c echo.Context) {

if c.Response().Committed {
return
}

for _, handle := range errHdlrFuncs {
handled, err := handle(err, c)
if err != nil {
if options.SentryOn {
sentry.CaptureException(err)
} else {
c.Logger().Error(err)
}
}
if handled {
break
}
}
}
b.errorHandlerMiddlewares = append(b.errorHandlerMiddlewares, errorHandlerMiddleware...)
}

// InitDB initialize all the database dependencies and store it in global variable `global.DBConn`.
Expand Down
Loading