goring

package module
v0.1.1-beta Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2020 License: Apache-2.0 Imports: 18 Imported by: 1

README

GORING

Introduction

A simple and lightweight web framework, pure native, no third dependencies, including routes, filters, interceptors, static resource resolution, templates without rendering, parameter presets, parameter validation and global cache etc.

Diagrams

Diagram

Install

  1. Git
mkdir -p $GOPATH/src/gitee.com/billcoding/goring

cd $GOPATH/src/gitee.com/Billcoding

git clone https://gitee.com/billcoding/goring.git goring
  1. GoLand
import "gitee.com/billcoding/goring"

Usage

Default bind

package main

import (
	"gitee.com/billcoding/goring"
)

func main() {
	goring.App().Get("/", func(context goring.Context) {
		context.Text("index")
	}).FaviconIco().Run()
}

OR DIY bind

package main

import (
	"gitee.com/billcoding/goring"
)

func main() {
	goring.App().Get("/", func(context goring.Context) {
		context.Text("index")
	}).FaviconIco().RunAs("192.168.1.111", 8080)
}

Tests

Goring-tests

Configuration

Name Key Config Default Description
WebRoot global.webRoot app.SetWebRoot(WEB_ROOT) Exec DIR The goring app webroot
StaticEnable static.enable app.SetStaticEnable(STATIC_ENABLE) false Static resource enable
StaticPattern static.pattern app.SetStaticPattern(STATIC_PATTERN) /static Static resource request URL
StaticPrefix static.prefix app.SetStaticPrefix(STATIC_PREFIX) static Static resource local file prefix
StaticCache static.cache app.SetStaticCache(STATIC_CACHE) true Static resource enable cache
ViewPrefix view.prefix app.SetViewPrefix(VIEW_PREFIX) templates View local file prefix
ViewSuffix view.suffix app.SetViewSuffix(VIEW_SUFFIX) html View local file suffix
ViewCache view.cache app.SetViewCache(VIEW_CACHE) true View enable cache
ValidateErrCode validate.err.code app.SetValidateErrCode(Validate_ERR_CODE) 1 Route field validate err code

examples

config_test.go

Environment Variables Support

  • GORING_HOST overwrites bind addr

  • GORING_PORT overwrites bind port

  • GORING_WEB_ROOT overwrites App webroot

  • GORING_STATIC_CACHE overwrites App static resource cache

  • GORING_VIEW_CACHE overwrites App view cache

Handler Config

Route Types

Type Pattern Examples
Pattern Route /path/subpath /index/id
Variables Route /$var1/$var2 /index/{id}/{name}

Route Methods

Routing is similar to RESTful style mapping

  • N/A using app.Req(PATTERN, HANDLER)

  • GET using app.Get(PATTERN, HANDLER)

  • POST using app.Post(PATTERN, HANDLER)

  • DELETE using app.Delete(PATTERN, HANDLER)

  • PUT using app.Put(PATTERN, HANDLER)

  • PATCH using app.Patch(PATTERN, HANDLER)

Route Methods With Fields

  • N/A using app.Req(PATTERN, HANDLER, FIELD...)

  • GET using app.Get(PATTERN, HANDLER, FIELD...)

  • POST using app.Post(PATTERN, HANDLER, FIELD...)

  • DELETE using app.Delete(PATTERN, HANDLER, FIELD...)

  • PUT using app.Put(PATTERN, HANDLER, FIELD...)

  • PATCH using app.Patch(PATTERN, HANDLER, FIELD...)

Favicon Ico Handler

Integrates automatic processing of Favicon Ico requests using app.FaviconIco().

The favicon ico file should be stored at $WEB_ROOT/$STATIC_PREFIX/favicon.ico

examples

faviconico_test.go

Static Resources Registration

Support for static resource registration using app.RegisterStaticRes(FILE_EXT, MIME_TYPE)

examples

staticres_reg_test.go

Filter

The before filter executes first, and the after filter executes after the after interceptor is executed

Filter chain is supported

Filter cannot be returned to clients

  1. Before filter define using app.FilterBefore(PATTERN, HANDLER)

  2. After filter define using app.FilterAfter(PATTERN, HANDLER)

examples

filter_test.go

Interceptor

The before interceptor executes after the before filter execution is complete, and the after interceptor executes after the routing handler is performed, so the after interceptor can get results to the routing handler

Using context.Response.GetData() get results to the routing handler

Interceptor chain is supported

  1. Before interceptor define using app.InterceptorBefore(PATTERN, HANDLER)

  2. After interceptor define using app.InterceptorAfter(PATTERN, HANDLER)

examples

interceptor_test.go

Field Preset And Validation

