> For the complete documentation index, see [llms.txt](https://elchemist.gitbook.io/tinh-tinh/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://elchemist.gitbook.io/tinh-tinh/core-fundamental/guard.md).

# Guard

<figure><img src="https://2541580492-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtKnxvxRflr41Wbs7ajzp%2Fuploads%2F6YaC412iBMiPv94cJ3rx%2FTinhTinh-Guard.drawio.png?alt=media&amp;token=073c8b64-87a0-4d4c-9ec4-b11da67e2fae" alt=""><figcaption></figcaption></figure>

Guard is a middleware only use for manage access in route. It is a function return bool value if true the route can be handler, else app will throw 403 error. Have two guard for each level. `Guard` for Controller and `AppGuard` for Module.

```go
type Guard func(ctrl *DynamicController, ctx *Ctx) bool

type AppGuard func(module *DynamicModule, ctx Ctx) bool
```

### Define guard and use in controller

```go
package app

import "github.com/tinh-tinh/tinhtinh/core"

func QueryGuard(ctrl *DynamicController, ctx *Ctx) bool {
    return ctx.Query("key") == "value"
}

func Controller(module *core.DynamicModule) *core.DynamicController {
    ctrl := module.NewController("test")
    
    ctrl.Guard(QueryGuard).Get("", func (ctx core.Ctx) error {
        return ctx.JSON(core.Map{
            "data": "ok",
        })
    })
    
    return ctrl
}
```

### Define guard and use in module

```go
package app

import "github.com/tinh-tinh/tinhtinh/core"

func QueryGuard(module *core.DynamicModule, ctx *Ctx) bool {
    return ctx.Query("key") == "value"
}

func Controller(module *core.DynamicModule) *core.DynamicModule {
    mod := module.New(core.NewModuleOptions{
        Guards: []core.AppGuard{QueryGuard},
    })
    
    return mod
}
```
