kwiscale

package module
v0.0.0-...-d174076 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2016 License: BSD-3-Clause Imports: 13 Imported by: 0

README

/!\ Project has moved /!\

Please go to https://github.com/kwiscale to see the entire modules

And https://github.com/kwiscale/framework to see the base project.

kwiscale

Web Middleware for Golang

At this time, Kwiscale is at the very begining of developpement. But you can test and give'em some pull-request to improve it.

Check documentation: http://godoc.org/github.com/kwiscale/framework

Features

  • Implement your handlers as structs with HTTP Verbs as method
  • Plugin system for template engines, session engines and ORM
  • Use gorilla to manipulate routes and mux
  • Handler spawned with concurrency

How to use

Install with "go get" command:

go get github.com/kwiscale/framework

Create a project:

mkdir ~/myproject && cd ~/myproject

The common way to create handlers is to append a package::

mkdir handlers
vim handlers/index.go

Let's try an example:

package handlers

import "github.com/kwiscale/framework"

// this is the Index Handler that
// is composed by a RequestHandler
type IndexHandler struct {
    // compose your handler with kwiscale.Handler
    kwiscale.RequestHandler
}

// Will respond to GET request. "params" are url params (not GET and POST data)
func (i *IndexHandler) Get () {
    i.WriteString("Hello !" + i.Vars["username"])
}

Then in you main.go::


package main

import (
    "github.com/kwiscale/framework"
    "./handlers"
)

// HomeHandler
type HomeHandler struct {
	kwiscale.RequestHandler
}

// Get respond to GET request
func (h *HomeHandler) Get (){
	h.WriteString("reponse to GET home")
}

// Another handler
type OtherHandler struct {
	kwiscale.RequestHandler
}

func (o *OtherHandler) Get (){
	// read url params
	// it always returns a string !
	userid := o.Vars["userid"]
	o.WriteString(fmt.Printf("Hello user %s", userid))
}


func main() {
	kwiscale.DEBUG = true
	app := kwiscale.NewApp(&kswicale.Config{
        Port: ":8000",
    })
	app.AddRoute("/", HomeHandler{})
	app.AddRoute("/user/{userid:[0-9]+}", OtherHandler{})
    app.ListenAndServe()

    // note: App respects http.Mux so you can use:
    // http.ListenAndServe(":9999", app)
    // to override behaviors, testing, or if your infrastructure
    // restricts this usage
}

Then run:

go run main.go

Or build your project:

go build main.go
./main

The Kwiscale way ?

Kwiscale let you declare Handler methods with the HTTP method. This allows you to declare:

  • Get()
  • Post()
  • Head()
  • Delete()
  • Put()
  • Patch()

Basic Templates

Kwiscale provides a "basic" template engine that use http/template. Kwiscale only add a "very basic template override system".

If you plan to have a complete override system, please use http://github.com/kwiscale/template-pango2 that implements pango2 template.

See the following example.

Append templates directory:

mkdir templates

Then create templates/main.html:

<!DOCTYPE html>
<html>
    <head>
        <title>{{ if .title }}{{.title}}{{ else }} Default title {{ end }}</title>
    </head>
    <body>
        {{/* Remember to use "." as context */}}
        {{ template "CONTENT" . }}
    </body>
</html>

Now create templates/home directory:

mkdir templates/home

Create templates/home/welcome.html:

{{/* override "main.html" */}}

{{ define "CONTENT" }}
    This the welcome message {{ .msg }}
{{ end }}

This template overrides "main.html" (in ./templates/ directory) and apppend "CONTENT" template definition. So, the "CONTENT" block will appear at template "CONTENT" in "main.html". That's all.

In handlers/index.go you may now ask for template rendering:

func (h *IndexHandler) Get() {
    h.Render("home/welcome.html", map[string]string{
        "title" : "Welcome !!!",
        "msg"   : "Hello you",
    })
}

You can override template directory using App configuration passed to the constuctor:

app := kwiscale.NewApp(&kswiscale.Config{
    TemplateDir: "./my-template-dir",
})

Documentation

Overview

