admin

package
v0.0.0-...-e194c0f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 24, 2016 License: MIT Imports: 28 Imported by: 0

README

Introduction

Qor admin provide easy-to-use interface for data management.

Features

  • CRUD of any resource
  • JSON API supported
  • Authentication
  • Search and filtering
  • Custom actions
  • Customizable view
  • Extendable

Quick Example

package main

import (
    "net/http"

    "github.com/jinzhu/gorm"
    _ "github.com/mattn/go-sqlite3"
    "github.com/qor/qor"
    "github.com/qor/qor/admin"
)

type User struct {
  gorm.Model
    Name string
}

type Product struct {
  gorm.Model
    Name        string
    Description string
}

func main() {
  DB, _ := gorm.Open("sqlite3", "demo.db")
  DB.AutoMigrate(&User{}, &Product{})

  Admin := admin.New(&qor.Config{DB: &DB})
  Admin.AddResource(&User{}, &admin.Config{Menu: []string{"User Management"}})
  Admin.AddResource(&Product{}, &admin.Config{Menu: []string{"Product Management"}})

  mux := http.NewServeMux()
  Admin.MountTo("/admin", mux)
  http.ListenAndServe(":9000", mux)
}

// TODO: add screenshot after QOR admin UI finished
`go run main.go` and visit `localhost:9000/admin` to see the result !

Usage

Register route

router := Admin.GetRouter()

router.Get("/path", func(context *admin.Context) {
    // do something here
})

router.Post("/path", func(context *admin.Context) {
    // do something here
})

router.Put("/path", func(context *admin.Context) {
    // do something here
})

router.Delete("/path", func(context *admin.Context) {
    // do something here
})

// naming route
router.Get("/path/:name", func(context *admin.Context) {
    context.Request.URL.Query().Get(":name")
})

// regexp support
router.Get("/path/:name[world]", func(context *admin.Context) { // "/hello/world"
    context.Request.URL.Query().Get(":name")
})

router.Get("/path/:name[\\d+]", func(context *admin.Context) { // "/hello/123"
    context.Request.URL.Query().Get(":name")
})

You can view qor example for a more detailed configuration example.

Documentation

Index

Constants

View Source
const (
	DEFAULT_PAGE_COUNT = 20
)
View Source
const HTTPUnprocessableEntity = 422
View Source
const (
	VISIBLE_PAGE_COUNT = 8
)

Variables

View Source
var DefaultHandler = func(name string, value string, scope *gorm.DB, context *qor.Context) *gorm.DB {
	lastIndex := strings.LastIndex(name, "_")
	operation := name[lastIndex+1 : len(name)]
	column := name[0:lastIndex]

	switch operation {
	case "cont":
		return scope.Where(fmt.Sprintf("%v ILIKE ?", scope.NewScope(nil).Quote(column)), "%"+value+"%")
	case "eq":
		return scope.Where(fmt.Sprintf("%v = ?", scope.NewScope(nil).Quote(column)), value)
	case "gt":
		return scope.Where(fmt.Sprintf("%v > ?", scope.NewScope(nil).Quote(column)), value)
	case "gteq":
		return scope.Where(fmt.Sprintf("%v >= ?", scope.NewScope(nil).Quote(column)), value)
	case "lt":
		return scope.Where(fmt.Sprintf("%v < ?", scope.NewScope(nil).Quote(column)), value)
	case "lteq":
		return scope.Where(fmt.Sprintf("%v <= ?", scope.NewScope(nil).Quote(column)), value)
	}
	return scope
}
View Source
var Root, _ = os.Getwd()

Functions

func RegisterViewPath

func RegisterViewPath(p string)

RegisterViewPath register views directory

Types

type Action

type Action struct {
	Name       string
	Label      string
	Handle     func(arg *ActionArgument) error
	Resource   *Resource
	Permission *roles.Permission
	Visibles   []string
}

func (Action) HasPermission

func (action Action) HasPermission(mode roles.PermissionMode, context *qor.Context) bool

func (Action) ToParam

