# README

GoAdmin Documentation

{% content-ref url="/pages/-Lvp55\_moHwdXBr5x\_Uu" %}
[English](/en)
{% endcontent-ref %}

{% content-ref url="/pages/-Lvp55\_pCOjRCHiWJFxn" %}
[简体中文](/zh)
{% endcontent-ref %}


# English

GoAdmin is a framework, providing a complete set of visual UI calls to golang programs, and a built-in sql relational database management backend plugin. \
&#x20;\
&#x20;In the past, when we try to build an administrative platform, we needed at least one backend IT engineer, a front-end IT engineer, taking at least a week work. Now with GoAdmin, we don't need front-end IT engineers. Our back-end IT engineers don't even need to know the front-end knowledge. We can build a complete administrative platform or a data visualization platform in half an hour. If your requirements are not so complicated, just simple crud, then all you need are serveral golang files, and all files can be packaged into a single binary file, which is very convenient for distribution and deployment.

Here is a super simple example which quickly shows you how it works: <https://github.com/GoAdminGroup/example>

## Features

* Build-in RBAC Access Authentication System
* Support most web framework
* Support plug-ins(working on it)
* Provided different ui theme(only Adminlte now, others are coming soon.)

## Online Demo

<https://demo.go-admin.com>

## Dependencies