Kwiscale is a framework that provides Handling System. That means that you will be able to create Handlers that handles HTTP Verbs methods. Kwiscale can handle basic HTTP Verbs as Get, Post, Delete, Patch, Head and Option.

Kwiscale can also serve Websockets.

It provides a basic template system based on http/template from Go SDK and has got a plugin system to provides other template engines

See http://github.com/metal3d/kwiscale-template-pongo2 to use Pongo2.

To handle HTTP Verbs:

type HomeHandler struct {kwiscale.RequetHandler}
func (home *HomeHandler) Get(){
	// This will respond to GET call
	home.WriteString("Hello !")
}

func main(){
	app := kwiscale.NewApp(nil)
	app.AddRoute("/home", HomeHandler{})
	// Default listening on 8000 port
	app.ListenAndServe()
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HandleError

func HandleError(code int, response http.ResponseWriter, req *http.Request, err error)

HandleError write error code in header + message

func RegisterSessionEngine

func RegisterSessionEngine(name string, engine ISessionStore)

RegisterSessionEngine can register session engine that implements ISessionStore. The name is used to let configuration to select it.

func RegisterTemplateEngine

func RegisterTemplateEngine(name string, t ITemplate)

RegisterTemplateEngine records template engine that implements ITemplate interface. The name is used to let config select the template engine.

func SetDebug

func SetDebug(mode bool)

Change debug mode

Types

type App

type App struct {

	// configuration
	Config *Config
	// contains filtered or unexported fields
}

App handles router and handlers.

func NewApp

func NewApp(config *Config) *App

NewApp Create new *App - App constructor.

func (*App) AddRoute

func (app *App) AddRoute(route string, handler interface{})

AddRoute appends route mapped to handler. Note that rh parameter should implement IRequestHandler (generally a struct composing RequestHandler)

func (*App) ListenAndServe

func (a *App) ListenAndServe()

ListenAndServe calls http.ListenAndServe method

func (*App) ServeHTTP

func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

Implement http.Handler ServeHTTP method

func (*App) SetStatic

func (a *App) SetStatic(prefix string)

SetStatic set the route "prefix" to serve files configured in Config.StatiDir

func (*App) SoftStop

func (app *App) SoftStop()

HangOut stops each handler manager goroutine (useful for testing)

type BaseHandler

type BaseHandler struct {
	Response http.ResponseWriter
	Request  *http.Request
	Vars     map[string]string
	// contains filtered or unexported fields
}

BaseHandler is the parent struct of every Handler.

func (*BaseHandler) CleanSession

func (b *BaseHandler) CleanSession()

CleanSession remove every key/value of the current session.

func (*BaseHandler) GetSession

func (b *BaseHandler) GetSession(key interface{}) (interface{}, error)

GetSession return the session value of "key".

func (*BaseHandler) SetSession

func (b *BaseHandler) SetSession(key interface{}, value interface{})

SetSession set the "key" session to "value".

type Config

type Config struct {
	// Root directory where TemplateEngine will get files
	TemplateDir string
	// Port to listen
	Port string
	// Number of handler to prepare
	NbHandlerCache int
	// TemplateEngine to use (default, pango2...)
	TemplateEngine string
	// SessionEngine (default is a file storage)
	SessionsEngine string
	// SessionName is the name of session, eg. Cookie name, default is "kwiscale-session"
	SessionName string
	// A secret string to encrypt cookie
	SessionSecret []byte
	// Static directory (to put css, images, and so on...)
	StaticDir string
	// Activate static in memory cache
	StaticCacheEnabled bool
}

Config structure that holds configuration

type IBaseHandler

type IBaseHandler interface {
	GetSession(interface{}) (interface{}, error)
	SetSession(interface{}, interface{})
	// contains filtered or unexported methods
}

IBaseHandler is the main handler interface that every handler sould implement.

type IRequestHandler

type IRequestHandler interface {
	Get()
	Post()
	Put()
	Head()
	Patch()
	Delete()
}

IRequestHandler interface which declare HTTP verbs.

type ISessionStore

type ISessionStore interface {
	// Init is called when store is initialized while App is initialized
	Init()

	// Name should set the session name
	Name(string)

	// SetSecret should register a string to encode cookie (not mandatory
	// but you should implement this to respect interface)
	SetSecret([]byte)

	// Get a value from storage , interface param is the key
	Get(IBaseHandler, interface{}) (interface{}, error)

	// Set a value in the storage, first interface param is the key,
	// second interface is the value to store
	Set(IBaseHandler, interface{}, interface{})

	// Clean, should cleanup files
	Clean(IBaseHandler)
}

ISessionStore to implement to give a session storage

type ITemplate

type ITemplate interface {
	// Render method to implement to compile and run template
	// then write to ReponseWriter.
	Render(io.Writer, string, interface{}) error

	// SetTemplateDir should set the template base directory
	SetTemplateDir(string)
}

ITemplate should be implemented by other template implementation to allow RequestHandlers to use Render() method

type IWSHandler

type IWSHandler interface {
	// Serve is the method to implement inside the project
	Serve()
	// contains filtered or unexported methods
}

IWSHander is the base template to implement to be able to use Websocket

type RequestHandler

type RequestHandler struct {
	BaseHandler
}

RequestHandler that should be composed by users.

func (*RequestHandler) Delete

func (r *RequestHandler) Delete()

Delete implements IRequestHandler Method - default "not found".

func (*RequestHandler) Get

func (r *RequestHandler) Get()

Get implements IRequestHandler Method - default "not found".

func (*RequestHandler) Head

func (r *RequestHandler) Head()

Head implements IRequestHandler Method - default "not found".

func (*RequestHandler) Patch

func (r *RequestHandler) Patch()

Patch implements IRequestHandler Method - default "not found".

func (*RequestHandler) Post

func (r *RequestHandler) Post()

Post implements IRequestHandler Method - default "not found".

func (*RequestHandler) Put

func (r *RequestHandler) Put()

Put implements IRequestHandler Method - default "not found".

func (*RequestHandler) Render

func (r *RequestHandler) Render(file string, ctx interface{}) error

Render calls assigned template engine Render method.

func (*RequestHandler) Status

func (r *RequestHandler) Status(status int)

Stauts write int status to header (use htt.StatusXXX as status).

func (*RequestHandler) Write

func (r *RequestHandler) Write(data []byte) (int, error)

Write is an alias to RequestHandler.Request.Write. That implements io.Writer.

func (*RequestHandler) WriteString

func (r *RequestHandler) WriteString(data string) (int, error)

WriteString is converts param to []byte then use Write method.

type SessionStore

type SessionStore struct {
	// contains filtered or unexported fields
}

SessionStore is a basic cookie based on gorilla.session.

func (*SessionStore) Clean

func (s *SessionStore) Clean(handler IBaseHandler)

func (*SessionStore) Get

func (s *SessionStore) Get(handler IBaseHandler, key interface{}) (interface{}, error)

Get a value from session by name.

func (*SessionStore) Init

func (s *SessionStore) Init()

Init prepare the cookie storage.

func (*SessionStore) Name

func (s *SessionStore) Name(name string)

Name set session name

func (*SessionStore) Set

func (s *SessionStore) Set(handler IBaseHandler, key interface{}, val interface{})

Set a named value in sessionstore.

func (*SessionStore) SetSecret

func (s *SessionStore) SetSecret(secret []byte)

SetSecret record a string to encode cookie

type Template

type Template struct {
	// contains filtered or unexported fields
}

Basic template engine that use html/template

func (*Template) Render

func (tpl *Template) Render(w io.Writer, file string, ctx interface{}) error

Render method for the basic Template system. Allow {{/* override "path.html" */}}, no cache, very basic.

func (*Template) SetTemplateDir

func (tpl *Template) SetTemplateDir(path string)

type WebSocketHandler

type WebSocketHandler struct {
	BaseHandler
	// contains filtered or unexported fields
}

WebsockerHandler type

func (*WebSocketHandler) GetConnection

func (ws *WebSocketHandler) GetConnection() *websocket.Conn

GetConnection returns the websocket client connection.

func (*WebSocketHandler) Serve

func (ws *WebSocketHandler) Serve()

Serve is the method to implement to serve websocket.

Jump to

Keyboard shortcuts

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