mego

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

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

Go to latest
Published: Sep 15, 2017 License: Apache-2.0 Imports: 24 Imported by: 2

README

mego

mego route framework

Sample
package main

import "github.com/simbory/mego"
import (
	"fmt"
	"github.com/simbory/mego/session/memory"
	"github.com/simbory/mego/session"
	"github.com/simbory/mego/cache"
	"io/ioutil"
	"time"
)

func pageFilter(ctx *mego.HttpCtx) {
	if ctx.Request().URL.Path == "/" {
		ctx.SetCtxItem("pageName", "home")
	}
}

func handleHome(ctx *mego.HttpCtx) interface{} {
	return ctx.TextResult(
		fmt.Sprintf("Hello, mego! this is the %s page", ctx.GetCtxItem("pageName")),
		"text/plain",
	)
}

func handleSession(ctx *mego.HttpCtx) interface{} {
	s := session.Default().Start(ctx)
	data := s.Get("data")
	if data == nil {
		data = "test session data"
		s.Set("data", data)
		return map[string]interface{} {
			"from_session": false,
			"data": data,
		}
	} else {
		return map[string]interface{} {
			"from_session": true,
			"data": data,
		}
	}
}

func handleCache(ctx *mego.HttpCtx) interface{} {
	data := cache.Default().Get("cache_data")
	if data == nil {
		data = "test cache data"
		dataFile := ctx.MapRootPath("/cache-dependency-file.txt")
		ioutil.WriteFile(dataFile, []byte(data.(string)), 0777)
		cache.Default().Set("cache_data", data, []string{dataFile}, 1 * time.Hour)
		return map[string]interface{} {
			"from_cache": false,
			"data": data,
		}
	} else {
		return map[string]interface{} {
			"from_cache": true,
			"data": data,
		}
	}
}

func main() {
	server := mego.NewServer(mego.WorkingDir(), ":8080")
	server.Route("/", handleHome)
	server.Route("/test-session", handleSession)
	server.Route("/test-cache", handleCache)
	server.HijackRequest("/", pageFilter)

	sessionProvider := memory.NewProvider()
	sessionManager := session.CreateManager(nil, sessionProvider)
	session.UseAsDefault(sessionManager)

	cache.UseDefault()

	server.Run()
}

Documentation

Index

Constants

View Source
const Version = "1.0"

Variables

This section is empty.

Functions

func ClearPath

func ClearPath(pathStr string) string

ClearPath clear the pathStr and return the shortest path.

func EnsurePrefix

func EnsurePrefix(s, prefix string) string

EnsurePrefix ensure that the string s must has the prefix

func EnsureSuffix

func EnsureSuffix(s, suffix string) string

EnsureSuffix ensure that the string s must has suffix

func ExeDir

func ExeDir() string

ExeDir get the current directory that the executable file is located in.

func WorkingDir

func WorkingDir() string

WorkingDir get the current working directory

Types

type Area

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

Area implement mego area

func (*Area) Dir

func (a *Area) Dir() string

Dir get the physical directory of the current area

func (*Area) ExtendView

func (a *Area) ExtendView(name string, f interface{})

ExtendView add view function to the view engine of the current area

func (*Area) HijackRequest

func (a *Area) HijackRequest(pathPrefix string, h func(*HttpCtx))

HijackRequest hijack the area dynamic request that starts with pathPrefix

func (*Area) Key

func (a *Area) Key() string

Key get the area key/pathPrefix

func (*Area) Route

func (a *Area) Route(routePath string, handler interface{})

Route used to register router for all methods

type BufResult

type BufResult struct {
	ContentType string
	Encoding    string

	StatusCode int
	// contains filtered or unexported fields
}

BufResult the buffered result

func NewBufResult

func NewBufResult(buf *bytes.Buffer) *BufResult

NewBufResult create a new buffer result with default value buf

func (*BufResult) AddHeader

func (b *BufResult) AddHeader(key, value string)

AddHeader write http header to the result

func (*BufResult) ExecResult

func (b *BufResult) ExecResult(w http.ResponseWriter, r *http.Request)

ExecResult write the data in the result buffer to the response writer

func (*BufResult) ReadFrom

func (b *BufResult) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom read the data from reader r and write to the result buffer

func (*BufResult) Write

func (b *BufResult) Write(p []byte) (n int, err error)

Write write byte array p to the result buffer

func (*BufResult) WriteByte

func (b *BufResult) WriteByte(c byte) error

WriteByte write byte c to the result buffer

func (*BufResult) WriteRune

func (b *BufResult) WriteRune(r rune) (n int, err error)

WriteRune write rune r to the result buffer

func (*BufResult) WriteString

func (b *BufResult) WriteString(s string) (n int, err error)

WriteString write string s to the result buffer

type ErrHandler

type ErrHandler func(http.ResponseWriter, *http.Request, interface{})

ErrHandler define the internal s error handler func

type FileResult

type FileResult struct {
	ContentType string
	FilePath    string
}

FileResult the file result

func (*FileResult) ExecResult

func (fr *FileResult) ExecResult(w http.ResponseWriter, r *http.Request)