* [Datetimepicker](http://eonasdan.github.io/bootstrap-datetimepicker/)
* [font-awesome](http://fontawesome.io/)
* [bootstrap-fileinput](https://github.com/kartik-v/bootstrap-fileinput)
* [jquery-pjax](https://github.com/defunkt/jquery-pjax)
* [Nestable](http://dbushell.github.io/Nestable/)
* [toastr](http://codeseven.github.io/toastr/)
* [bootstrap-number-input](https://github.com/wpic/bootstrap-number-input)
* [fontawesome-iconpicker](https://github.com/itsjavi/fontawesome-iconpicker)

## Community

[Community](http://discuss.go-admin.com)

## Backers

Your support will help me do better!

[Support Paypal too](https://www.paypal.me/cg80333)


# Get Ready

***

This program is based on `golang`. It is recommended to use `golang` with version higher than 1.11. More infomation, please visit: <https://golang.org>

## Import the program required sql to the corresponding self-built database

The content of the sql file are the data tables required by the framework. Suppose your business database is: `database_a`; then you can import the framework sql into `database_a`, or you can create another database `database_b` to import into. Besides, they can be different driver databases, for example, your business database is `mysql`, the framework database is `sqlite`. GoAdmin currently supports multiple database connection operations. How to configure, will be described in detail later.

* [mysql](https://raw.githubusercontent.com/GoAdminGroup/go-admin/master/data/admin.sql)
* [sqlite](https://raw.githubusercontent.com/GoAdminGroup/go-admin/master/data/admin.db)
* [postgresql](https://raw.githubusercontent.com/GoAdminGroup/go-admin/master/data/admin.pgsql)
* [mssql](https://raw.githubusercontent.com/GoAdminGroup/go-admin/master/data/admin.mssql)

## Install command line tools

Download the binary excecute file:

| File name                                                                                                         | OS      | Arch   | Size    |
| ----------------------------------------------------------------------------------------------------------------- | ------- | ------ | ------- |
| [adm\_darwin\_x86\_64\_v1.2.24.zip](http://file.go-admin.cn/go_admin/cli/v1_2_24/adm_darwin_x86_64_v1.2.24.zip)   | macOs   | x86-64 | 4.77 MB |
| [adm\_linux\_x86\_64\_v1.2.24.zip](http://file.go-admin.cn/go_admin/cli/v1_2_24/adm_linux_x86_64_v1.2.24.zip)     | Linux   | x86-64 | 6.52 MB |
| [adm\_linux\_armel\_v1.2.24.zip](http://file.go-admin.cn/go_admin/cli/v1_2_24/adm_linux_armel_v1.2.24.zip)        | Linux   | x86    | 6.06 MB |
| [adm\_windows\_i386\_v1.2.24.zip](http://file.go-admin.cn/go_admin/cli/v1_2_24/adm_windows_i386_v1.2.24.zip)      | Windows | x86    | 6.16 MB |
| [adm\_windows\_x86\_64\_v1.2.24.zip](http://file.go-admin.cn/go_admin/cli/v1_2_24/adm_windows_x86_64_v1.2.24.zip) | Windows | x86-64 | 6.38 MB |

Or use the command:

```
go install github.com/GoAdminGroup/adm
```

<br>

🍺🍺 Get ready to work here!!

<br>

> English is not my main language. If any typo or wrong translation you found, you can help to translate in [github here](https://github.com/GoAdminGroup/docs). I will very appreciate it.


# Quick Start

GoAdmin makes it easy to use in various web frameworks through various adapters. Currently supported web frameworks are:

* [gin](http://github.com/gin-gonic/gin)
* [beego](https://github.com/astaxie/beego)
* [fasthttp](https://github.com/valyala/fasthttp)
* [buffalo](https://github.com/gobuffalo/buffalo)
* [echo](https://github.com/labstack/echo)
* [gorilla/mux](http://github.com/gorilla/mux)
* [iris](https://github.com/kataras/iris)
* [chi](https://github.com/go-chi/chi)
* [gf](https://github.com/gogf/gf)

You can choose the framework which your own project is using. If there is no framework you like, please feel free to give us an [issue](https://github.com/GoAdminGroup/go-admin/issues/new?assignees=\&labels=\&template=proposal.md\&title=%5BProposal%5D) or pr!

Let's take the gin framework for example to demonstrate the build process.

## main.go

Firstly, create a new `main.go` file in your project folder with the following contents:

```go
package main

import (
    _ "github.com/GoAdminGroup/go-admin/adapter/gin" // Import the adapter, it must be imported. If it is not imported, you need to define it yourself.
    _ "github.com/GoAdminGroup/themes/adminlte" // Import the theme
    _ "github.com/GoAdminGroup/go-admin/modules/db/drivers/mysql" // Import the sql driver

    "github.com/GoAdminGroup/go-admin/engine"
    "github.com/GoAdminGroup/go-admin/modules/config"
    "github.com/GoAdminGroup/go-admin/modules/language"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    // Instantiate a GoAdmin engine object.
    eng := engine.Default()

    // GoAdmin global configuration, can also be imported as a json file.
    cfg := config.Config{
        Databases: []config.Database{
            {
                Host:         "127.0.0.1",
                Port:         "3306",
                User:         "root",
                Pwd:          "root",
                Name:         "godmin",
                MaxIdleCon:   50,
                MaxOpenCon:   150,
                Driver:       "mysql",
            },
        },
        UrlPrefix: "admin", // The url prefix of the website.
        // Store must be set and guaranteed to have write access, otherwise new administrator users cannot be added.
        Store: config.Store{
            Path:   "./uploads",
            Prefix: "uploads",
        },
        Language: language.EN,
    }

    // Add configuration and plugins, use the Use method to mount to the web framework.
    _ = eng.AddConfig(cfg).
        Use(r)

    _ = r.Run(":9033")
}
```

Please pay attention to the above code and comments, the corresponding steps are added to the comments, it is simple to use. Summary of up to five steps:

* Import the adapter, the theme and the sql driver
* Set global configuration items
* Mounted to the web framework

Then execute `go run main.go` to run the code and access: <http://localhost:9033/admin/login> \
&#x20;\
&#x20;default account: admin\
&#x20;default password: admin

more web framework example: <https://github.com/GoAdminGroup/go-admin/tree/master/examples>

## Add your own business table for management

See:

{% content-ref url="/pages/-Lvp7mBD8sOeei5DYdx\_" %}
[How To Use Plugins](/en/plugins/plugins)
{% endcontent-ref %}

{% content-ref url="/pages/-Lvp7mBEtyRq2bJ324o5" %}
[How To Use Admin Plugin](/en/plugins/admin)
{% endcontent-ref %}

## Global configuration item description

<https://github.com/GoAdminGroup/go-admin/blob/master/modules/config/config.go>

```go
package config

import (
    "html/template"
)

// Database is a type of database connection config.
// Because a little difference of different database driver.
// The Config has multiple options but may be not used.
// Such as the sqlite driver only use the FILE option which
// can be ignored when the driver is mysql.
//
// If the Dsn is configured, when driver is mysql/postgresql/
// mssql, the other configurations will be ignored, except for
// MaxIdleCon and MaxOpenCon.
type Database struct {
    Host         string
    Port         string
    User         string
    Pwd          string
    Name         string
    MaxIdleCon   int
    MaxOpenCon   int
    Driver       string
    File         string
    Dsn          string
}

// Database configuration
// which is a map where key is the name of the database connection and 
// value is the corresponding data configuration.
// The key is the default database is the default database, but also 
// the database used by the framework, and you can configure multiple 
// databases to be used by your business tables to manage different databases.
type DatabaseList map[string]Database

// Store is the file store config. Path is the local store path.
// and prefix is the url prefix used to visit it.
type Store struct {
    Path   string
    Prefix string
}

// Config type is the global config of goAdmin. It will be
// initialized in the engine.
type Config struct {
    // An map supports multi database connection. The first
    // element of Databases is the default connection. See the
    // file connection.go.
    Databases DatabaseList `json:"database"`

    // The cookie domain used in the auth modules. see
    // the session.go.
    Domain string `json:"domain"`

    // Used to set as the localize language which show in the
    // interface.
    Language string `json:"language"`

    // The global url prefix.
    UrlPrefix string `json:"prefix"`

    // The theme name of template.
    Theme string `json:"theme"`

    // The path where files will be stored into.
    Store Store `json:"store"`

    // The title of web page.
    Title string `json:"title"`

    // Logo is the top text in the sidebar.
    Logo template.HTML `json:"logo"`

    // Mini-logo is the top text in the sidebar when folding.
    MiniLogo template.HTML `json:"mini_logo"`

    // The url redirect to after login
    IndexUrl string `json:"index"`

    // Debug mode
    Debug bool `json:"debug"`

    // Env is the environment, which maybe local, test, prod.
    Env string

    // Info log path
    InfoLogPath string `json:"info_log"`

    // Error log path
    ErrorLogPath string `json:"error_log"`

    // Access log path
    AccessLogPath string `json:"access_log"`

    // Sql operator record log switch
    SqlLog bool `json:"sql_log"`

    AccessLogOff bool
    InfoLogOff   bool
    ErrorLogOff  bool

    // Color scheme
    ColorScheme string `json:"color_scheme"`

    // Session life time, unit is second.
    SessionLifeTime int `json:"session_life_time"`

    // Cdn link of assets
    AssetUrl string `json:"asset_url"`

    // File upload engine, default "local"
    FileUploadEngine FileUploadEngine `json:"file_upload_engine"`

    // Custom html in the tag head.
    CustomHeadHtml template.HTML `json:"custom_head_html"`

    // Custom html after body.
    CustomFootHtml template.HTML `json:"custom_foot_html"`

    // Login page title
    LoginTitle string `json:"login_title"`

    // Login page logo
    LoginLogo template.HTML `json:"login_logo"`

    // Auth user table
    AuthUserTable string `json:"auth_user_table",yaml:"auth_user_table",ini:"auth_user_table"`

    // Extra config info
    Extra ExtraInfo `json:"extra",yaml:"extra",ini:"extra"`

    // Page animation
    Animation PageAnimation `json:"animation",yaml:"animation",ini:"animation"`

    // Limit login with different IPs
    NoLimitLoginIP bool `json:"no_limit_login_ip",yaml:"no_limit_login_ip",ini:"no_limit_login_ip"`

    // When site off is true, website will be closed
    SiteOff bool `json:"site_off",yaml:"site_off",ini:"site_off"`

    // Hide config center entrance flag
    HideConfigCenterEntrance bool `json:"hide_config_center_entrance",yaml:"hide_config_center_entrance",ini:"hide_config_center_entrance"`

    // Hide app info entrance flag
    HideAppInfoEntrance bool `json:"hide_app_info_entrance",yaml:"hide_app_info_entrance",ini:"hide_app_info_entrance"`

    // Update Process Function
    UpdateProcessFn UpdateConfigProcessFn `json:"-",yaml:"-",ini:"-"`

    // Is open admin plugin json api
    OpenAdminApi bool `json:"open_admin_api",yaml:"open_admin_api",ini:"open_admin_api"`

    HideVisitorUserCenterEntrance bool `json:"hide_visitor_user_center_entrance",yaml:"hide_visitor_user_center_entrance",ini:"hide_visitor_user_center_entrance"`

    // Custom 404 Page
    Custom404HTML template.HTML `json:"custom_404_html,omitempty",yaml:"custom_404_html",ini:"custom_404_html"`

    // Custom 403 Page
    Custom403HTML template.HTML `json:"custom_403_html,omitempty",yaml:"custom_403_html",ini:"custom_403_html"`

    // Custom 500 Page
    Custom500HTML template.HTML `json:"custom_500_html,omitempty",yaml:"custom_500_html",ini:"custom_500_html"`
}
```

Logger configuration:

```go
type Logger struct {
    Encoder EncoderCfg `json:"encoder",yaml:"encoder",ini:"encoder"`
    Rotate  RotateCfg  `json:"rotate",yaml:"rotate",ini:"rotate"`
    Level   int8       `json:"level",yaml:"level",ini:"level"`
}

// Logger encode configuration
type EncoderCfg struct {
    // TimeKey, default is ts
    TimeKey       string `json:"time_key",yaml:"time_key",ini:"time_key"`
    // LevelKey, default is level
    LevelKey      string `json:"level_key",yaml:"level_key",ini:"level_key"`
    // LevelKey, default is logger
    NameKey       string `json:"name_key",yaml:"name_key",ini:"name_key"`
    // CallerKey caller
    CallerKey     string `json:"caller_key",yaml:"caller_key",ini:"caller_key"`
    // MessageKey, default is msg
    MessageKey    string `json:"message_key",yaml:"message_key",ini:"message_key"`
    // StacktraceKey, default is stacktrace
    StacktraceKey string `json:"stacktrace_key",yaml:"stacktrace_key",ini:"stacktrace_key"`
    // Level Encoder, default is CapticalColor
    Level         string `json:"level",yaml:"level",ini:"level"`
    // Time Encoder, default is ISO8601
    Time          string `json:"time",yaml:"time",ini:"time"`
    // Duration Encoder, default is seconds
    Duration      string `json:"duration",yaml:"duration",ini:"duration"`
    // Caller Encoder, default is short
    Caller        string `json:"caller",yaml:"caller",ini:"caller"`
    // Encoding Format, default is console
    Encoding      string `json:"encoding",yaml:"encoding",ini:"encoding"`
}

// Logger rotate configuration
type RotateCfg struct {
    // Max file size, unit is m, default is 10m
    MaxSize    int  `json:"max_size",yaml:"max_size",ini:"max_size"`
    // Max file backups, default is 5
    MaxBackups int  `json:"max_backups",yaml:"max_backups",ini:"max_backups"`
    // Max store age, unit is day, default is 30 day
    MaxAge     int  `json:"max_age",yaml:"max_age",ini:"max_age"`
    // Is compress or not, defaul is false
    Compress   bool `json:"compress",yaml:"compress",ini:"compress"`
}
```

> English is not my main language. If any typo or wrong translation you found, you can help to translate in [github here](https://github.com/GoAdminGroup/docs). I will very appreciate it.


# Plugins

GoAdmin Documentation

{% content-ref url="/pages/-Lvp55\_moHwdXBr5x\_Uu" %}
[English](/en)
{% endcontent-ref %}

{% content-ref url="/pages/-Lvp55\_pCOjRCHiWJFxn" %}
[简体中文](/zh)
{% endcontent-ref %}


# How To Use Plugins

The framework's plugins include: controllers, routing, and views. The specific plug-in development will be discussed in the project development part, here just show you how to use it.

The example plugin is our demo.

Using plugins are divided into: using the third package source code plugin and use the dynamic link library plugin (.so file, currently only supports linux and mac platforms)

You can skip this part, if you just want to build a crud administrative platform.

## Using the third package source code plugin

For example:

```go
package main

import (
    _ "github.com/GoAdminGroup/go-admin/adapter/gin" // Import the adapter
    _ "github.com/GoAdminGroup/themes/adminlte" // Import the theme
    _ "github.com/GoAdminGroup/go-admin/modules/db/drivers/mysql" // Import the sql driver

    "github.com/gin-gonic/gin"
    "github.com/GoAdminGroup/go-admin/engine"
    "github.com/GoAdminGroup/go-admin/plugins/admin"
    "github.com/GoAdminGroup/go-admin/plugins/example"
    "github.com/GoAdminGroup/go-admin/modules/config"
    "github.com/GoAdminGroup/go-admin/examples/datamodel"
)

func main() {
    r := gin.Default()
    eng := engine.Default()
    cfg := config.Config{}

    adminPlugin := admin.NewAdmin(datamodel.Generators)
    examplePlugin := example.NewExample()

    eng.AddConfig(cfg).
        AddPlugins(adminPlugin, examplePlugin).  // loading
        Use(r)

    r.Run(":9033")
}
```

## Using the binary plugin

Load the `.so`file, and call`plugins.LoadFromPlugin`.

如：

```go
package main

import (    
    _ "github.com/GoAdminGroup/go-admin/adapter/gin" // Import the adapter
    _ "github.com/GoAdminGroup/themes/adminlte" // Import the theme
    _ "github.com/GoAdminGroup/go-admin/modules/db/drivers/mysql" // Import the sql driver

    "github.com/gin-gonic/gin"
    "github.com/GoAdminGroup/go-admin/engine"
    "github.com/GoAdminGroup/go-admin/plugins/admin"
    "github.com/GoAdminGroup/go-admin/plugins"
    "github.com/GoAdminGroup/go-admin/modules/config"
    "github.com/GoAdminGroup/go-admin/examples/datamodel"
)

func main() {
    r := gin.Default()
    eng := engine.Default()
    cfg := config.Config{}

    adminPlugin := admin.NewAdmin(datamodel.Generators)

    // load plugin from .so file.
    examplePlugin := plugins.LoadFromPlugin("../datamodel/example.so")

    eng.AddConfig(cfg).
        AddPlugins(adminPlugin, examplePlugin).
        Use(r)

    r.Run(":9033")
}
```


# How To Use Admin Plugin

The Admin plugin can help you to quickly generate a platform for database data table query, adding, deleting, and editing.

## Quick Start

Following the steps:

* Generate a configuration file corresponding to the data table
* Set access routing
* Initialize and load in the engine
* Set access menu

### Step 1. Generate configuration file

Suppose you have a data table users in your database, such as:

```sql
CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `gender` tinyint(4) DEFAULT NULL,
  `city` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `ip` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `phone` varchar(10) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

Use the command line tools - `adm` to help you quickly generate configuration files:

* install adm

```bash
go install github.com/GoAdminGroup/adm
```

* generate

\
&#x20;Execute the command in your project folder

```bash
adm generate
```

**Notice: use space to choose table, not enter**

Fill in the information according to the prompts. After the run, a file `users.go` will be generated. This is the configuration file corresponding to the data table. How to configure it is described in detail later.

### Step 2. Set access url

After the configuration file is generated, a routing configuration file `tables.go` will also be generated :

```go
package main

import "github.com/GoAdminGroup/go-admin/plugins/admin/models"

// The key of Generators is the prefix of table info url.
// The corresponding value is the Form and Table data.
//
// http://{{config.DOMAIN}}:{{PORT}}/{{config.PREFIX}}/info/{{key}}
//
// example:
//
// "user"   => http://localhost:9033/admin/info/user
//
var Generators = map[string]models.TableGenerator{
    "user":    GetUserTable,
}
```

`"user"` is the corresponding access route prefix, `GetUserTable` is the table data generation method. The corresponding access routing address is: <http://localhost:9033/admin/info/user>

### Step 3. Initialize and load in the engine

To initialize, you need to call the `eng.AddGenerators` method, and then pass the `Generators` above.

```go
package main

import (
    _ "github.com/GoAdminGroup/go-admin/adapter/gin" // Import the adapter, it must be imported. If it is not imported, you need to define it yourself.
    _ "github.com/GoAdminGroup/themes/adminlte" // Import the theme
    _ "github.com/GoAdminGroup/go-admin/modules/db/drivers/mysql" // Import the sql driver

    "github.com/gin-gonic/gin"
    "github.com/GoAdminGroup/go-admin/engine"
    "github.com/GoAdminGroup/go-admin/plugins/admin"
    "github.com/GoAdminGroup/go-admin/modules/config"
    "github.com/GoAdminGroup/go-admin/modules/language"
)

func main() {
    r := gin.Default()
    eng := engine.Default()
    cfg := config.Config{
        Databases: config.DatabaseList{
            "default": {
                Host:       "127.0.0.1",
                Port:       "3306",
                User:       "root",
                Pwd:        "root",
                Name:       "godmin",
                MaxIdleCon: 50,
                MaxOpenCon: 150,
                Driver:     config.DriverMysql,
            },
        },
        UrlPrefix: "admin",
        Store: config.Store{
            Path:   "./uploads",
            Prefix: "uploads",
        },
        Language: language.CN,
    }

    // AddGenerator can also be used to load the Generator, like:
    // eng.AddGenerator("user", GetUserTable)

    eng.AddConfig(cfg).
        AddGenerators(Generators).  // 加载插件
        Use(r)

    r.Run(":9033")
}
```

### Step 4. Set access menu

After running, access the login URL, enter the menu management page, and then set the management menu of the data table to enter in the sidebar.

> In the above example, the login URL is <http://localhost:9033/admin/login>
>
> The menu management page is <http://localhost:9033/admin/menu>

## Introduction of the business data table generation method

```go
package datamodel

import (
    "fmt"
    "github.com/GoAdminGroup/go-admin/modules/db"
    form2 "github.com/GoAdminGroup/go-admin/plugins/admin/modules/form"
    "github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
    "github.com/GoAdminGroup/go-admin/template/types"
    "github.com/GoAdminGroup/go-admin/template/types/form"
)

func GetUserTable(ctx *context.Context) (userTable table.Table) {

    // config the table model.
    userTable = table.NewDefaultTable(table.Config{
        Driver:     db.DriverMysql,
        CanAdd:     true,
        Editable:   true,
        Deletable:  true,
        Exportable: true,
        Connection: table.DefaultConnectionName,
        PrimaryKey: table.PrimaryKey{
            Type: db.Int,
            Name: table.DefaultPrimaryKeyName,
        },
    })

    info := userTable.GetInfo()

    // set id sortable.
    info.AddField("ID", "id", db.Int).FieldSortable(true)
    info.AddField("Name", "name", db.Varchar)

    // use FieldDisplay.
    info.AddField("Gender", "gender", db.Tinyint).FieldDisplay(func(model types.FieldModel) interface{} {
        if model.Value == "0" {
            return "men"
        }
        if model.Value == "1" {
            return "women"
        }
        return "unknown"
    })

    info.AddField("Phone", "phone", db.Varchar)
    info.AddField("City", "city", db.Varchar)
    info.AddField("CreatedAt", "created_at", db.Timestamp)
    info.AddField("UpdatedAt", "updated_at", db.Timestamp)

    // set the title and description of table page.
    info.SetTable("users").SetTitle("Users").SetDescription("Users").
        SetAction(template.HTML(`<a href="http://google.com"><i class="fa fa-google"></i></a>`))  // custom operation button

    formList := userTable.GetForm()

    // set id editable is false.
    formList.AddField("ID", "id", db.Int, form.Default).FieldNotAllowEdit()
    formList.AddField("Ip", "ip", db.Varchar, form.Text)
    formList.AddField("Name", "name", db.Varchar, form.Text)

    // use FieldOptions.
    formList.AddField("Gender", "gender", db.Tinyint, form.Radio).
        FieldOptions(types.FieldOptions{
            {
                Text:    "male",
                Value:    "0",
            }, {
                Text:    "female",
                Value:    "1",
            },
        }).FieldDefault("0")
    formList.AddField("Phone", "phone", db.Varchar, form.Text)
    formList.AddField("City", "city", db.Varchar, form.Text)

    // add a custom field and use FieldPostFilterFn to do more things.
    formList.AddField("Custom Field", "role", db.Varchar, form.Text).
        FieldPostFilterFn(func(value types.PostFieldModel) interface{} {
            fmt.Println("user custom field", value)
            return ""
        })

    formList.AddField("UpdatedAt", "updated_at", db.Timestamp, form.Default).FieldNotAllowAdd(true)
    formList.AddField("CreatedAt", "created_at", db.Timestamp, form.Default).FieldNotAllowAdd(true)

    // use SetTabGroups to group a form into tabs.
    formList.SetTabGroups(types.
        NewTabGroups("id", "ip", "name", "gender", "city").
        AddGroup("phone", "role", "created_at", "updated_at")).
        SetTabHeaders("profile1", "profile2")

    // set the title and description of form page.
    formList.SetTable("users").SetTitle("Users").SetDescription("Users")

    // use SetPostHook to add operation when form posted.
    formList.SetPostHook(func(values form2.Values) {
        fmt.Println("userTable.GetForm().PostHook", values)
    })

    return
}
```

Initialized by calling `models.NewDefaultTable(models.DefaultTableConfig)` method to pass **data table model configuration**. The data table model is configured as:

```go
type Config struct {
    Driver      string // database driver
    Connection  string // database connection name, defined in the global configuration
    CanAdd      bool   // Can I add data
    Editable    bool   // Can I edit
    Deletable   bool   // Can I delete it
    Exportable  bool   // Whether it can be exported
    PrimaryKey  PrimaryKey // primary key of the data table
}

type PrimaryKey struct {
    Type db.DatabaseType  // primary key type
    Name string           // primary key name
}
```

The business data table generation method is a function that returns a type object of `models.Table`. The following is the definition of `models.Table`:

```go
type Table interface {
    GetInfo() *types.InfoPanel
    GetDetail() *types.InfoPanel
    GetDetailFromInfo() *types.InfoPanel
    GetForm() *types.FormPanel

    GetCanAdd() bool
    GetEditable() bool
    GetDeletable() bool
    GetExportable() bool

    GetPrimaryKey() PrimaryKey

    GetData(params parameter.Parameters) (PanelInfo, error)
    GetDataWithIds(params parameter.Parameters) (PanelInfo, error)
    GetDataWithId(params parameter.Parameters) (FormInfo, error)
    UpdateData(dataList form.Values) error
    InsertData(dataList form.Values) error
    DeleteData(pk string) error

    GetNewForm() FormInfo

    Copy() Table
}
```

It mainly includes `GetInfo()` and `GetForm()`. The UI corresponding to the type returned by these two functions is the table for displaying data and the form for editing or creating data. The screenshots are as follows:

* This is the `Info`.

![](http://quizfile.dadadaa.cn/everyday/app/jlds/img/006tNbRwly1fxoy26qnc5j31y60u0q91.jpg)

* This is the `Form`.

![](http://quizfile.dadadaa.cn/everyday/app/jlds/img/006tNbRwly1fxoy2w3cobj318k0ooabv.jpg)

### Info

```go
type InfoPanel struct {
    FieldList   FieldList

    Table       string   
    Title       string   
    Description string   

    TabGroups  TabGroups  
    TabHeaders TabHeaders 

    Sort      Sort     
    SortField string   

    PageSizeList    []int 
    DefaultPageSize int   

    ExportType int

    IsHideNewButton    bool 
    IsHideExportButton bool 
    IsHideEditButton   bool 
    IsHideDeleteButton bool 
    IsHideDetailButton bool 
    IsHideFilterButton bool 
    IsHideRowSelector  bool 
    IsHidePagination   bool 
    IsHideFilterArea   bool 
    FilterFormLayout   form.Layout 

    FilterFormHeadWidth  int
    FilterFormInputWidth int

    Wheres    Wheres    
    WhereRaws WhereRaw  

    TableLayout string 

    DeleteHook  DeleteFn 
    PreDeleteFn DeleteFn 
    DeleteFn    DeleteFn 

    DeleteHookWithRes DeleteFnWithRes 

    GetDataFn GetDataFn

    Action        template.HTML 
    HeaderHtml    template.HTML 
    FooterHtml    template.HTML 
}

type Field struct {
    Head     string                // title    
    Field    string                // field name
    TypeName db.DatabaseType    // database type name

    Join Join // join table setting

    Width      int    // width
    Sortable   bool   // sortable
    Fixed      bool   // fixed
    Filterable bool   // filterable
    Hide       bool   // hide or not

    EditType    table.Type    // edit type
    EditOptions FieldOptions  // edit options

    Display              FieldFilterFn           // display filter callback function
    DisplayProcessChains DisplayProcessFnChains  // display process function chains
}

// join table setting
// example: left join Table on Table.JoinField = Field
type Join struct {
    Table     string
    Field     string
    JoinField string
}
```

### Form

```go
type FormPanel struct {
    FieldList         FormFields  // form field list
    curFieldListIndex int

    // Warn: may be deprecated future.
    TabGroups  TabGroups    // tabs, [example](https://github.com/GoAdminGroup/go-admin/blob/master/examples/datamodel/user.go#L76)
    TabHeaders TabHeaders   // tabs headers, [example](https://github.com/GoAdminGroup/go-admin/blob/master/examples/datamodel/user.go#L78)

    Table       string
    Title       string
    Description string

    Validator FormValidator   // form post validator function
    PostHook  FormPostHookFn  // form post hook function
    PreProcessFn FormPreProcessFn // form post pre process function

    IsHideContinueEditCheckBox bool
    IsHideContinueNewCheckBox  bool
    IsHideResetButton          bool
    IsHideBackButton           bool

    HeaderHtml template.HTML  // header custom html content
    FooterHtml template.HTML  // footer custom html content

    UpdateFn FormPostFn // Form update function, set up this function, it took over the form of updates, PostHook is no longer in effect
    InsertFn FormPostFn // Form inserts function, set up this function, it took over the form of the insert, PostHook effect no longer
}

type FormPostFn func(values form.Values) error

// form hook function type
type PostHookFn func(values form.Values)

type FormField struct {
    Field        string               
    TypeName     string               
    Head         string               
    FormType     form.Type            

    Default                 string               
    Value                  string               
    Options                []map[string]string  
    DefaultOptionDelimiter string                

    Editable     bool 
    NotAllowAdd  bool 
    Must         bool 
    Hide         bool 

    HelpMsg   template.HTML 
    OptionExt template.JS   

    Display              FieldFilterFn          
    DisplayProcessChains DisplayProcessFnChains 
    PostFilterFn PostFieldFilterFn              

    Placeholder string

    CustomContent template.HTML
    CustomJs      template.JS  
    CustomCss     template.CSS 

    Width int

    Divider      bool  
    DividerTitle string

    OptionExt    template.JS 
    OptionInitFn OptionInitFn
    OptionTable  OptionTable 
}
```

The currently supported form types are:

* default
* normal text
* Single selection
* Password
* rich text
* File
* Code
* double selection box
* Multiple choices
* icon drop-down selection box
* time selection box
* radio selection box
* email input box
* url input box
* ip input box
* color selection box
* Currency input box
* Digital input box

\</br>

Can be used like this:

```go
import "github.com/GoAdminGroup/go-admin/template/types/form"

...
FormType: form.File,
...
```

See more in：[admin form components](https://github.com/GoAdminGroup/docs/tree/5591126264305e4996ee8dde31525b4a7f2de437/en/plugins/admin/form/components.md)

Where field is the name of the field and value is the value corresponding to the selection.

### Filter function FilterFn and processing function PostFn description

The data which framework retrieve from database will be displayed in the table or form. If you want to transform them before displaying, for example turn capital or add some html style etc, you can do that using the field filter callback function. Of course, the framework have some built-in data process functions which will be introduced in the chapter of admin table.

```go
// FieldModel contains ID and value of the single query result.
type FieldModel struct {
    ID    string
    Value string
}

// FieldFilterFn determines the value that is retrieved from the database 
// and passes to the format displayed by the front end.
//
// The type currently accepted for return is: template.HTML, string, []string
//
// For tables, you can return the template.HTML type, including html and css 
// styles, so that the fields in the table can be personalized, such as:
// 
// FilterFn: func(model types.FieldModel) interface{} {
//     return template.Get("adminlte").Label().SetContent(template2.HTML(model.Value)).GetContent()
// },
//
// For forms, note that if it is a select box type: Select/SelectSingle/SelectBox, 
// you need to return an array: []string, such as:
//
// FilterFn: func(model types.FieldModel) interface{} {
//     return strings.Split(model.Value, ",")
// },
// 
// For other form types, return the string type
//
type FieldFilterFn func(value FieldModel) interface{}

// PostFieldModel contains ID and value of the single query result.
type PostFieldModel struct {
    ID    string
    Value FieldModelValue
    Row   map[string]interface{}
}

type FieldModelValue []string

func (r FieldModelValue) Value() string {
    return r.First()
}

func (r FieldModelValue) First() string {
    return r[0]
}
```

> English is not my main language. If any typo or wrong translation you found, you can help to translate in [github here](https://github.com/GoAdminGroup/docs). I will very appreciate it.


# Plan

GoAdmin not only aim for a admin panel builder tool. Now the base version of 1.0 has achieved a base framework which can help quickly build a simple crud admin panel with permession manage and other fetures. On this basis, you can also customize the theme and the plugin. The following points after three expounds the project development plan.

## Features

The final purpose of GoAdmin is achieving a no-code or to some extent, no-code operations set. And we will at least build the plugins of two. The one we named admin is help you build a crud admin panel quickly, and the other one is a Grafana like data monitor dashboard builder, which we named monitor.

### version 1.0.0

* Build the basic framework, and at the same time provide a built-in plugin which can satisfy the rapid construction of crud admin panel.
* This basic framework can support theme and plugin customizing.

### version 2.0.0

* On the basis of version 1.0, this version will imporve the admin plugin to provide a ec mall and saas system infrastructure features
* Improve the tool chain of developing themes and plugins, make it easier for developer to get start with developing of themes and plugins.
* Providing more themes and built-in plugins.
* The basic support of monitor system.
* Improve performance of project.

### version 3.0.0

* Support the productive monitor system.
* Achieving a interface which support dragging and dropping in the front-end.

### version 4.0.0

* Support no-code operations.

## Community

GoAdmin project needs more developers to join together.

Now the project is maintained by [@cg33](https://github.com/chenhg5), who is a two years gopher。

Work of the projects:

* [developing](https://github.com/GoAdminGroup/go-admin)
* forum project maintenance(not be a opensource project yet)
* [The maintenance of document improvement and translation](https://github.com/GoAdminGroup/docs)
* Publicity and community culture of the organization of the project

GoAdmin always adheres to an open and open attitude, and welcomes people with lofty and capable ability to join in the development of a conspiracy project and community. The community and the individual complement each other.

If you are optimistic about the development of GoAdmin and are willing to gamble for him, use time for future financial or reputational returns, and you have confidence in your own abilities, then you can try to fully read the GoAdmin code and understand GoAdmin's development plan, make your contribution to this. The pre-code flaws are large and can be modified. If you have the ability to make enough contributions, you will become the project's co-founder **or** core develope&#x72;**. In the later stages, the code is highly sophisticated and there is still room for improvement. You can become a** contributor by submitting a fix\*\*. The team will remain open and accept new members. Every member of the team who works hard will also receive a certain return in the future based on the proportion of the effort to harvest the project.

If you don't have enough time and energy, but have a certain amount of money, and are equally optimistic about GoAdmin development, although GoAdmin has not yet planned a plan for this. But as long as you have enough interest, you can bring your plan to negotiate with us.

## Commercial Plan

GoAdmin will be gradually commercialized, but the core infrastructure features are free and open source. GoAdmin's capital revenue model is mainly:

* Accept donations
* Selling themes
* Selling plugins
* Provide saas customized development
* Commercial version for a fee

Revenue funds are mainly used to maintain the development of the community, and the return on compensation of developers, to promote the project to grow better.


# 简体中文

***

GoAdmin是一个基于 golang 面向生产的数据可视化管理平台搭建框架，可以让你使用简短的代码在极短时间内搭建起一个管理后台。

一般开发一套管理后台需要至少一个后台工程师，一个前端工程师，花费至少一周时间才能搭建完成，搭建完成后我们需要分别去部署前端代码和后端代码。 而利用 GoAdmin，只需要一名golang后端工程师。在先花一点点时间了解掌握GoAdmin后，即可开发好一个面向生产环境的管理后台。而且所有的框架代码（包括前端文件）都将编译成一个二进制文件，直接部署到正式服务器即可运行，测试分发和部署十分便捷。

在功能需求方面，GoAdmin目前内置支持对主流SQL数据库（mysql/postgresql/sqlite/mssql）增删改查的管理插件，更多的[功能插件](https://www.go-admin.cn/plugins)如：服务器文件管理，数据监控系统等等会陆续开发并开放。

对于前端个性化需求，GoAdmin目前官方免费支持Adminlte、Sword两个主题，更多[主题](https://www.go-admin.cn/themes)正在制作中以及对应更多的登录界面组件也在制作中，敬请期待。

## 特性

* 内置完善的rbac权限系统
* 支持多个web框架接入
* 本地化支持
* 整个系统可以编译成一个二进制文件
* 提供多个插件（开发中）
* 多个好看的ui主题（更多主题开发中）

## 在线Demo

[https://demo.go-admin.cn](https://demo.go-admin.cn/admin/login)

## 依赖

* [Datetimepicker](http://eonasdan.github.io/bootstrap-datetimepicker/)
* [font-awesome](http://fontawesome.io/)
* [bootstrap-fileinput](https://github.com/kartik-v/bootstrap-fileinput)
* [jquery-pjax](https://github.com/defunkt/jquery-pjax)
* [Nestable](http://dbushell.github.io/Nestable/)
* [toastr](http://codeseven.github.io/toastr/)
* [bootstrap-number-input](https://github.com/wpic/bootstrap-number-input)
* [fontawesome-iconpicker](https://github.com/itsjavi/fontawesome-iconpicker)

## 社区

⚠️ 为了避免发广告及不看文档用户，请先到Github star此项目，然后附上Github账号(非邮箱)申请入群，没备注不通过。

在社区中如有问题提问，请务必清晰描述，包括但不限于**问题详叙/问题代码/复现方法/已经尝试过的方法**，时间生命可贵，请珍惜自己和别人的时间！

**QQ群**

一群：756664859（已满）

二群：874825430（已满）

三群：641768714（已满）

四群：[694446792](https://qm.qq.com/q/bp3hsYyUzS)

**微信群**

添加以下个人微信，并备注加GoAdmin开发交流群。同时如果有意向加入一起开发框架，成为框架的贡献者，也可以联系我(^^)。

![](http://quick.go-admin.cn/resource/wechat_qrcode_02.jpg)

**论坛**

<https://discuss.go-admin.com/>

## 捐赠

开发软件不易，您的支持会帮助我更好的去完善项目，备注或告知我您的 github/gitee 用户名。 会根据意愿在[网站](http://www.go-admin.cn/donation)中列出捐赠者名单。🙏\
帮忙分享给好友或是在各个在线软件交流平台发布教程也是一种支持！

![](http://quick.go-admin.cn/official/assets/imgs/shoukuan.jpg)

> 目前GoAdmin项目捐赠达666元，联系作者可进vip用户群，vip群中您的问题将得到优先解答，同时也会根据您的需求进行分析和优先安排，vip群也会提供其他关于golang的福利。
>
> 同时您也可以联系我，雇佣我的时间帮助您干活。


# 准备工作

***

本程序是基于`golang`语言编写，推荐使用golang版本高于1.11，golang相关信息具体可以访问其[官网](https://golang.org)查询。

## 准备数据

以下sql文件内容为框架所需数据表，假设你的业务数据库为：`database_a`；那么你可以将以下框架sql文件导入到`database_a`中，也可以另外建一个数据库`database_b`再导入，可以为不同驱动的数据库，比方说你的业务数据库为`mysql`，框架数据库为`sqlite`。框架目前支持多个数据库连接操作。关于如何配置，后面文档会具体介绍。

### 下载

[sqlite](https://gitee.com/go-admin/go-admin/raw/master/data/admin.db) / [mssql](https://gitee.com/go-admin/go-admin/raw/master/data/admin.mssql) / [postgresql](https://gitee.com/go-admin/go-admin/raw/master/data/admin.pgsql) / [mysql](https://gitee.com/go-admin/go-admin/raw/master/data/admin.sql)

### 导入

#### sqlite

直接下载即可。但windows用户需要安装gcc才能使用sqlite golang驱动。

#### mysql

```bash
mysql -h 127.0.0.1 -P 3306 -u root -p root go_admin < ./admin.sql
```

#### mssql

```bash
sqlcmd -S 127.0.0.1 -U SA -P 123456 -d go_admin -i ./admin.sql
```

#### postgresql

```bash
PGPASSWORD=root psql -h 127.0.0.1 -p 5432 -d go_admin -U postgres -f ./admin.sql
```

## 安装命令行工具

下载对应系统的二进制文件到本地，并配置到环境变量中。

| 文件名                                                                                                               | 系统      | 架构     | 大小      |
| ----------------------------------------------------------------------------------------------------------------- | ------- | ------ | ------- |
| [adm\_darwin\_x86\_64\_v1.2.24.zip](http://file.go-admin.cn/go_admin/cli/v1_2_24/adm_darwin_x86_64_v1.2.24.zip)   | macOs   | x86-64 | 4.77 MB |
| [adm\_linux\_x86\_64\_v1.2.24.zip](http://file.go-admin.cn/go_admin/cli/v1_2_24/adm_linux_x86_64_v1.2.24.zip)     | Linux   | x86-64 | 6.52 MB |
| [adm\_linux\_armel\_v1.2.24.zip](http://file.go-admin.cn/go_admin/cli/v1_2_24/adm_linux_armel_v1.2.24.zip)        | Linux   | x86    | 6.06 MB |
| [adm\_windows\_i386\_v1.2.24.zip](http://file.go-admin.cn/go_admin/cli/v1_2_24/adm_windows_i386_v1.2.24.zip)      | Windows | x86    | 6.16 MB |
| [adm\_windows\_x86\_64\_v1.2.24.zip](http://file.go-admin.cn/go_admin/cli/v1_2_24/adm_windows_x86_64_v1.2.24.zip) | Windows | x86-64 | 6.38 MB |

或使用命令安装：

```bash
$ go install github.com/GoAdminGroup/adm
```

🍺🍺 到这里准备工作完毕\~\~


# 快速开始

***

GoAdmin通过各种适配器使得你在各个web框架中使用都十分的方便。目前支持的web框架有：

[gin](http://github.com/gin-gonic/gin) / [beego](https://github.com/astaxie/beego) / [fasthttp](https://github.com/valyala/fasthttp) / [buffalo](https://github.com/gobuffalo/buffalo) / [echo](https://github.com/labstack/echo) / [gorilla/mux](http://github.com/gorilla/mux) / [iris](https://github.com/kataras/iris) / [chi](https://github.com/go-chi/chi) / [gf](https://github.com/gogf/gf)

您可以选择拿手的或者业务项目正在用的框架开始，如果上述没有你喜欢的框架，欢迎给我们提[issue](https://github.com/GoAdminGroup/go-admin/issues/new?assignees=\&labels=\&template=proposal.md\&title=%5BProposal%5D)！

下面演示一下怎么快速搭建和启动项目。

## 初始化

首先新建一个项目文件夹，然后进入文件夹中使用最新版命令行工具 adm 执行：

```bash
$ adm init -l cn
```

或者使用以下命令，可以打开一个web界面安装：

```bash
$ adm init web -l cn
```

初始化完成后，在你的项目文件夹下会生成整个项目的骨架。其中有一个`main.go`文件，内容如下：

```go
package main

import (
	"io/ioutil"
	"log"
	"os"
	"os/signal"

	_ "github.com/GoAdminGroup/go-admin/adapter/gin" // 引入适配器，必须引入，如若不引入，则需要自己定义
	_ "github.com/GoAdminGroup/themes/adminlte" // 引入主题，必须引入，不然报错
	_ "github.com/GoAdminGroup/go-admin/modules/db/drivers/mysql" // 引入对应数据库引擎

	"github.com/GoAdminGroup/go-admin/engine"
	"github.com/GoAdminGroup/go-admin/template"
	"github.com/GoAdminGroup/go-admin/template/chartjs"
	"github.com/gin-gonic/gin"

	"xxx/pages"
	"xxx/tables"
)

func main() {
	startServer()
}

func startServer() {
	gin.SetMode(gin.ReleaseMode)
	gin.DefaultWriter = ioutil.Discard

	r := gin.Default()

	template.AddComp(chartjs.NewChart())

	// 实例化一个GoAdmin引擎对象
	eng := engine.Default()

	// 增加配置与插件，使用Use方法挂载到Web框架中
	if err := eng.AddConfigFromJSON("./config.json").
		// 这里引入你需要管理的业务表配置
		// 后面会介绍如何使用命令行根据你自己的业务表生成Generators
		AddGenerators(tables.Generators).
		Use(r); err != nil {
		panic(err)
	}

	r.Static("/uploads", "./uploads")

	eng.HTML("GET", "/admin", pages.GetDashBoard)
	eng.HTMLFile("GET", "/admin/hello", "./html/hello.tmpl", map[string]interface{}{
		"msg": "Hello world",
	})

	_ = r.Run(":9033")

	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Print("closing database connection")
	eng.MysqlConnection().Close()
}
```

请**留意以上代码与注释**，对应的步骤都加上了注释，十分好理解：

* 匿名引入**适配器**，**主题**与**数据库驱动**（必须）
* 载入设置好的全局配置项：`eng.AddConfig`
* 挂载到Web框架中：`eng.Use`

接着根据提示依次执行： (以下为mac/linux用户执行命令，windows用户需根据提示执行)

```bash
$ make init module=xxx
$ GORPOXY=https://goproxy.io make install
$ make serve
```

运行代码，访问：<http://localhost:9033/admin/login>\
\
默认登录账号：admin\
默认登录密码：admin

注意：golang版本高于1.11强烈建议开启`GO111MODULE=on`，如果运行下载依赖有问题，这里提供了依赖包下载：

* [vendor\_v1.2.24.zip](http://file.go-admin.cn/go_admin/vendor/v1_2_24/vendor.zip)

## 添加业务表管理

详见：

{% content-ref url="<https://github.com/GoAdminGroup/docs/blob/master/zh/plugins/plugins.md>" %}
<https://github.com/GoAdminGroup/docs/blob/master/zh/plugins/plugins.md>
{% endcontent-ref %}

{% content-ref url="<https://github.com/GoAdminGroup/docs/blob/master/zh/plugins/admin.md>" %}
<https://github.com/GoAdminGroup/docs/blob/master/zh/plugins/admin.md>
{% endcontent-ref %}

* [插件介绍](https://github.com/GoAdminGroup/docs/blob/master/zh/plugins/plugins.md)
* [内置admin插件](https://github.com/GoAdminGroup/docs/blob/master/zh/plugins/admin.md)

## 前端模板文件分离

如果对前端功能需要较多自定义，可使用模板文件分离的形式。

假设已经使用`adm init`初始化一个模板后，那么需要进行以下几步更改：

* 修改main.go文件，修改导入主题包为分离主题包
* 下载模板文件夹public到本地
  * [adminlte](https://gitee.com/go-admin/themes/raw/master/adminlte/separation/public.zip)
  * [sword](https://gitee.com/go-admin/themes/raw/master/sword/separation/public.zip)
* 修改config.json文件：
  * 改动主题 theme 配置项：adminlte 改为 adminlte\_sep，sword 改为 sword\_sep
  * 增加 asset\_root\_path 配置项，为模板文件夹(public)的地址，建议用绝对路径，末尾需要带上斜杆
* 重新启动，并在网站右上角进去设置页更改主题

这时修改一下模板文件夹下文件`public/pages/header.tmpl`试试吧！

main.go

```go
package main

import (
	...

	_ "github.com/GoAdminGroup/themes/adminlte/separation" 

	...
)

func main() {
	startServer()
}

func startServer() {
	...
}
```

config.json

```js
{
  ...
  "theme": "sword_sep",
  ...
  "asset_root_path": "./public/"
}
```

## 全局配置项说明

<https://github.com/GoAdminGroup/go-admin/blob/master/modules/config/config.go>

**注意：配置一旦初始化生成后，后续修改请在网站右上角中进入配置中心修改！**\
**注意：配置一旦初始化生成后，后续修改请在网站右上角中进入配置中心修改！**\
**注意：配置一旦初始化生成后，后续修改请在网站右上角中进入配置中心修改！**

```go
package config

import (
	"html/template"
)

type Database struct {
	Host         string  // 地址
	Port         string  // 端口
	User         string  // 用户名
	Pwd          string  // 密码
	Name         string  // 数据库名
	MaxIdleCon   int     // 最大闲置连接数
	MaxOpenCon   int     // 最大打开连接数
	Driver       string  // 驱动名
	File         string  // 文件名
	DSN          string  // DSN语句：如果设置了DSN语句，则优先使用DSN进行连接
	Params       map[string]string  // DSN的额外参数
}

// 数据库配置
// 为一个map，其中key为数据库连接的名字，value为对应的数据配置
// 注意：key为default的数据库是默认数据库，也是框架所用的数据库，而你可以
// 配置多个数据库，提供给你的业务表使用，实现对不同数据库的管理。
type DatabaseList map[string]Database

// 存储目录：存储头像等上传文件
type Store struct {
	Path   string // 存储路径
	Prefix string // url访问前缀
}

type Config struct {
	// 数据库配置
	Databases DatabaseList `json:"database"`

	// 登录域名
	Domain string `json:"domain"`

	// 网站语言
	Language string `json:"language"`

	// 全局的管理前缀
	UrlPrefix string `json:"prefix"`

	// 主题名
	Theme string `json:"theme"`

	// 上传文件存储的位置
	Store Store `json:"store"`

	// 网站的标题
	Title string `json:"title"`

	// 侧边栏上的Logo
	Logo template.HTML `json:"logo"`

	// 侧边栏上的Logo缩小版
	MiniLogo template.HTML `json:"mini_logo"`

	// 登录后跳转的路由
	IndexUrl string `json:"index"`

	// 自定义登录路由地址
	LoginUrl string `json:"login_url",yaml:"login_url",ini:"login_url"`

	// 是否开始debug模式
	Debug bool `json:"debug"`

	// Info日志路径
	InfoLogPath string `json:"info_log"`

	// Error log日志路径
	ErrorLogPath string `json:"error_log"`

	// Access log日志路径
	AccessLogPath string `json:"access_log"`

	// 是否开始数据库Sql操作日志
	SqlLog bool `json:"sql_log"`

	// 是否关闭access日志
	AccessLogOff bool `json:"access_log_off"`
	// 是否关闭info日志
	InfoLogOff   bool `json:"info_log_off"`
	// 是否关闭error日志
	ErrorLogOff  bool `json:"error_log_off"`

	// 日志配置
	Logger Logger `json:"logger",yaml:"logger",ini:"logger"`

	// 网站颜色主题
	ColorScheme string `json:"color_scheme"`

	// Session的有效时间，单位为秒
	SessionLifeTime int `json:"session_life_time"`
	
	// Cdn链接，为全局js/css配置cdn链接
	AssetUrl string `json:"asset_url"`

	// 文件上传引擎
	FileUploadEngine FileUploadEngine `json:"file_upload_engine"`

	// 自定义头部js/css
	CustomHeadHtml template.HTML `json:"custom_head_html"`

	// 自定义尾部js/css
	CustomFootHtml template.HTML `json:"custom_foot_html"`

	// 登录页面标题
	LoginTitle string `json:"login_title"`

	// 登录页面logo
	LoginLogo template.HTML `json:"login_logo"`

	// 自定义认证用户的数据表
	AuthUserTable string `json:"auth_user_table",yaml:"auth_user_table",ini:"auth_user_table"`

	// 额外
	Extra ExtraInfo `json:"extra",yaml:"extra",ini:"extra"`

	// 页面动画
	Animation PageAnimation `json:"animation",yaml:"animation",ini:"animation"`

	// 是否不限制不同IP登录，默认限制
	NoLimitLoginIP bool `json:"no_limit_login_ip",yaml:"no_limit_login_ip",ini:"no_limit_login_ip"`

	// 网站开关
	SiteOff bool `json:"site_off",yaml:"site_off",ini:"site_off"`

	// 是否隐藏配置中心入口，默认显示
	HideConfigCenterEntrance bool `json:"hide_config_center_entrance",yaml:"hide_config_center_entrance",ini:"hide_config_center_entrance"`

	// 是否隐藏应用信息入口，默认显示
	HideAppInfoEntrance bool `json:"hide_app_info_entrance",yaml:"hide_app_info_entrance",ini:"hide_app_info_entrance"`

	// 隐藏模块列表入口，默认显示
	HidePluginEntrance bool `json:"hide_plugin_entrance,omitempty" yaml:"hide_plugin_entrance,omitempty" ini:"hide_plugin_entrance,omitempty"`

	// 自定义404页面
	Custom404HTML template.HTML `json:"custom_404_html,omitempty",yaml:"custom_404_html",ini:"custom_404_html"`

	// 自定义403页面
	Custom403HTML template.HTML `json:"custom_403_html,omitempty",yaml:"custom_403_html",ini:"custom_403_html"`

	// 自定义500页面
	Custom500HTML template.HTML `json:"custom_500_html,omitempty",yaml:"custom_500_html",ini:"custom_500_html"`

	// 配置更新处理函数
	UpdateProcessFn UpdateConfigProcessFn `json:"-",yaml:"-",ini:"-"`

	// 是否开放admin的json apis，默认关闭
	OpenAdminApi bool `json:"open_admin_api",yaml:"open_admin_api",ini:"open_admin_api"`

	// 隐藏访客用户设置菜单
	HideVisitorUserCenterEntrance bool `json:"hide_visitor_user_center_entrance",yaml:"hide_visitor_user_center_entrance",ini:"hide_visitor_user_center_entrance"`

	// 需要排除的主题模块
	ExcludeThemeComponents []string `json:"exclude_theme_components,omitempty" yaml:"exclude_theme_components,omitempty" ini:"exclude_theme_components,omitempty"`

	// 引导文件路径
	BootstrapFilePath string `json:"bootstrap_file_path,omitempty" yaml:"bootstrap_file_path,omitempty" ini:"bootstrap_file_path,omitempty"`

	// go mod文件路径
	GoModFilePath string `json:"go_mod_file_path,omitempty" yaml:"go_mod_file_path,omitempty" ini:"go_mod_file_path,omitempty"`
}
```

日志设置：

```go
type Logger struct {
	// 编码设置
	Encoder EncoderCfg `json:"encoder",yaml:"encoder",ini:"encoder"`
	// 分割设置
	Rotate  RotateCfg  `json:"rotate",yaml:"rotate",ini:"rotate"`
	// 日志级别
	Level   int8       `json:"level",yaml:"level",ini:"level"`
}

// 日志输出内容编码设置
type EncoderCfg struct {
	// 时间键内容，默认为 ts
	TimeKey       string `json:"time_key",yaml:"time_key",ini:"time_key"`
	// 级别键内容，默认为 level
	LevelKey      string `json:"level_key",yaml:"level_key",ini:"level_key"`
	// 名字键内容，默认为 logger
	NameKey       string `json:"name_key",yaml:"name_key",ini:"name_key"`
	// 调用者键内容，默认为 caller
	CallerKey     string `json:"caller_key",yaml:"caller_key",ini:"caller_key"`
	// 消息键内容，默认为 msg
	MessageKey    string `json:"message_key",yaml:"message_key",ini:"message_key"`
	// 栈键内容，默认为 stacktrace
	StacktraceKey string `json:"stacktrace_key",yaml:"stacktrace_key",ini:"stacktrace_key"`
	// 级别编码器，默认为 大写带颜色
	Level         string `json:"level",yaml:"level",ini:"level"`
	// 时间编码器，默认为 ISO8601
	Time          string `json:"time",yaml:"time",ini:"time"`
	// 间隔时间编码器，默认为 秒
	Duration      string `json:"duration",yaml:"duration",ini:"duration"`
	// 调用者编码器，默认为 简短路径
	Caller        string `json:"caller",yaml:"caller",ini:"caller"`
	// 输出格式，默认console
	Encoding      string `json:"encoding",yaml:"encoding",ini:"encoding"`
}

// 日志分割设置
type RotateCfg struct {
	// 文件最大大小，单位为m，默认为 10m
	MaxSize    int  `json:"max_size",yaml:"max_size",ini:"max_size"`
	// 最多文件数，默认为 5个
	MaxBackups int  `json:"max_backups",yaml:"max_backups",ini:"max_backups"`
	// 存储最长时间，单位为天，默认为 30天
	MaxAge     int  `json:"max_age",yaml:"max_age",ini:"max_age"`
	// 是否压缩，默认为 不开启
	Compress   bool `json:"compress",yaml:"compress",ini:"compress"`
}
```


# Monitor插件

一个兼容`grafana`的插件。 只需要配置`dashboard`和数据源即可拥有一个实时监控面板。

未来两到三周，即将面世，敬请期待。


# 发展规划

GoAdmin的定位不只是一个管理后台中心构建框架，目前在1.0基础版本已经实现了一个能快速构建简单的crud以及有权限管理功能的管理后台的基础构建框架。在此基础上，可以对主题以及插件等进行一定程度的定制。以下分三点阐述这个项目以后的发展计划：

## 项目功能规划

GoAdmin的目标是实现无代码化或某种程度的无代码化可视化操作，内置插件会至少包括：简单与复杂商业化crud管理中心极速构建，支持多数据源的监控体系的搭建等等。以下是对版本的初步规划：

### 1.0.0 版本

* 实现基础的框架，同时提供一个内置插件能够满足快速构建crud管理后台。
* 这个基础框架可以实现前端主题的自由定制，以及对插件的加载。

### 2.0.0 版本

* 在 1.0 版本的基础上，此版本将完善内置插件的功能，基本达到商业化水平（能够提供一个ec商城后台/saas系统的所有功能）
* 完善主题和插件的开发工具链，使得非项目开发人员都能够轻松的上手主题与插件的开发
* 提供更多样化的内置主题与内置插件
* 监控体系的初步支持（实时监控系统，数据前端展示，定制数据源）
* 项目性能的评估与优化

### 3.0.0 版本

* 可生产环境商业化的监控体系支持
* 初步实现界面数据化以及实现一个界面拖拽定制框架

### 4.0.0 版本

* 实现无代码化的界面拖拽框架

## 人才社区构建

GoAdmin项目需要更多的人才一同加入。

目前由我 [@cg33](https://github.com/chenhg5) 一人维护此项目，我是中山大学大学软件系本科毕业，三年的gopher。

目前项目需要的工作有：

* [项目开发](https://github.com/GoAdminGroup/go-admin)，需掌握一定的`golang`开发能力
* 社区项目开发（暂未开源，暂不对外开放）
* [文档的维护改进与翻译](https://github.com/GoAdminGroup/docs)
* 项目的宣传与社区文化的组织

GoAdmin始终秉持开放开源的态度，欢迎有志有能力之士加入一块共谋项目和社区的发展，社区与个人相辅相成。

如果你看好并喜欢GoAdmin的发展，那么你可以尝试充分阅读GoAdmin的代码，并理解GoAdmin的发展规划，为此做出你的贡献。前期代码缺陷漏洞大，可修改空间多，如果你有能力做出足够的贡献，将成为项目的**联合创始人**或**核心开发者**。到后期，代码完善度高，也仍然有改进空间，你可以通过提交修复成为**贡献者**。团队将会一直保持开放态度，接纳新成员。团队每一个付出努力的成员也会在将来根据付出比例公平地去收获项目给大家带来的一定的回报。

如果你没有足够的时间和精力，但有一定的资金，且同样看好GoAdmin发展，虽然GoAdmin尚未就此加入的方案拟定计划。但只要你有足够大的兴趣，也可以带上你的计划与我们进行洽谈。

## 商业项目计划

GoAdmin会逐步实现商业化，但核心基础功能是免费开源的。 GoAdmin的资金收入模式主要是：

* 接受捐助
* 售卖主题
* 售卖插件
* 提供saas定制化开发
* 提供收费的商业化版本

收入资金主要用于维护社区的发展，与开发人员的薪酬回报，促使项目更好的成长。


