Documentation ¶
Overview ¶
Package utron is a lightweight MVC framework for building fast, scalable and robust web applications
example hello world in utron
type Hello struct { *BaseController } func (h *Hello) World() { h.Ctx.Write([]byte("hello world")) h.String(http.StatusOK) }
Index ¶
- Variables
- func Migrate()
- func RegisterController(ctrl Controller, middlewares ...interface{})
- func RegisterModels(models ...interface{})
- func Run()
- func ServeHTTP(w http.ResponseWriter, r *http.Request)
- func SetConfigPath(path string)
- type App
- type BaseController
- type Config
- type Context
- func (c *Context) Commit() error
- func (c *Context) GetData(key interface{}) interface{}
- func (c *Context) HTML()
- func (c *Context) Init()
- func (c *Context) JSON()
- func (c *Context) Redirect(url string, code int)
- func (c *Context) Request() *http.Request
- func (c *Context) Response() http.ResponseWriter
- func (c *Context) Set(value interface{})
- func (c *Context) SetHeader(key, value string)
- func (c *Context) TextPlain()
- func (c *Context) Write(data []byte) (int, error)
- type Controller
- type DefaultLogger
- type Logger
- type Model
- type Router
- type SimpleView
- type View
Constants ¶
This section is empty.
Variables ¶
var Content = struct { Type string TextPlain string TextHTML string Application struct { Form, JSON, MultipartForm string } }{ "Content-Type", "text/plain", "text/html", struct { Form, JSON, MultipartForm string }{ "application/x-www-form-urlencoded", "application/json", "multipart/form-data", }, }
Content holds http response content type strings
var ( // ErrRouteStringFormat is returned when the route string is of the wrong format ErrRouteStringFormat = errors.New("wrong route string, example is\" get,post;/hello/world;Hello\"") )
Functions ¶
func RegisterController ¶
func RegisterController(ctrl Controller, middlewares ...interface{})
RegisterController registers a controller in the global utron App.
func RegisterModels ¶
func RegisterModels(models ...interface{})
RegisterModels registers models in the global utron App.
func Run ¶
func Run()
Run runs a http server, serving the global utron App.
By using this, you should make sure you followed the MVC pattern.
func ServeHTTP ¶
func ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves request using global utron App.
func SetConfigPath ¶
func SetConfigPath(path string)
SetConfigPath sets the path to look for the configuration files in the global utron App.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the main utron application.
func NewApp ¶
func NewApp() *App
NewApp creates a new bare-bone utron application. To use the MVC components, you should call the Init method before serving requests.
func NewMVC ¶
NewMVC creates a new MVC utron app. If cfg is passed, it should be a directory to look for the configuration files. The App returned is initialized.
func (*App) AddController ¶
func (a *App) AddController(ctrl Controller, middlewares ...interface{})
AddController registers a controller, and middlewares if any is provided.
func (*App) ServeHTTP ¶
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves http requests. It can be used with other http.Handler implementations.
func (*App) Set ¶
func (a *App) Set(value interface{})
Set is for assigning a value to *App components. The following can be set:
Logger by passing Logger View by passing View Router by passing *Router Config by passing *Config Model by passing *Model
func (*App) SetConfigPath ¶
SetConfigPath sets the directory path to search for the config files.
type BaseController ¶
type BaseController struct {
Ctx *Context
}
BaseController implements the Controller interface, It is recommended all user defined Controllers should embed *BaseController.
func (*BaseController) HTML ¶
func (b *BaseController) HTML(code int)
HTML renders text/html with the given code as status code
func (*BaseController) JSON ¶
func (b *BaseController) JSON(code int)
JSON renders application/json with the given code
func (*BaseController) New ¶
func (b *BaseController) New(ctx *Context)
New sets ctx as the active context
func (*BaseController) Render ¶
func (b *BaseController) Render() error
Render commits the changes made in the active context.
func (*BaseController) String ¶
func (b *BaseController) String(code int)
String renders text/plain with given code as status code
type Config ¶
type Config struct { AppName string `json:"app_name" yaml:"app_name" toml:"app_name"` BaseURL string `json:"base_url" yaml:"base_url" toml:"base_url"` Port int `json:"port" yaml:"port" toml:"port"` Verbose bool `json:"verbose" yaml:"verbose" toml:"verbose"` StaticDir string `json:"static_dir" yaml:"static_dir" toml:"static_dir"` ViewsDir string `json:"view_dir" yaml:"view_dir" toml:"view_dir"` Database string `json:"database" yaml:"database" toml:"database"` DatabaseConn string `json:"database_conn" yaml:"database_conn" toml:"database_conn"` }
Config stores configurations values
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns the default configuration settings.
func NewConfig ¶
NewConfig reads configuration from path. The format is deduced from the file extension
- .json - is decoded as json
- .yml - is decoded as yaml
- .toml - is decoded as toml
func (*Config) SyncEnv ¶
SyncEnv overrides c field's values that are set in the environment.
The environment variable names are derived from config fields by underscoring, and uppercasing the name. E.g. AppName will have a corresponding environment variable APP_NAME
NOTE only int, string and bool fields are supported and the corresponding values are set. when the field value is not supported it is ignored.
type Context ¶
type Context struct { // Params are the parameters specified in the url patterns // utron uses gorilla mux for routing. So basically Params stores results // after calling mux.Vars function . // // e.g. if you have route /hello/{world} // when you make request to /hello/gernest , then // in the Params, key named world will have value gernest. meaning Params["world"]=="gernest" Params map[string]string // Data keeps values that are going to be passed to the view as context Data map[string]interface{} // Template is the name of the template to be rendered by the view Template string // Cfg is the application configuration Cfg *Config //DB is the database stuff, with all models registered DB *Model // contains filtered or unexported fields }
Context wraps request and response. It provides methods for handling responses
func NewContext ¶
func NewContext(w http.ResponseWriter, r *http.Request) *Context
NewContext creates new context for the given w and r
func (*Context) Commit ¶
Commit writes the results on the underlying http.ResponseWriter and commits the changes. This should be called only once, subsequent calls to this will result in an error.
If there is a view, and the template is specified the the view is rendered and its output is written to the response, otherwise any data written to the context is written to the ResponseWriter.
func (*Context) GetData ¶
func (c *Context) GetData(key interface{}) interface{}
GetData retrievess any data stored in the request using gorilla.Context package
func (*Context) Response ¶
func (c *Context) Response() http.ResponseWriter
Response returns the http.ResponseWriter object used by the context
func (*Context) Set ¶
func (c *Context) Set(value interface{})
Set sets value in the context object. You can use this to change the following
- Request by passing *http.Request
- ResponseWriter by passing http.ResponseVritter
- view by passing View
- response status code by passing an int
type Controller ¶
Controller is an interface for utron controllers
type DefaultLogger ¶
DefaultLogger is the default logger
func (*DefaultLogger) Errors ¶
func (d *DefaultLogger) Errors(v ...interface{})
Errors log error messages
func (*DefaultLogger) Success ¶
func (d *DefaultLogger) Success(v ...interface{})
Success logs success messages
func (*DefaultLogger) Warn ¶
func (d *DefaultLogger) Warn(v ...interface{})
Warn logs warning messages
type Logger ¶
type Logger interface { Info(v ...interface{}) Errors(fv ...interface{}) Warn(v ...interface{}) Success(v ...interface{}) }
Logger is an interface for utron logger
func NewDefaultLogger ¶
NewDefaultLogger returns a default logger writing to out
type Model ¶
Model facilitate database interactions, supports postgres, mysql and foundation
func NewModel ¶
func NewModel() *Model
NewModel returns a new Model without opening database connection
func NewModelWithConfig ¶
NewModelWithConfig creates a new model, and opens database connection based on cfg settings
func (*Model) AutoMigrateAll ¶
func (m *Model) AutoMigrateAll()
AutoMigrateAll runs migrations for all the registered models
func (*Model) IsOpen ¶
IsOpen returns true if the Model has already established connection to the database
func (*Model) OpenWithConfig ¶
OpenWithConfig opens database connection with the settings found in cfg
type Router ¶
Router registers routes and handlers. It embeds gorilla mux Router
func (*Router) Add ¶
func (r *Router) Add(ctrl Controller, middlewares ...interface{}) error
Add registers ctrl. It takes additional comma separated list of middleware. middlewares are of type
func(http.Handler)http.Handler or func(*Context)error
utron uses the alice package to chain middlewares, this means all alice compatible middleware works out of the box
func (*Router) LoadRoutesFile ¶
LoadRoutesFile loads routes from a json file. Example of the routes file.
{ "routes": [ "get,post;/hello;Sample.Hello", "get,post;/about;Hello.About" ] }
supported formats are json,toml and yaml with extension .json, .toml and .yml respectively.
TODO refactor the decoding part to a separate function? This part shares the same logic as the one found in NewConfig()
type SimpleView ¶
type SimpleView struct {
// contains filtered or unexported fields
}
SimpleView implements View interface, but based on golang templates.