goravel

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2024 License: MIT Imports: 42 Imported by: 4

README

Goravel

Goravel

Release

PHP's Laravel like web framework supercharged with Go.

Features overview

  • Routing
  • Handlers (For Laravel's Controllers)
  • Build robust and scalable RESTful APIs
  • Middlewares
  • Data binding for JSON, XML and form payloads
  • Handy functions to send variety of HTTP responses
  • Template rendering with Go's html/template package or Jet template engine
  • Multiple database support (PostgreSQL, MySQL, Mariadb), just provide the driver and connection string, Goravel will handle the rest
  • Migrations handled out of the box for the user
  • Caching support (Redis and BadgerDB)
  • Session management built-in
  • In-built user authentication, you don't have to reinvent the wheel
  • In-built password reset functionality
  • Remember me functionality using cookies
  • Validation support with Goravel's Validator
  • Upper/db ORM support
  • Email sending support with Goravel's Mailer
  • Scheduled tasks support (Cron jobs)
  • Helper functions for encryption
  • Goravel Command Line Tool to make your life easier with Goravel

Why Goravel?

  • Goravel is a opinionated web framework that is inspired by Laravel, a popular PHP web framework. It's a heavy duty web framework unlike other micro web frameworks in Go like Gin, Echo, Fiber etc. Goravel is designed to help you build robust and scalable web applications with ease. It's a full stack web framework that comes with a lot of features out of the box so that you can focus on building your application rather than reinventing the wheel.

  • Goravel is built on top of Go's standard library and some popular third party packages loved by the Go community:

  • So you don't have to learn anything new to get started with Goravel. It's a collection of some of the best Go packages that are already popular in the Go community. Goravel just wraps them up in a nice package so that you can build your web applications with ease without you having to set up everything from scratch.

Installation

  1. Install Goravel CLI tool:
go install github.com/saalikmubeen/goravel/cmd/goravel@v1.6.0
  1. Make sure to add $GOPATH/bin to your $PATH so that you can run the Goravel CLI tool from anywhere. If you don't have it, you can add it to your ~/.bashrc or ~/.bash_profile or ~/.zshrc file:
export GOPATH="$HOME/go"
export PATH=$PATH:$GOPATH/bin
  1. Create a new Goravel project:
goravel new myapp
  1. Change directory to your project:
cd myapp
  1. Install the dependencies (just in case):
go mod tidy
  1. Run the server:
go run ./*.go
  1. Visit http://localhost:4000 in your browser to see the welcome page.

Goravel

Example Usage

Check out the Goravel Demo App to see how to use Goravel to build an application with user authentication, cache management, sending JSON and XML responses, email sending, password reset, remember me functionality using cookies, API routes, and much more. It will help you to get started with Goravel quickly.

Goravel Command Line Tool

Goravel comes with a command line tool that makes your life easier with Goravel. You can use the Goravel CLI tool to create a new Goravel project, generate handlers, models, migrations, run migrations, start the server, and much more.

Here are some of the commands that you can use with the Goravel CLI tool:

  • goravel help: Shows the help message

  • goravel version: Shows the version of Goravel CLI tool

  • goravel serve: Start the web server

  • goravel new <project-name>: Create a new Goravel project

  • goravel make handler <handler-name>: Generates a new handler

  • goravel make model <model-name>: Generates a new model

  • goravel make migration <migration-name>: Generates two migration files for up and down operations

  • goravel migrate up: Run all the pending migrations

  • goravel migrate down: Rollback the last migration

  • goravel migrate down all: Rollback all the migrations

  • goravel migrate fix: Fix the migrations table if it's corrupted

  • goravel migrate to <version_number>: Migrate to a specific version (version_number is +ve for up and -ve for down migration)

  • goravel migrate reset: Resets the database. This first runs all the down migrations in reverse order and then runs all the up migrations.

  • goravel make auth: Generates all the necessary files for user authentication. This creates and runs migrations for authentication tables, and creates models and middleware. It also creates handlers for authentication, password reset, and remember me functionality. Yiiiihaaa! You don't have to do anything. Just run this command and you are good to go.

  • goravel make session: Generates all the necessary files for session management if you want to use database for session storage. This creates and runs migrations for session tables, again saving you from the hassle of writing boring migration files.

License

Goravel is open-source software licensed under the MIT license.

Documentation

Index

Constants

View Source
const (
	// Version of Goravel
	Version = "1.6.0"
	Banner = `` /* 314-byte string literal not displayed */

)