ExecResult execute the result

type HttpCtx

type HttpCtx struct {
	Server *Server
	// contains filtered or unexported fields
}

HttpCtx the mego http context struct

func (*HttpCtx) CtxId

func (ctx *HttpCtx) CtxId() uint64

CtxId get the http context id

func (*HttpCtx) End

func (ctx *HttpCtx) End()

End end the mego context and stop the rest request function

func (*HttpCtx) FileResult

func (ctx *HttpCtx) FileResult(path string, contentType string) Result

FileResult generate the mego result as file result

func (*HttpCtx) FormValue

func (ctx *HttpCtx) FormValue(key string) string

FormValue get the form value from request. It's the same as ctx.Request().FormValue(key)

func (*HttpCtx) GetCtxItem

func (ctx *HttpCtx) GetCtxItem(key string) interface{}

GetCtxItem get the context data from mego context by key

func (*HttpCtx) JsonResult

func (ctx *HttpCtx) JsonResult(data interface{}) Result

JsonResult generate the mego result as JSON string

func (*HttpCtx) JsonpResult

func (ctx *HttpCtx) JsonpResult(data interface{}, callback string) Result

JsonpResult generate the mego result as jsonp string

func (*HttpCtx) MapContentPath

func (ctx *HttpCtx) MapContentPath(urlPath string) string

MapContentPath Returns the physical file path that corresponds to the specified virtual path.

func (*HttpCtx) MapRootPath

func (ctx *HttpCtx) MapRootPath(path string) string

MapRootPath Returns the physical file path that corresponds to the specified virtual path.

func (*HttpCtx) PostFile

func (ctx *HttpCtx) PostFile(formName string) *UploadFile

PostFile get the post file info

func (*HttpCtx) QueryStr

func (ctx *HttpCtx) QueryStr(key string) string

QueryStr get the value from the url query string

func (*HttpCtx) Redirect

func (ctx *HttpCtx) Redirect(urlStr string, permanent bool)

func (*HttpCtx) RedirectResult

func (ctx *HttpCtx) RedirectResult(urlStr string, permanent bool) Result

Redirect get the redirect result. if the value of 'permanent' is true , the status code is 301, else the status code is 302

func (*HttpCtx) RemoveCtxItem

func (ctx *HttpCtx) RemoveCtxItem(key string)

RemoveCtxItem delete context item from mego context by key

func (*HttpCtx) Request

func (ctx *HttpCtx) Request() *http.Request

Request get the mego request

func (*HttpCtx) Response

func (ctx *HttpCtx) Response() http.ResponseWriter

Response get the mego response

func (*HttpCtx) RouteVar

func (ctx *HttpCtx) RouteVar(key string) string

RouteString get the route parameter value as string by key

func (*HttpCtx) SetCtxItem

func (ctx *HttpCtx) SetCtxItem(key string, data interface{})

SetCtxItem add context data to mego context

func (*HttpCtx) TextResult

func (ctx *HttpCtx) TextResult(content, contentType string) Result

TextResult generate the mego result as plain text

func (*HttpCtx) ViewResult

func (ctx *HttpCtx) ViewResult(viewName string, data interface{}) Result

ViewResult find the view by view name, execute the view template and get the result

func (*HttpCtx) XmlResult

func (ctx *HttpCtx) XmlResult(data interface{}) Result

XmlResult generate the mego result as XML string

type RedirectResult

type RedirectResult struct {
	RedirectURL string
	StatusCode  int
}

RedirectResult the redirect result

func (*RedirectResult) ExecResult

func (rr *RedirectResult) ExecResult(w http.ResponseWriter, r *http.Request)

ExecResult execute the redirect result

type Result

type Result interface {
	ExecResult(w http.ResponseWriter, r *http.Request)
}

Result the request result interface

type RouteConnect

type RouteConnect interface {
	Connect(ctx *HttpCtx) interface{}
}

type RouteCopy

type RouteCopy interface {
	Copy(ctx *HttpCtx) interface{}
}

RouteCopy WebDAV http method 'COPY' processing interface

type RouteDelete

type RouteDelete interface {
	Delete(ctx *HttpCtx) interface{}
}

type RouteFilter

type RouteFilter interface {
	Filter(ctx *HttpCtx)
}

type RouteFunc

type RouteFunc func(urlPath string, opt RouteOpt) string

RouteFunc define the route check function

type RouteGet

type RouteGet interface {
	Get(ctx *HttpCtx) interface{}
}

type RouteHead

type RouteHead interface {
	Head(ctx *HttpCtx) interface{}
}

type RouteLock

type RouteLock interface {
	Lock(ctx *HttpCtx) interface{}
}

RouteLock WebDAV http method 'LOCK' processing interface

type RouteMkcol

type RouteMkcol interface {
	Mkcol(ctx *HttpCtx) interface{}
}

RouteMkcol WebDAV http method 'MKCOL' processing interface

type RouteMove

type RouteMove interface {
	Move(ctx *HttpCtx) interface{}
}

RouteMove WebDAV http method 'MOVE' processing interface

type RouteOpt

type RouteOpt interface {
	Validation() string
	Setting() string
	MaxLength() int
	MinLength() int
}

RouteOpt the route option struct

type RouteOptions

type RouteOptions interface {
	Options(ctx *HttpCtx) interface{}
}

type RoutePatch

type RoutePatch interface {
	Patch(ctx *HttpCtx) interface{}
}

type RoutePost

type RoutePost interface {
	Post(ctx *HttpCtx) interface{}
}

type RouteProcessor

type RouteProcessor interface {
	ProcessRequest(ctx *HttpCtx) interface{}
}

type RoutePropFind

type RoutePropFind interface {
	PropFind(ctx *HttpCtx) interface{}
}

RoutePropFind WebDAV http method 'PROPFIND' processing interface

type RoutePropPatch

type RoutePropPatch interface {
	PropPatch(ctx *HttpCtx) interface{}
}

RoutePropPatch WebDAV http method 'PROPPATCH' processing interface

type RoutePut

type RoutePut interface {
	Put(ctx *HttpCtx) interface{}
}

type RouteTrace

type RouteTrace interface {
	Trace(ctx *HttpCtx) interface{}
}

type RouteUnlock

type RouteUnlock interface {
	Unlock(ctx *HttpCtx) interface{}
}

RouteUnlock WebDAV http method 'UNLOCK' processing interface

type Server

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

func NewServer

func NewServer(webRoot, addr string) *Server

NewServer create a new server

webRoot: the root of this web server. and the content root is '${webRoot}/www'

addr: the address the server is listen on

func (*Server) AddRouteFunc

func (s *Server) AddRouteFunc(name string, fun RouteFunc)

AddRouteFunc add route validation func

func (*Server) ExtendView

func (s *Server) ExtendView(name string, f interface{})

ExtendView extend the view engine with func f

func (*Server) GetArea

func (s *Server) GetArea(pathPrefix string) *Area

GetArea get or create the mego area

func (*Server) GetVar

func (s *Server) GetVar(key string) interface{}

func (*Server) GetVarBool

func (s *Server) GetVarBool(key string, defaultValue bool) bool

func (*Server) GetVarFloat

func (s *Server) GetVarFloat(key string, defaultValue float64) float64

func (*Server) GetVarInt

func (s *Server) GetVarInt(key string, defaultValue int) int

func (*Server) GetVarStr

func (s *Server) GetVarStr(key string, defaultValue string) string

func (*Server) Handle400

func (s *Server) Handle400(h http.HandlerFunc)

Handle404 set custom error handler for status code 404

func (*Server) Handle403

func (s *Server) Handle403(h http.HandlerFunc)

Handle404 set custom error handler for status code 404

func (*Server) Handle404

func (s *Server) Handle404(h http.HandlerFunc)

Handle404 set custom error handler for status code 404

func (*Server) Handle500

func (s *Server) Handle500(h func(http.ResponseWriter, *http.Request, interface{}))

Handle500 set custom error handler for status code 500

func (*Server) HijackRequest

func (s *Server) HijackRequest(pathPrefix string, h func(*HttpCtx))

Hijack hijack the dynamic request that starts with pathPrefix

func (*Server) MapContentPath

func (s *Server) MapContentPath(virtualPath string) string

MapContentPath Returns the physical file path that corresponds to the specified virtual path. @param virtualPath: the virtual path starts with @return the absolute file path

func (*Server) MapRootPath

func (s *Server) MapRootPath(virtualPath string) string

MapRootPath Returns the physical file path that corresponds to the specified virtual path. @param virtualPath: the virtual path starts with @return the absolute file path

func (*Server) OnStart

func (s *Server) OnStart(h func())

OnStart attach an event handler to the s start event

func (*Server) Route

func (s *Server) Route(routePath string, handler interface{})

Route used to register router for all methods

func (*Server) Run

func (s *Server) Run()

Run run the application as http

func (*Server) RunTLS

func (s *Server) RunTLS(certFile, keyFile string)

RunTLS run the application as https

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) SetVar

func (s *Server) SetVar(key string, v interface{})

type UploadFile

type UploadFile struct {
	FileName string
	Size     int64
	Error    error
	File     multipart.File
	Header   *multipart.FileHeader
}

UploadFile the uploaded file struct

func (*UploadFile) Save

func (file *UploadFile) Save(path string) error

Save save the posted file data as a file.

func (*UploadFile) SaveAndClose

func (file *UploadFile) SaveAndClose(path string) error

SaveAndClose save the posted file as a file and then close the posted data stream

type ViewEngine

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

ViewEngine the mego view engine struct

func NewViewEngine

func NewViewEngine(viewDir string) *ViewEngine

NewViewEngine create a new view engine in ViewDir with file extension '.gohtml'

func (*ViewEngine) ExtendView

func (e *ViewEngine) ExtendView(name string, viewFunc interface{})

ExtendView extend the view helper functions with 'name' and 'viewFunc'

func (*ViewEngine) Render

func (e *ViewEngine) Render(viewName string, data interface{}) Result

Render render the view 'viewName' with 'data' and get the view result

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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