crud

package module
v0.0.0-...-4bc60db Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2023 License: MIT Imports: 14 Imported by: 0

README

Crud - A lightweight and user-friendly web-based admin panel for Golang applications.

Crud is a lightweight and user-friendly web-based admin panel for Golang applications. It simplifies the process of managing database tables by offering a straightforward CRUD (Create, Read, Update, Delete) user interface. With minimal configuration, you can quickly set up and customize an admin dashboard for your application, saving you time and effort.

Installation

To install Crud, run the following command:

go get github.com/mirzakhany/crud

Features

  • User-friendly interface - Crud provides a simple and intuitive user interface for managing database tables. It is designed to be easy to use, even for non-technical users.

  • Minimal configuration - Crud is designed to be easy to set up and use. It requires minimal configuration and can be integrated into your application in minutes.

  • Customizable - Crud is highly customizable. You can easily change the look and feel of the admin panel by modifying the HTML templates and CSS stylesheets.

How to use

To use Crud, you need to create a new instance of the Crud struct and pass chi router to it. The following example shows how to create a new instance of the Crud struct:

package main

import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/mirzakhany/crud"
)

func main() {
   
    // Define your entities.
	entities := []crud.Entity{
		{
			TableName:     "tasks",
			PrimaryKey:    "id",
			TitlePlural:   "Tasks",
			TitleSingular: "task",
			Description:   "User tasks",
			SelectColumns: []string{"id", "name", "description", "status"},
			EditColumns:   []string{"name", "description", "status"},
			FavIcon:       "fa-tasks",
			Order:         1,
		},
	}

    // Create a new instance of the Crud struct.
   	a, err := crud.New(
		crud.WithDatabaseURI("postgres://postgres:postgres@localhost:15432/postgres?sslmode=disable"),
		crud.WithBaseURL("/admin"),
		crud.WithEntities(entities))

	if err != nil {
		panic(err)
	}

    // Create a new HTTP router.
    httpRouter := chi.NewRouter()
    // Register the Crud handlers.
	a.PrepareHandlers(httpRouter)

	server := http.Server{
		Addr:    ":8080",
		Handler: httpRouter,
	}

    // Start the HTTP server. and open http://localhost:8080/admin in your browser.
	server.ListenAndServe()
}

Screenshots

Dashboard Create Retrive Update Delete

License

This project is licensed under the terms of the MIT license.

Contributing

Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Admin

type Admin struct {
	// DatabaseURI represents the database uri. default is "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable".
	DatabaseURI string

	// Entities represents the entities of the admin module.
	Entities map[string]Entity
	// BaseURL represents the base url for the admin module. default is "/admin".
	BaseURL string
	// DefaultFormatters represents the default formatters for each column. if provided, the formatter will be used to format the column value.
	// if a column has a formatter, the formatter will be used instead of the default formatter.
	DefaultFormatters map[string]Formatter
	// TemplateFuncs represents the template funcs for the admin module.
	TemplateFuncs template.FuncMap
	// Templates represents the templates for the admin module. will override the default templates.
	Templates map[string]*template.Template
	// PermissionChecker represents the permission checker for the admin module.
	PermissionChecker func(r *http.Request, userID, entityName, action string) bool
	// UserIdentifier represents the function that returns the user identifier from the request.
	UserIdentifier func(r *http.Request) string
	// SearchHandler represents the search handler for the admin module.
	SearchHandler func(r *http.Request, query string) ([]SearchResult, error)
	// contains filtered or unexported fields
}

Admin represents the admin module.

func New

func New(opts ...Option) (*Admin, error)

New returns a new admin module.

func (*Admin) GetMux

func (a *Admin) GetMux() http.Handler

GetMux prepares the admin module handlers.

type BaseContextData

type BaseContextData struct {
	ShowSearchBar bool
	BaseURL       string
	Menus         []Menu
}

BaseContextData represents the data needed to render the base template.

type Column

type Column struct {
	Name      string
	Type      string
	Value     any
	IsPrimary bool
}

Column represents a column of a table.

type DB

type DB struct {
	URI    string
	Engine string
}

DB represents a database.

func (*DB) CreateEntity

func (d *DB) CreateEntity(ctx context.Context, tableName, primaryKey string, columns []Column) error

CreateEntity creates a row of a table.

func (*DB) DeleteEntityByID

func (d *DB) DeleteEntityByID(ctx context.Context, tableName, primaryKey string, id any) error

DeleteEntityByID deletes a row of a table by its primary key.

func (*DB) GetEntityByID

func (d *DB) GetEntityByID(ctx context.Context, tableName, primaryKey string, editColumns []string, id any) (*Row, error)

GetEntityByID returns a row of a table by its primary key.