Variables

This section is empty.

Functions

This section is empty.

Types

type Database

type Database struct {
	DatabaseType string
	Pool         *sql.DB
}

type Encryption

type Encryption struct {
	Key []byte
}

func (*Encryption) Decrypt

func (e *Encryption) Decrypt(cryptoText string) (string, error)

Decrypt decrypts a string using the AES encryption algorithm

func (*Encryption) Encrypt

func (e *Encryption) Encrypt(text string) (string, error)

Encrypt encrypts a string using the AES encryption algorithm

type ErrorsMap

type ErrorsMap map[string][]string

func (ErrorsMap) Add

func (e ErrorsMap) Add(field, message string)

Add adds an error message to a given Validation field

func (ErrorsMap) Get

func (e ErrorsMap) Get(field string) string

Get returns the first error message for a given field

type Goravel

type Goravel struct {
	AppName       string
	GoAppURL      string
	Debug         bool // true for development mode
	Version       string
	Server        Server
	ErrorLog      *log.Logger
	InfoLog       *log.Logger
	RootPath      string // rootPath is the path that we are in when we start the goravel app
	Render        *render.Render
	Routes        *chi.Mux
	JetViews      *jet.Set
	Session       *scs.SessionManager
	DB            Database
	Cache         cache.Cache
	EncryptionKey string
	Mail          mailer.Mail
	Scheduler     *cron.Cron
	// contains filtered or unexported fields
}

func (*Goravel) BuildDSN

func (g *Goravel) BuildDSN() string

func (*Goravel) ConnectToDatabase

func (g *Goravel) ConnectToDatabase(dbType, dsn string) (*sql.DB, error)

func (*Goravel) CreateDirIfNotExists

func (g *Goravel) CreateDirIfNotExists(path string) error

CreateDirIfNotExists creates a new directory if it does not exist

func (*Goravel) CreateFileIfNotExists

func (g *Goravel) CreateFileIfNotExists(path string) error

CreateFileIfNotExists creates a new file at path if it does not exist

func (*Goravel) CreateFolderStructure

func (g *Goravel) CreateFolderStructure(p InitPaths) error

CreateFolderStructure creates necessary folders for our Goravel application

func (*Goravel) CreateLoggers

func (g *Goravel) CreateLoggers() (*log.Logger, *log.Logger)

func (*Goravel) DownloadFile

func (g *Goravel) DownloadFile(w http.ResponseWriter, r *http.Request, pathToFile, fileName string) error

DownloadFile helps users download files from the server

func (*Goravel) Error404

func (g *Goravel) Error404(w http.ResponseWriter, r *http.Request)

Error404 returns page not found response

func (*Goravel) Error500

func (g *Goravel) Error500(w http.ResponseWriter, r *http.Request)

Error500 returns internal server error response

func (*Goravel) ErrorForbidden

func (g *Goravel) ErrorForbidden(w http.ResponseWriter, r *http.Request)

ErrorForbidden returns a forbidden status message (client is known)

func (*Goravel) ErrorStatus

func (g *Goravel) ErrorStatus(w http.ResponseWriter, status int)

ErrorStatus returns a response with the supplied http status

func (*Goravel) ErrorUnauthorized

func (g *Goravel) ErrorUnauthorized(w http.ResponseWriter, r *http.Request)

ErrorUnauthorized sends an unauthorized status (client is not known)

func (*Goravel) ListenAndServe

func (g *Goravel) ListenAndServe() error

ListenAndServe starts the web server

func (*Goravel) MigrateDownAll

func (g *Goravel) MigrateDownAll(dsn string) error

func (*Goravel) MigrateForce

func (g *Goravel) MigrateForce(dsn string) error

MigrateForce forces the migration to the immediate last version

func (*Goravel) MigrateSteps

func (g *Goravel) MigrateSteps(n int, dsn string) error

Steps runs n steps of migrations. If n > 0, it will run n steps of "up" migrations. If n < 0, it will run n steps of "down" migrations.

func (*Goravel) MigrateUp

func (g *Goravel) MigrateUp(dsn string) error

func (*Goravel) New

func (g *Goravel) New(rootPath string) error

