# Guard

<figure><img src="/files/NyuEPKPRensFLGXXRDzJ" 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
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://elchemist.gitbook.io/tinh-tinh/core-fundamental/guard.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