func (action Action) ToParam() string

type ActionArgument

type ActionArgument struct {
	PrimaryValues []string
	Context       *Context
	Argument      interface{}
}

func (*ActionArgument) FindSelectedRecords

func (actionArgument *ActionArgument) FindSelectedRecords() []interface{}

type Admin

type Admin struct {
	Config   *qor.Config
	SiteName string
	I18n     I18n
	// contains filtered or unexported fields
}

func New

func New(config *qor.Config) *Admin

func (*Admin) AddMenu

func (admin *Admin) AddMenu(menu *Menu)

func (*Admin) AddResource

func (admin *Admin) AddResource(value interface{}, config ...*Config) *Resource

func (*Admin) AddSearchResource

func (admin *Admin) AddSearchResource(resources ...*Resource)

func (*Admin) EnabledSearchCenter

func (admin *Admin) EnabledSearchCenter() bool

func (Admin) GetMenu

func (admin Admin) GetMenu(name string) *Menu

func (Admin) GetMenus

func (admin Admin) GetMenus() []*Menu

func (*Admin) GetResource

func (admin *Admin) GetResource(name string) *Resource

func (*Admin) GetResources

func (admin *Admin) GetResources() []*Resource

func (*Admin) GetRouter

func (admin *Admin) GetRouter() *Router

func (*Admin) MountTo

func (admin *Admin) MountTo(mountTo string, mux *http.ServeMux)

MountTo mount the service into mux (HTTP request multiplexer) with given path

func (*Admin) NewContext

func (admin *Admin) NewContext(w http.ResponseWriter, r *http.Request) *Context

func (*Admin) NewResource

func (admin *Admin) NewResource(value interface{}, config ...*Config) *Resource

func (*Admin) RegisterFuncMap

func (admin *Admin) RegisterFuncMap(name string, fc interface{})

RegisterFuncMap register view funcs, it could be used in view templates

func (*Admin) RegisterMetaConfigor

func (admin *Admin) RegisterMetaConfigor(kind string, fc func(*Meta))

RegisterMetaConfigor register configor for a kind, it will be called when register those kind of metas

func (*Admin) ServeHTTP

func (admin *Admin) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP dispatches the handler registered in the matched route

func (*Admin) SetAuth

func (admin *Admin) SetAuth(auth Auth)

func (*Admin) SetSiteName

func (admin *Admin) SetSiteName(siteName string)

func (*Admin) T

func (admin *Admin) T(context *qor.Context, key string, value string, values ...interface{}) template.HTML

type Auth

type Auth interface {
	GetCurrentUser(*Context) qor.CurrentUser
	LoginURL(*Context) string
	LogoutURL(*Context) string
}

type Config

type Config struct {
	Name       string
	Menu       []string
	Invisible  bool
	Permission *roles.Permission
	Themes     []string
	PageCount  int
	Singleton  bool
}

type Context

type Context struct {
	*qor.Context
	*Searcher
	Flashes  []Flash
	Resource *Resource
	Admin    *Admin
	Content  template.HTML
	Action   string
	Result   interface{}
}

func (*Context) AllowedActions

func (context *Context) AllowedActions(actions []*Action, mode string) []*Action

func (*Context) Execute

func (context *Context) Execute(name string, result interface{})

func (*Context) FindTemplate

func (context *Context) FindTemplate(layouts ...string) (string, error)

func (*Context) Flash

func (context *Context) Flash(message, typ string)

func (*Context) FlashNow

func (context *Context) FlashNow(message, typ string)

func (*Context) FormattedValueOf

func (context *Context) FormattedValueOf(value interface{}, meta *Meta) interface{}

func (*Context) FuncMap

func (context *Context) FuncMap() template.FuncMap

func (*Context) GetFlashes

func (context *Context) GetFlashes() []Flash

func (*Context) GetResource

func (context *Context) GetResource(name string) *Resource

func (*Context) GetScopes

func (context *Context) GetScopes() (menus []*scopeMenu)

func (*Context) JSON

func (context *Context) JSON(name string, result interface{})