func (*Goravel) NoSurf

func (g *Goravel) NoSurf(next http.Handler) http.Handler

func (*Goravel) RandomString

func (g *Goravel) RandomString(n int) string

RandomString generates a random string of length n from values in the const randomString

func (*Goravel) ReadCSV

func (g *Goravel) ReadCSV(qs url.Values, key string, defaultValue []string) []string

readCSV is a helper method on application type that reads a string value from the URL query string and then splits it into a slice on the comma character. If no matching key is found then it returns the provided default value.

func (*Goravel) ReadIDParam

func (g *Goravel) ReadIDParam(r *http.Request) (int64, error)

readIDParam reads interpolated "id" from request URL and returns it and nil. If there is an error it returns and 0 and an error.

func (*Goravel) ReadInt

func (g *Goravel) ReadInt(qs url.Values, key string, defaultValue int) (int, error)

readInt is a helper method on application type that reads a string value from the URL query string and converts it to an integer before returning. If no matching key is found then it returns the provided default value. If the value couldn't be converted to an integer, then we record an error message in the provided Validator instance, and return the default value.

func (*Goravel) ReadJSON

func (g *Goravel) ReadJSON(w http.ResponseWriter, r *http.Request, dst interface{}) error

readJSON decodes request Body into corresponding Go type. It triages for any potential errors and returns corresponding appropriate errors.

func (*Goravel) ReadStrings

func (g *Goravel) ReadStrings(qs url.Values, key string, defaultValue string) string

readString is a helper method on application type that returns a string value from the URL query string, or the provided default value if no matching key is found.

func (*Goravel) SessionLoad

func (g *Goravel) SessionLoad(next http.Handler) http.Handler

func (*Goravel) Validator

func (g *Goravel) Validator(data url.Values) *Validation

New initializes a custom Validation struct

func (*Goravel) WriteJSON

func (g *Goravel) WriteJSON(w http.ResponseWriter, status int, data Response,
	headers ...http.Header) error

writeJSON marshals data structure to encoded JSON response. It returns an error if there are any issues, else error is nil.

func (*Goravel) WriteXML

func (g *Goravel) WriteXML(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error

WriteXML sends an XML response

type InitPaths

type InitPaths struct {
	RootPath    string   // rootPath is the path that we are in when we start the goravel app
	FolderNames []string // folderNames is the names of the folders that we need to create in the rootPath
}

type Response

type Response map[string]interface{}

Define an envelope type.

type Server

type Server struct {
	ServerName string
	Port       string
	Secure     bool
	URL        string
}

type Validation

type Validation struct {
	// Validation Struct will contain all the key value pairs of the url.Values
	// object(field name and value pairs of html Validation that was submitted by the user)
	Data   url.Values // map[string][]string
	Errors ErrorsMap  // map[string][]string
}

Validation creates a custom Validation struct, embeds a url.Values object

func (*Validation) Check

func (v *Validation) Check(ok bool, field, message string)

Check adds an error message to the validation object if the condition is not met

func (*Validation) HasMinLength

func (v *Validation) HasMinLength(field string, length int, value ...string) bool

func (*Validation) HasRequired

func (v *Validation) HasRequired(requiredFields ...string)

To check if any of the Validation field in POST request is empty or not

func (*Validation) HasValue

func (v *Validation) HasValue(field string, value ...string) bool

To check if a Validation field in POST request is empty or not

func (*Validation) IsDateISO

func (v *Validation) IsDateISO(field string, value ...string) bool

func (*Validation) IsFloat

func (v *Validation) IsFloat(field string, value ...string) bool

func (*Validation) IsInt

func (v *Validation) IsInt(field string, value ...string) bool

func (*Validation) IsValid

func (v *Validation) IsValid() bool

Valid returns true if there are no errors, otherwise false

func (*Validation) IsValidEmail

func (v *Validation) IsValidEmail(field string, value ...string) bool

func (*Validation) IsValidPassword

func (v *Validation) IsValidPassword(field string, value ...string) bool

func (*Validation) IsValidUrl

func (v *Validation) IsValidUrl(field string, value ...string) bool

func (*Validation) IsValidUsername

func (v *Validation) IsValidUsername(field string, value ...string) bool

func (*Validation) NoWhitespace

func (v *Validation) NoWhitespace(field string, value ...string) bool

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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