Documentation ¶
Overview ¶
Package rubik is used for accessing Rubik Framework: a minimal and efficient web framework for Go and it's APIs.
Running an empty server:
package main import r "github.com/rubikorg/rubik" func main() { // this runs Rubik server on port: 8000 panic(r.Run()) }
Adding a route:
package main import r "github.com/rubikorg/rubik" func main() { // this runs Rubik server on port: 8000 index := rubik.Route{ Path: "/", Controller: func (req *r.Request) { req.Respond("This is a text response") }, } rubik.UseRoute(index) panic(r.Run()) }
Index ¶
- Constants
- Variables
- func AfterRequest(h RequestHook)
- func Attach(symbol string, b Block)
- func AttachAfter(symbol string, b Block)
- func BeforeRequest(h RequestHook)
- func E(msg string) error
- func GetConfig() interface{}
- func GetStorageContainers() []string
- func Load(config interface{}) error
- func Plug(ext ExtensionBlock)
- func Run() error
- func SetNotFoundHandler(h http.Handler)
- func Use(router Router)
- func UseRoute(route Route)
- type App
- type Assertion
- type BlankRequestEntity
- type Block
- type ByteResponse
- type ByteType
- type Claims
- type Client
- func (c *Client) Delete(entity interface{}) (Response, error)
- func (c *Client) Download(entity DownloadRequestEntity) ([]byte, error)
- func (c *Client) Get(entity interface{}) (Response, error)
- func (c *Client) Post(entity interface{}) (Response, error)
- func (c *Client) Put(entity interface{}) (Response, error)
- type Communicator
- type Controller
- func Ctls(ctls ...Controller) []Controller
- func Proxy(url string) Controller
- func Render(btype ByteType, vars interface{}, paths ...string) Controller
- func UseHandler(handler http.Handler) Controller
- func UseHandlerFunc(fn http.HandlerFunc) Controller
- func UseIntermHandler(intermHandler func(http.Handler) http.Handler) Controller
- type DownloadRequestEntity
- type Entity
- type ExtensionBlock
- type File
- type FileStore
- type HookContext
- type Message
- type MessagePasser
- type Payload
- type RResponseWriter
- type RenderMixin
- type Request
- type RequestHook
- type Response
- type RestErrorMixin
- type Route
- type RouteInfo
- type RouteTree
- type Router
- type SessionManager
- type StorageContainer
- type TestProbe
- type Validation
- type Values
Examples ¶
Constants ¶
const ( // GET method GET = "GET" // POST method POST = "POST" // PUT method PUT = "PUT" // DELETE method DELETE = "DELETE" )
const (
// Version of rubik
Version = "0.2.5"
)
Variables ¶
var Content = struct { Header string JSON string Text string HTML string URLEncoded string Multipart string }{ "Content-Type", "application/json", "text/plain", "text/html", "application/x-www-form-urlencoded", "multipart/form-data", }
Content is a struct that holds default values of Content-Type headers it can be used throughout your rubik application for avoiding basic spell mistakes
var Dispatch = MessagePasser{ Message: make(chan Message), Error: make(chan error), }
Dispatch is topic dispatcher of rubik server
var Storage = StorageContainer{ // contains filtered or unexported fields }
Storage is the Container Access of your storage/ folder
var StringByteTypeMap = map[string]ByteType{ "json": Type.JSON, "html": Type.HTML, "text": Type.Text, }
var Type = struct { HTML ByteType JSON ByteType Text ByteType Bytes ByteType templateHTML ByteType templateText ByteType }{1, 2, 3, 4, 5, 6}
Type is a rubik type literal used for indication of response/template types
Functions ¶
func AfterRequest ¶
func AfterRequest(h RequestHook)
AfterRequest is used to execute the request hook h after completion of the request. A request is said to be complete only after the response is written through http.ResponseWriter interface of http.Server.
func AttachAfter ¶
AttachAfter attaches blocks after boot sequence of routes are complete
func BeforeRequest ¶
func BeforeRequest(h RequestHook)
BeforeRequest is used to execute the request hook h. When a request is sent on a certain route the hook specified as h is executed in a separate goroutine without hindering the current main goroutine of request.
func E ¶
E wraps the message into an error interface and returns it. This method can be used in your controller for throwing error response.
NOTE: this error is not stdlib errors package this is pkg/errors error wrapper
Example ¶
package main import ( "github.com/rubikorg/rubik" ) func main() { r := rubik.Route{ Path: "/test", Controller: func(req *rubik.Request) { req.Throw(403, rubik.E("invalid token or something")) }, } rubik.UseRoute(r) }
Output:
func GetConfig ¶
func GetConfig() interface{}
GetConfig returns the injected config from the Load method
func GetStorageContainers ¶
func GetStorageContainers() []string
GetStorageContainers returns the names of containers present in your storage/ folder. You can access them by calling `Storage.Access` API and use Get or Put to work with your files.
func Load ¶
func Load(config interface{}) error
Load method loads the config/RUBIK_ENV.toml file into the interface given
func Plug ¶ added in v0.2.5
func Plug(ext ExtensionBlock)
Plug adds an extension of Rubik to your workflow
func Run ¶
func Run() error
Run will make sure all dependencies are met, resolves config and it's conflicts with respect to the RUBIC_ENV passed while executing. It boots all your blocks, middlewares message passing channels and port resolution; before starting the server. If this method does not find PORT that is passed as the first argument or the config/*RUBIC_ENV.toml then it startes at :8000.
func SetNotFoundHandler ¶
SetNotFoundHandler sets custom 404 handler
Types ¶
type App ¶
App is a sandboxed object used by the external blocks of code to access some risk-free part of your rubik server For example: App do not have full access to your project config but it has the ability to decode the config that it needs for only this block of code to work
type Assertion ¶ added in v0.2.5
type Assertion func(interface{}) error
Assertion is the assert functions for rubiks validation cycle it should return a message stating why validation failed and bool indicating if assertion has passed or not
type Block ¶
Block is an interface that can be implemented to provide extended functionalities to rubik server Think of it as a plugin which can be attached to the rubik server and can be accessible throughout the lifecycle of rubik server.
A Block can also be thought of as a dependency injected plugin and can be accessed in your controllers by calling rubik.GetBlock('BLOCK_NAME'). Blocks requires you to implement a method called OnAttach. This method is called during rubik server bootstrapper is run and requires you to return an error if any complexity arrises in for your block to function
type ByteResponse ¶
type ByteResponse struct { Status int Data interface{} OfType ByteType Error error // contains filtered or unexported fields }
ByteResponse is the response of rubik server
func RenderContent ¶
func RenderContent(btype ByteType, vars interface{}, paths ...string) ByteResponse
RenderContent returns you the response bytes of the target paths that is going to be written on the wire. It is an abstraction of Render method which is used as a layered method inside Render method.
type Client ¶
type Client struct { Debug bool JWTSecret string BasicSecret string BearerName string UserAgent string // contains filtered or unexported fields }
Client is the implementation for rubik project to create a common abstraction of HTTP calls by passing defined entity
type Communicator ¶
Communicator interface is used to handle the service/driver that rubik's inherent communication depends upon
type Controller ¶
type Controller func(*Request)
Controller ...
func Ctls ¶ added in v0.2.5
func Ctls(ctls ...Controller) []Controller
Ctls adds the controllers one in the order of parameters passed and feeds them to the bootloader
func Proxy ¶
func Proxy(url string) Controller
Proxy does not redirect your current resource locator but makes an internal GET call to the specified URL to serve it's response as your own
func Render ¶
func Render(btype ByteType, vars interface{}, paths ...string) Controller
Render returns a mixin holding the data to be rendered on the web page or sent over the wire
func UseHandler ¶
func UseHandler(handler http.Handler) Controller
UseHandler converts any http,Handler into rubik.Controller
func UseHandlerFunc ¶
func UseHandlerFunc(fn http.HandlerFunc) Controller
UseHandlerFunc converts any http,HandlerFunc into rubik.Controller
func UseIntermHandler ¶
func UseIntermHandler(intermHandler func(http.Handler) http.Handler) Controller
UseIntermHandler converts any func(http,Handler) http,Handler into rubik.Controller
type DownloadRequestEntity ¶
DownloadRequestEntity ...
type Entity ¶
type Entity struct { PointTo string Params []string FormData bool URLEncoded bool JSON bool Infer interface{} Cookies Values // contains filtered or unexported fields }
Entity holds the data for a single API call It lets you write consolidated clean Go code
type ExtensionBlock ¶ added in v0.2.5
ExtensionBlock is executed plugins when RUBIK_ENV = ext. Blocks which requires access to server but does need the server to run. To run your extention block use `okrubik run --ext`
type FileStore ¶
type FileStore struct { Name string // contains filtered or unexported fields }
FileStore lets you perform CRUD on files of StorageContainer FileStore returns the name of container you are accessing by Name field
func (FileStore) GetFile ¶
GetFile returns pointer to os.File for passing it into the rubikClient using File{}.OSFile = return value of this function Other usage may be to obtain file metadata stored
type HookContext ¶
type HookContext struct { Request *http.Request Ctx map[string]interface{} Response []byte Status int }
HookContext ...
type MessagePasser ¶
MessagePasser holds the channels for communication with rubik server
type Payload ¶
type Payload struct {
// contains filtered or unexported fields
}
Payload holds the data between the intermediate state of Client and PostProcessor
type RResponseWriter ¶
type RResponseWriter struct { http.ResponseWriter // contains filtered or unexported fields }
RResponseWriter is Rubik's response writer that implements http.ResponseWriter and it's methods to provide additional functionalities related to Rubik.
func (*RResponseWriter) Write ¶
func (w *RResponseWriter) Write(b []byte) (int, error)
Write writes the response bytes b to the wire
func (*RResponseWriter) WriteHeader ¶
func (w *RResponseWriter) WriteHeader(status int)
WriteHeader writes the http.Request's Header values to the wire and sets the status given as the parameter
type RenderMixin ¶
type RenderMixin struct {
// contains filtered or unexported fields
}
RenderMixin is a mixin holding values for rendering a template
func (RenderMixin) Result ¶
func (rm RenderMixin) Result() []byte
Result returns the parsed/executed content of a template as bytes
type Request ¶
type Request struct { Entity interface{} Session SessionManager Writer RResponseWriter Params httprouter.Params Raw *http.Request Ctx context.Context Claims Claims // contains filtered or unexported fields }
Request ...
func (Request) GetRouteTree ¶
GetRouteTree returns a list of loaded routes in rubik
func (*Request) Redirect ¶
Redirect redirects your request to the given URL with status 302 by default. If you want to provide a custom status for your redirection you can do that by passing in a custom status like so:
func someCtl(req *Request) { req.Redirect("https://ashishshekar.com", http.StatusTemporaryRedirect) }
func (*Request) Respond ¶
Respond is a terminal function for rubik controller that sends byte response it wraps around your arguments for better reading
func (*Request) Throw ¶
Throw writes an error with given status code as response The ByteType parameter is optional as you can convert your error into a JSON or plain text
If you dont have an error object with you in the moment you can use rubik.E() to quickly wrap your string into an error and pass it inside this function
Example ¶
package main import ( "github.com/rubikorg/rubik" ) func main() { func(req *rubik.Request) { req.Throw(403, rubik.E("invalid token or something")) }(&rubik.Request{}) }
Output:
type Response ¶
type Response struct { Status int Body interface{} Raw *http.Response ParsedBody interface{} StringBody string IsJSON bool }
Response is a struct that is returned by every client after request is made successful
type RestErrorMixin ¶
RestErrorMixin type is used by rubik when rubik.Throw is called for writing error types as common JSON structure across Rubik server
func (RestErrorMixin) Error ¶
func (re RestErrorMixin) Error() string
Error implements the error interface of Go
type Route ¶
type Route struct { Path string Method string Description string ResponseDeclarations map[int]string JSON bool Entity interface{} Guards []Controller Middlewares []Controller Validation Validation Controller Controller }
Route defines how a specific route route inside the Rubik server must behave. Route collects all the information required for processing of a HTTP request and performs a handler construction depending upon these values.
There is a specific order in which handlers of Routes are constructed:
[ Entity check --- Guard() --- Validation() --- []Middlewares() --- Controller() ]
type RouteInfo ¶
type RouteInfo struct { Path string Description string BelongsTo string Entity interface{} IsJSON bool Method string Responses map[int]string }
RouteInfo is a flat structure for processing information about the routes
type RouteTree ¶
RouteTree represents your routes as a local map for getting information about your routes
type Router ¶
type Router struct { Middleware []Controller Description string // contains filtered or unexported fields }
Router is used to hold all your rubik routes together
type SessionManager ¶ added in v0.2.5
SessionManager is an interface contract that rubik.Session uses Anything abiding by this contract can
type StorageContainer ¶
type StorageContainer struct {
// contains filtered or unexported fields
}
StorageContainer is abstracted struct to access your storage files. It can access of remove a whole container.
Container corresponds to a single directory in your storage folder and will have access to files only inside this container/directory
func (StorageContainer) Access ¶
func (s StorageContainer) Access(name string) (FileStore, error)
Access a FileStore from your StorageContainer. It can be viewed as accessing a specific folder inside your storage/ folder and performing operations inside of that folder
func (StorageContainer) Remove ¶
func (s StorageContainer) Remove(name string) error
Remove a FileStore from your StorageContainer. Removing a FileStore will remove all the files inside the FileStore
type TestProbe ¶
type TestProbe struct {
// contains filtered or unexported fields
}
TestProbe is an abstraction for easily testing your rubik routes
func NewProbe ¶
NewProbe returns a probe for testing your rubik server
Example:
var probe rubik.TestProbe func init() { // pass the rubik.Router you want to test probe = rubik.NewProbe(index.Router) } func TestSomeRoute(t *testing.T) { // returns the *http.Request, *httptest.ResponseRecorder used inside the test req, rr := probe.Test(en) if rr.Result().StatusCode != 200 { /* Something is wrong */} }
func (TestProbe) TestHandler ¶
func (p TestProbe) TestHandler(method, path string, reqBody io.Reader, en interface{}, h http.Handler) (*http.Request, *httptest.ResponseRecorder)
TestHandler is a probe util function to test your handler if you are not using a rubik.Controller for your route and using UseHandler() to cast it
func (TestProbe) TestSimple ¶ added in v0.2.5
func (p TestProbe) TestSimple(r Route, en interface{}, ctl Controller) *httptest.ResponseRecorder
TestSimple a route with method, path to request, Entity (if used) and the controller to test
type Validation ¶
Validation is validation operations to be performed on the request entity