func (*Context) LinkTo

func (context *Context) LinkTo(text interface{}, link interface{}) template.HTML

func (*Context) NewResourceContext

func (context *Context) NewResourceContext(name ...interface{}) *Context

func (*Context) Pagination

func (context *Context) Pagination() *[]Page

Keep VISIBLE_PAGE_COUNT's pages visible, exclude prev and next link Assume there are 12 pages in total. When current page is 1 [current, 2, 3, 4, 5, 6, 7, 8, next] When current page is 6 [prev, 2, 3, 4, 5, current, 7, 8, 9, 10, next] When current page is 10 [prev, 5, 6, 7, 8, 9, current, 11, 12] If total page count less than VISIBLE_PAGE_COUNT, always show all pages

func (*Context) RawValueOf

func (context *Context) RawValueOf(value interface{}, meta *Meta) interface{}

func (*Context) Render

func (context *Context) Render(name string, results ...interface{}) template.HTML

func (*Context) RenderMeta

func (context *Context) RenderMeta(meta *Meta, value interface{}, prefix []string, metaType string, writer *bytes.Buffer)

func (*Context) UrlFor

func (context *Context) UrlFor(value interface{}, resources ...*Resource) string

type Filter

type Filter struct {
	Name       string
	Operations []string
	Handler    func(name string, value string, scope *gorm.DB, context *qor.Context) *gorm.DB
}

type Flash

type Flash struct {
	Type    string
	Message string
	Keep    bool
}

type HasPermissioner

type HasPermissioner interface {
	HasPermission(roles.PermissionMode, *qor.Context) bool
}

type I18n

type I18n interface {
	Scope(scope string) I18n
	Default(value string) I18n
	T(locale string, key string, args ...interface{}) template.HTML
}

I18n define admin's i18n interface

type Menu struct {
	Name      string
	Link      string
	Ancestors []string
	// contains filtered or unexported fields
}
func (menu *Menu) GetSubMenus() []*Menu

type Meta

type Meta struct {
	Name            string
	FieldName       string
	Label           string
	Type            string
	FormattedValuer func(interface{}, *qor.Context) interface{}
	Valuer          func(interface{}, *qor.Context) interface{}
	Setter          func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context)
	Metas           []resource.Metaor
	Resource        *Resource
	Collection      interface{}
	GetCollection   func(interface{}, *qor.Context) [][]string
	Permission      *roles.Permission
	resource.Meta
	// contains filtered or unexported fields
}

func (*Meta) DBName

func (meta *Meta) DBName() string

func (*Meta) GetMetas

func (meta *Meta) GetMetas() []resource.Metaor

func (*Meta) GetResource

func (meta *Meta) GetResource() resource.Resourcer

func (*Meta) SetPermission

func (meta *Meta) SetPermission(permission *roles.Permission)

type Middleware

type Middleware struct {
	Name    string
	Handler func(*Context, *Middleware)
	// contains filtered or unexported fields
}

Middleware is a way to filter a request and response coming into your application

Register new middleware with `admin.GetRouter().Use(Middleware{
  Name: "middleware name", // use middleware with same name will overwrite old one
  Handler: func(*Context, *Middleware) {
    // do something
    // run next middleware
    middleware.Next(context)
  },
})`

It will be called in order, it need to be registered before `admin.MountTo`

func (Middleware) Next

func (middleware Middleware) Next(context *Context)

Next will call the next middleware

type Page

type Page struct {
	Page       int
	Current    bool
	IsPrevious bool
	IsNext     bool
}

type Pagination

type Pagination struct {
	Total       int
	Pages       int
	CurrentPage int
	PrePage     int
}

type Resource

type Resource struct {
	resource.Resource
	Config        *Config
	Metas         []*Meta
	Actions       []*Action
	SearchHandler func(keyword string, context *qor.Context) *gorm.DB
	// contains filtered or unexported fields
}

func (*Resource) Action

func (res *Resource) Action(action *Action)

func (*Resource) ConvertSectionToMetas