Goring allows the route binding fields to be used in the handler when the route is registered, the fields can be automatically pre-set as required by our requirements, and also support sits to validate the fields

When you create a new field using goring.Field(FIELD_NAME), the pre-set and validation is true. So you don't need to call field.Preset() and field.Validate(), unless you need it.

If the field's validation fails, it will be returned directly

  • Define field default value using field.DefaultVal(DEFAULT_VAL)

  • Need to concat multiple values with one value using field.Concat(true)

  • Define concat rune using field.ConcatRune(CONCAT_RUNE) and default ,

  • Need to split a value into multiple values using field.Split(true)

  • Define split rune using field.SplitRune(SPLIT_RUNE) and default ,

  • Define min number value using field.Min(MIN_VALUE)

  • Define max number value using field.Min(MAX_VALUE)

  • Define min length string value using field.MinLength(MIN_LENGTH)

  • Define max length string value using field.MaxLength(MAX_LENGTH)

  • Define optional values using field.Enums(VALUE...)

  • Define regex pattern validate using field.Regex(PATTERN)

examples

fieldset_test.go

Global Cache

Ready when the service starts and ends when the service is destroyed.

  • Set data into caches using app.SetCache(KEY,DATA)

  • Get data from caches using app.GetCache(KEY)

  • Remove data from caches using app.RemoveCache(KEY)

  • Clear caches using app.ClearCaches()

examples

config_cache_test.go

Multipart Support

Integrated simple file operations.

Before you can get the file, you need to parse the request like context.ParseMultipart(MEMORY_SIZE)

  • Get a multipart file using context.GetMultipartFile(FILE_NAME)

  • Get some multipart files using context.GetMultipartFiles(FILE_NAME)

  • Get multipart file original filename using multipartFile.Filename()

  • Get multipart file size in byte using multipartFile.Size()

  • Get multipart file MIME type in byte using multipartFile.ContentType()

  • Get formdata request a header val using multipartFile.Header(NAME)

  • Get formdata request all headers using multipartFile.Headers()

  • Copy to local disk using multipartFile.Copy(DISK_PATH)

examples

multipart_test.go

Performance Report

>ab -n 250000 -c 5000 localhost/

This is ApacheBench, Version 2.3 <$Revision: 1843412 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.ne
t/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 25000 requests
Completed 50000 requests
Completed 75000 requests
Completed 100000 requests
Completed 125000 requests
Completed 150000 requests
Completed 175000 requests
Completed 200000 requests
Completed 225000 requests
Completed 250000 requests
Finished 250000 requests


Server Software:        goring/0.1-beta
Server Hostname:        localhost
Server Port:            80

Document Path:          /
Document Length:        13 bytes

Concurrency Level:      5000
Time taken for tests:   45.580 seconds
Complete requests:      250000
Failed requests:        0
Total transferred:      46500000 bytes
HTML transferred:       3250000 bytes
Requests per second:    5484.91 [#/sec] (mean)
Time per request:       911.592 [ms] (mean)
Time per request:       0.182 [ms] (mean, across all concurrent reques
ts)
Transfer rate:          996.28 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   1.8      0     508
Processing:   274  905 134.7    879    1432
Waiting:        0  455 226.5    451    1371
Total:        274  905 134.7    879    1432

Percentage of the requests served within a certain time (ms)
  50%    879
  66%    883
  75%    887
  80%    890
  90%    916
  95%   1374
  98%   1409
  99%   1420
 100%   1432 (longest request)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type App

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

Define app struct

func NewApp

func NewApp() *App

Return new App

func (*App) ClearCaches

func (app *App) ClearCaches()

clear caches

func (*App) DefaultHandler

func (app *App) DefaultHandler(handler Handler) *App

Config default handler

func (*App) Delete

func (app *App) Delete(pattern string, handler Handler, fields ...*Field) *App

Route Handler for DELETE method

func (*App) FaviconIco

func (app *App) FaviconIco() *App

Enable default favicon ico handler

func (*App) FilterAfter

func (app *App) FilterAfter(pattern string, filterHandler FilterHandler) *App

Route after filter

func (*App) FilterBefore

func (app *App) FilterBefore(pattern string, filterHandler FilterHandler) *App

Route before filter

func (*App) Get

func (app *App) Get(pattern string, handler Handler, fields ...*Field) *App

Route Handler for GET method

func (*App) GetCache

func (app *App) GetCache(key string) interface{}

Get data from app storage

func (*App) GetContextPath

func (app *App) GetContextPath() string

Get contextPath

func (*App) GetStaticCache

func (app *App) GetStaticCache() bool

Get static cache

func (*App) GetStaticEnable

func (app *App) GetStaticEnable() bool

Get static enable

func (*App) GetStaticPattern

func (app *App) GetStaticPattern() string

Get static pattern

func (*App) GetStaticPrefix

func (app *App) GetStaticPrefix() string

Get static prefix

func (*App) GetValidateErrCode

func (app *App) GetValidateErrCode() int

Get validate err code

func (*App) GetViewCache

func (app *App) GetViewCache() bool

Get view cache

func (*App) GetViewPrefix

func (app *App) GetViewPrefix() string

Get view prefix

func (*App) GetViewSuffix

func (app *App) GetViewSuffix() string

Get view suffix

func (*App) GetWebRoot

func (app *App) GetWebRoot() string

Get webRoot

func (*App) InterceptorAfter

func (app *App) InterceptorAfter(pattern string, interceptorHandler InterceptorHandler) *App

Route after interceptor

func (*App) InterceptorBefore

func (app *App) InterceptorBefore(pattern string, interceptorHandler InterceptorHandler) *App

Route before interceptor

func (*App) LogFatal

func (app *App) LogFatal(message string, args ...interface{})

Log fatal

func (*App) LogInfo

func (app *App) LogInfo(message string, args ...interface{})

Log info

func (*App) LogWarn

func (app *App) LogWarn(message string, args ...interface{})

Log warn

func (*App) Patch

func (app *App) Patch(pattern string, handler Handler, fields ...*Field) *App

Route Handler for PATCH method

func (*App) Post

func (app *App) Post(pattern string, handler Handler, fields ...*Field) *App

Route Handler for POST method

func (*App) Put

func (app *App) Put(pattern string, handler Handler, fields ...*Field) *App

Route Handler for PUT method

func (*App) RegisterStaticRes

func (app *App) RegisterStaticRes(fileExt, contentType string) *App

Register a static res

func (*App) RemoveCache

func (app *App) RemoveCache(key string)

remove data from app storage

func (*App) Req

func (app *App) Req(pattern string, handler Handler, fields ...*Field) *App

Route Handler for all method

func (*App) RequestNotSupportedHandler

func (app *App) RequestNotSupportedHandler(handler Handler) *App

Config request not supported handler

func (*App) Run

func (app *App) Run()

Run the server

func (*App) RunAs

func (app *App) RunAs(host string, port int)

Run as the server

func (*App) SetCache

func (app *App) SetCache(key string, data interface{})

Set data into app storage

func (*App) SetContextPath

func (app *App) SetContextPath(contextPath string) *App

Set contextPath

func (*App) SetStaticCache

func (app *App) SetStaticCache(cache bool) *App

Set static cache

func (*App) SetStaticEnable

func (app *App) SetStaticEnable(enable bool) *App

Set static enable

func (*App) SetStaticPattern

func (app *App) SetStaticPattern(pattern string) *App

Set static pattern

func (*App) SetStaticPrefix

func (app *App) SetStaticPrefix(prefix string) *App

Set static prefix

func (*App) SetValidateErrCode

func (app *App) SetValidateErrCode(code int) *App

Set validate err code

func (*App) SetViewCache

func (app *App) SetViewCache(cache bool) *App

Set view cache

func (*App) SetViewPrefix

func (app *App) SetViewPrefix(prefix string) *App

Set view prefix

func (*App) SetViewSuffix

func (app *App) SetViewSuffix(suffix string) *App

Set view suffix

func (*App) SetWebRoot

func (app *App) SetWebRoot(webRoot string) *App

Set webRoot

func (*App) TLS

func (app *App) TLS(certFile, keyFile string)

Enable TLS mode

type Context

type Context struct {
	Request          *http.Request       //request
	RequestURI       string              //request uri
	ParsedRequestURI string              //parsed request uri
	RequestMethod    string              //request method
	RequestHeader    http.Header         //request header
	ResponseWriter   http.ResponseWriter //Response writer
	ResponseHeader   *http.Header        //Response header
	//K<string>,V<*list.ArrayList<MultipartFile>>
	Multipart *hashmap.HashMap //multipart map
	//K<string>,V<*list.ArrayList<string>>
	Parameters      *hashmap.HashMap //map[string][]string
	MultipartParsed bool             //multipart parsed ?
	Response        *Response        //Response
}

Define context struct

func (*Context) AddHeader

func (context *Context) AddHeader(name, value string) *Context

Add Response header

func (*Context) Binary

func (context *Context) Binary(buffer []byte)

Response binary to client

func (*Context) BinaryWith

func (context *Context) BinaryWith(buffer []byte, contentType string)

Response binary to client with ContentType

func (*Context) ClearCache

func (context *Context) ClearCache()

Clear app cache

func (*Context) GetCache

func (context *Context) GetCache(key string) interface{}

Get app cache

func (*Context) GetMultipartFile

func (context *Context) GetMultipartFile(name string) *MultipartFile

Get multipart file

func (*Context) GetMultipartFiles

func (context *Context) GetMultipartFiles(name string) []*MultipartFile

Get request parameter

func (*Context) GetParameter

func (context *Context) GetParameter(name string) string

Get request parameter

func (*Context) GetParameterWithDefault

func (context *Context) GetParameterWithDefault(name, defaultValue string) string

Get request parameter with default

func (*Context) GetParameters

func (context *Context) GetParameters(name string) []string

Get request parameters

func (*Context) GetParametersWithDefault

func (context *Context) GetParametersWithDefault(name string, defaultValue []string) []string

Get request parameters with default

func (*Context) Image

func (context *Context) Image(buffer []byte)

Response image to client

func (*Context) JSON

func (context *Context) JSON(data interface{})

Response json to client

func (*Context) ParseMultipart

func (context *Context) ParseMultipart(maxMemory int64) error

Parse Multipart

func (*Context) RemoveCache

func (context *Context) RemoveCache(key string)

Remove app cache

func (*Context) SetCache

func (context *Context) SetCache(key string, data interface{})

Set app cache

func (*Context) SetHeader

func (context *Context) SetHeader(name, value string) *Context

Set content type

func (*Context) Text

func (context *Context) Text(text string)

Response text to client

func (*Context) View

func (context *Context) View(name string)

Response view to client

type Field

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

Define field struct

func NewField

func NewField(name string) *Field

func (*Field) Concat

func (field *Field) Concat(concat bool) *Field

concat

func (*Field) ConcatRune

func (field *Field) ConcatRune(concatRune rune) *Field

concat rune

func (*Field) DefaultVal

func (field *Field) DefaultVal(defaultVal string) *Field

default val

func (*Field) Enums

func (field *Field) Enums(enums ...string) *Field

enums

func (*Field) Fixed

func (field *Field) Fixed(fixed string) *Field

fixed

func (*Field) Length

func (field *Field) Length(length int) *Field

length

func (*Field) Max

func (field *Field) Max(max int) *Field

max

func (*Field) MaxLength

func (field *Field) MaxLength(maxLength int) *Field

maxLength

func (*Field) Min

func (field *Field) Min(min int) *Field

min

func (*Field) MinLength

func (field *Field) MinLength(minLength int) *Field

minLength

func (*Field) Name

func (field *Field) Name(name string) *Field

name

func (*Field) Preset

func (field *Field) Preset(preset bool) *Field

set

func (*Field) Regex

func (field *Field) Regex(regex string) *Field

regex

func (*Field) Split

func (field *Field) Split(split bool) *Field

split

func (*Field) SplitRune

func (field *Field) SplitRune(splitRune rune) *Field

split rune

func (*Field) Validate

func (field *Field) Validate(validate bool) *Field

validate

type FilterContext

type FilterContext struct {
	RequestURI       string
	ParsedRequestURI string
	RequestMethod    string
	RequestHeader    http.Header
	ResponseHeader   *http.Header
	Parameters       *hashmap.HashMap //map[string][]string
}

Define filter context

type FilterHandler

type FilterHandler func(FilterContext)

Define filter handler

type Handler

type Handler func(context Context)

Define handler

type InterceptorHandler

type InterceptorHandler func(Context)

Define interceptor handler

type MultipartFile

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

Define MultipartFile struct

func (*MultipartFile) ContentType

func (file *MultipartFile) ContentType() string

Get multipart file content type

func (*MultipartFile) Copy

func (file *MultipartFile) Copy(distName string) error

Copy file to dist name

func (*MultipartFile) Filename

func (file *MultipartFile) Filename() string

Get multipart file name

func (*MultipartFile) Header

func (file *MultipartFile) Header(name string) string

Get multipart header

func (*MultipartFile) Headers

func (file *MultipartFile) Headers() *hashmap.HashMap

Get multipart headers

func (*MultipartFile) Size

func (file *MultipartFile) Size() int64

Get multipart file size in byte

type Response

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

Define Response struct

func (*Response) GetContentType

func (response *Response) GetContentType() string

Get content type

func (*Response) GetData

func (response *Response) GetData() []byte

Get data

func (*Response) GetHeaders

func (response *Response) GetHeaders() *hashmap.HashMap

Set done

func (*Response) SetContentType

func (response *Response) SetContentType(contentType string) *Response

Set content type

func (*Response) SetDone

func (response *Response) SetDone(done bool) *Response

Set done

func (*Response) SetHeaders

func (response *Response) SetHeaders(headers *hashmap.HashMap) *Response

Set done

type StaticHandler

type StaticHandler func(context Context, contentType, resourcePath string)

Define static handler

Jump to

Keyboard shortcuts

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