func (*DB) GetTableColumenRows

func (d *DB) GetTableColumenRows(ctx context.Context, tableName, primaryKey string, selectColumns []string) ([]Row, []string, error)

GetTableColumenRows returns the rows of a table.

func (*DB) GetTableFieldTypes

func (d *DB) GetTableFieldTypes(ctx context.Context, tableName string) (map[string]string, error)

GetTableFieldTypes returns the field types of a table.

func (*DB) GetTableRow

func (d *DB) GetTableRow(ctx context.Context, tableName, primaryKey string, editColumns []string) (*Row, error)

GetTableRow returns the columns of a table.

func (*DB) Open

func (d *DB) Open(ctx context.Context) (*sql.Conn, error)

Open opens a database connection.

func (*DB) UpdateEntity

func (d *DB) UpdateEntity(ctx context.Context, tableName, primaryKey string, primaryKeyValue string, columns []Column) error

UpdateEntity updates a row of a table.

type EditData

type EditData struct {
	Title       string
	Description string
	Row         Row
	EntityName  string
	EntityID    string

	IsEdit bool

	BaseContextData
}

EditData represents the data needed to render the edit template.

type Entity

type Entity struct {
	// Entity table name.
	TableName string
	// Primary key column name. default is "id".
	PrimaryKey string
	// Entity title plural. default is the entity table name.
	TitlePlural string
	// Entity title singular. default is the entity table name.
	TitleSingular string
	// FavIcon represents the entity fav icon. default is empty.
	FavIcon string
	// Menu order. default is 0.
	Order int
	// Entity description. default is empty.
	Description string
	// SelectColumns columns. if nil, all columns will be selected.
	SelectColumns []string
	// EditColumns columns. if nil, all columns will be selected.
	EditColumns []string
	// NewColumns columns. if nil, edit columns or all columns will be selected.
	NewColumns []string
	// ColumnNameFormatter represents the column name formatter. if provided, the formatter will be used to format the column name.
	ColumnNameFormatter map[string]Formatter
	// ValueFormatters for each column. if provided, the formatter will be used to format the column value.
	ValueFormatters map[string]Formatter
}

Entity represents a database entity.

type Formatter

type Formatter func(in any) string

Formatter represents a column formatter.

type ListData

type ListData struct {
	Title       string
	Description string
	EntityName  string

	Columns []string
	Rows    []Row

	BaseContextData
}

ListData represents the data needed to render the list template.

type Menu struct {
	Order     int
	Idenifier string
	Title     string
	URL       string
	FavIcon   string
}

Menu represents a menu item.

type Option

type Option func(*Admin) error

Option represents an admin option.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL returns an admin option that sets the admin base url.

func WithDatabaseURI

func WithDatabaseURI(uri string) Option

WithDatabaseURI returns an admin option that sets the database uri.

func WithDefaultFormatter

func WithDefaultFormatter(column string, formatter Formatter) Option

WithDefaultFormatter returns an admin option that sets a default formatter.

func WithDefaultFormatters

func WithDefaultFormatters(formatters map[string]Formatter) Option

WithDefaultFormatters returns an admin option that sets the default formatters.

func WithEntities

func WithEntities(entities []Entity) Option

WithEntities returns an admin option that adds entities.

func WithEntity

func WithEntity(entity Entity) Option

WithEntity returns an admin option that adds an entity.

func WithPermissionChecker

func WithPermissionChecker(fn func(r *http.Request, userID, entityName, action string) bool) Option

WithPermissionChecker returns an admin option that sets the permission checker.

func WithSearchHandler

func WithSearchHandler(fn func(r *http.Request, q string) ([]SearchResult, error)) Option

WithSearchHandler returns an admin option that sets the search handler.

func WithTemplate

func WithTemplate(name, text string) Option

WithTemplate returns an admin option that adds a template.

func WithTemplateFunc

func WithTemplateFunc(name string, fn interface{}) Option

WithTemplateFunc returns an admin option that adds a template func.

func WithTemplateFuncs

func WithTemplateFuncs(funcs template.FuncMap) Option

WithTemplateFuncs returns an admin option that adds template funcs.

func WithUserIdentifier

func WithUserIdentifier(fn func(r *http.Request) string) Option

WithUserIdentifier returns an admin option that sets the user identifier.

type Row

type Row struct {
	Columns         []Column
	PrimaryKey      string
	PrimaryKeyValue any
}

Row represents a row of a table.

type SearchData

type SearchData struct {
	Query       string
	ResultCount int

	BaseContextData

	Results []SearchResult
}

SearchData represents the data needed to render the search template.

type SearchResult

type SearchResult struct {
	Title       string
	Description string
	Link        string
}

SearchResult represents the search results.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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