func (res *Resource) ConvertSectionToMetas(sections []*Section) []*Meta

func (*Resource) ConvertSectionToStrings

func (res *Resource) ConvertSectionToStrings(sections []*Section) []string

func (*Resource) Decode

func (res *Resource) Decode(context *qor.Context, value interface{}) error

func (*Resource) EditAttrs

func (res *Resource) EditAttrs(values ...interface{}) []*Section

func (*Resource) Filter

func (res *Resource) Filter(filter *Filter)

func (Resource) GetAdmin

func (res Resource) GetAdmin() *Admin

func (*Resource) GetMeta

func (res *Resource) GetMeta(name string) *Meta

func (*Resource) GetMetaOrNew

func (res *Resource) GetMetaOrNew(name string) *Meta

func (*Resource) GetMetas

func (res *Resource) GetMetas(attrs []string) []resource.Metaor

func (Resource) GetPrimaryValue

func (res Resource) GetPrimaryValue(request *http.Request) string

GetPrimaryValue get priamry value from request

func (*Resource) IndexAttrs

func (res *Resource) IndexAttrs(values ...interface{}) []*Section

func (*Resource) Meta

func (res *Resource) Meta(meta *Meta) *Meta

func (*Resource) NewAttrs

func (res *Resource) NewAttrs(values ...interface{}) []*Section

func (Resource) ParamIDName

func (res Resource) ParamIDName() string

ParamIDName return param name for primary key like :product_id

func (*Resource) Scope

func (res *Resource) Scope(scope *Scope)

func (*Resource) SearchAttrs

func (res *Resource) SearchAttrs(columns ...string) []string

func (*Resource) ShowAttrs

func (res *Resource) ShowAttrs(values ...interface{}) []*Section

func (*Resource) SortableAttrs

func (res *Resource) SortableAttrs(columns ...string) []string

func (Resource) ToParam

func (res Resource) ToParam() string

func (Resource) UseTheme

func (res Resource) UseTheme(theme string) []string

type ResourceNamer

type ResourceNamer interface {
	ResourceName() string
}

type RouteConfig

type RouteConfig struct {
	Resource       *Resource
	Permission     *roles.Permission
	PermissionMode roles.PermissionMode
	Values         map[interface{}]interface{}
}

type Router

type Router struct {
	Prefix string
	// contains filtered or unexported fields
}

Router contains registered routers

func (*Router) Delete

func (r *Router) Delete(path string, handle requestHandler, config ...RouteConfig)

Delete register a DELETE request handle with the given path

func (*Router) Get

func (r *Router) Get(path string, handle requestHandler, config ...RouteConfig)

Get register a GET request handle with the given path

func (*Router) Post

func (r *Router) Post(path string, handle requestHandler, config ...RouteConfig)

Post register a POST request handle with the given path

func (*Router) Put

func (r *Router) Put(path string, handle requestHandler, config ...RouteConfig)

Put register a PUT request handle with the given path

func (*Router) Use

func (r *Router) Use(middleware *Middleware)

Use reigster a middleware to the router

type Scope

type Scope struct {
	Name    string
	Label   string
	Group   string
	Handle  func(*gorm.DB, *qor.Context) *gorm.DB
	Default bool
}

type Searcher

type Searcher struct {
	*Context

	Pagination Pagination
	// contains filtered or unexported fields
}

func (*Searcher) Filter

func (s *Searcher) Filter(name, query string) *Searcher

func (*Searcher) FindMany

func (s *Searcher) FindMany() (interface{}, error)

func (*Searcher) FindOne

func (s *Searcher) FindOne() (interface{}, error)

func (*Searcher) Page

func (s *Searcher) Page(num int) *Searcher

func (*Searcher) PrePage

func (s *Searcher) PrePage(num int) *Searcher

func (*Searcher) Scope

func (s *Searcher) Scope(names ...string) *Searcher

func (*Searcher) WithPagination

func (s *Searcher) WithPagination() *Searcher

type Section

type Section struct {
	Resource Resource
	Title    string
	Rows     [][]string
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL