cola

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2021 License: MIT Imports: 37 Imported by: 1

README

cola

Coke is a very simple microservice web framework

功能开发

  • 支持Cookie操作
  • 支持 html/template

How to use 如何使用(通过 go mod方式)

Step 1: 创建项目

# 创建一个目录
mkdir yourapp 

# 进入目录 
cd yourapp

# 初始化 go mod
go mod init yourapp

# vscode 打开这个目录
code .

Step 2: 编写一个网页服务器

写一个main

创建一个文件名为 main.go 并写入如下代码

package main

import (
	"github.com/xs23933/cola"
)

func main(){
	app := cola.New()
	app.Serve(8080)
}

以上代码启动了网页服务器并监听了 8080端口

编写一个 Handler (Controller)

创建一个目录 handler 并在里面创建一个你自己想起名的文件 例如 handler.go

handler.go

package handler

import (
	"github.com/xs23933/cola"
)

type Handler struct {
	cola.Handler
}

// Get  这里就实现了 根Path Handler
//
// 同等于  get /
func (Handler) Get(c *cola.Ctx) {
	c.Write([]byte("i love china"))
}

// GetAbout 带/目录的方法 
//
// get /about
func (Handler) GetAbout(c *cola.Ctx) {
	c.Write([]byte("i'm Cola, it's very sample web module"))
}

// GetWelcomeParam 带参数的方法定义,这里的Param是关键字
// get /welcome/:param
func (Handler) GetWelcomeParam(c *cola.Ctx) {
	your := c.Params("param")
	c.Write([]byte("Welcome " + your))
}

// PostSignup 接收 Post 数据方式 及采用 json返回数据
//
// post /signup
func (Handler) PostSignup(c *cola.Ctx) {
	form := make(map[string]interface{})
	if err := c.ReadBody(&form); err != nil {
		c.ToJSON(nil, err) // 读取失败返回错误信息
		return
	}

	c.ToJSON(form, nil)
}
修改下原来的 main.go

main.go 改为如下

package main

import (
	"yourapp/handler"
	"github.com/xs23933/cola"
)

func main(){
	app := cola.New()
	// 注册 handler
	app.Use(new(Handler))
	if err := app.Serve(8080); err != nil { // 友好的监视错误信息
		panic(err)
	}
}

ok 以上代码就能实现一个简单的网页服务器


更多高级使用方法

传入调试
func main(){
	app := cola.New(&cola.Options{
		Debug: true, // 修改为debug状态
	})
}
开启多进程服务模式 (Prefork)
func main(){
	app := cola.New(&cola.Options{
		Debug: true,
		Prefork: true,
	})
}
更多选项详见

cola.Options

针对每个handler 可以设置 方法前缀
func (Handler) Init(){
	h.SetPrefix("/api")
}
handler 前面挂钩子 比如识别网站,查询登录用户信息等放hook里面
func (Handler) Preload(c *cola.Ctx) {
	token := c.Get("Authorization") // 获得 headder 或 通过 cookie 获得 登录令牌
	user := model.AuthUser(token) // 查询已登录用户信息 返回
	c.Vars("us", user) // 存在 Ctx(Context) 中 任何下一步插件使用
}

Handler 定义 自动注册方法


// Handler Handler
type Handler struct {
	cola.Handler
}

// GetThemeParams get /theme/:param?
func (Handler) GetThemeParams(c *cola.Ctx) {
	theme := c.Params("param") // 获得路径参数
	c.Core.Views.Theme(theme) // 修改模版风格
}

// Get get /
func (Handler) Get(c *cola.Ctx) {
	c.Vars("title", "Hello world") // 设置全局变量
	c.Render("main") // 模版解析
}

启动服务


func main() {
	debug := true
	view := cola.NewView("./views", ".html", debug).Layout("layout")
	app := cola.New(&cola.Options{
		Prefork: false,
		Debug:   debug,
		ETag:    true,
		Views:   view,
	})

	models.New("mysql", "root:caisong.com@tcp(127.0.0.1:3306)/example?charset=utf8mb4&parseTime=True&loc=UTC", debug)
	app.Use(new(handler.Handler))

	app.Serve(8080)
}

Documentation

Index

Constants

View Source
const (
	MethodConnect = "CONNECT" // RFC 7231, 4.3.6
	MethodDelete  = "DELETE"  // RFC 7231, 4.3.5
	MethodGet     = "GET"     // RFC 7231, 4.3.1
	MethodHead    = "HEAD"    // RFC 7231, 4.3.2
	MethodOptions = "OPTIONS" // RFC 7231, 4.3.7
	MethodPatch   = "PATCH"   // RFC 5789
	MethodPost    = "POST"    // RFC 7231, 4.3.3
	MethodPut     = "PUT"     // RFC 7231, 4.3.4
	MethodTrace   = "TRACE"   // RFC 7231, 4.3.8

)

HTTP methods were copied from net/http.

View Source
const (
	MIMETextXML               = "text/xml"
	MIMETextHTML              = "text/html"
	MIMETextPlain             = "text/plain"
	MIMEApplicationXML        = "application/xml"
	MIMEApplicationJSON       = "application/json"
	MIMEApplicationJavaScript = "application/javascript"
	MIMEApplicationForm       = "application/x-www-form-urlencoded"
	MIMEOctetStream           = "application/octet-stream"
	MIMEMultipartForm         = "multipart/form-data"

	MIMETextXMLCharsetUTF8               = "text/xml; charset=utf-8"
	MIMETextHTMLCharsetUTF8              = "text/html; charset=utf-8"
	MIMETextPlainCharsetUTF8             = "text/plain; charset=utf-8"
	MIMEApplicationXMLCharsetUTF8        = "application/xml; charset=utf-8"
	MIMEApplicationJSONCharsetUTF8       = "application/json; charset=utf-8"
	MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
)

MIME types that are commonly used

View Source
const (
	StatusContinue                      = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols            = 101 // RFC 7231, 6.2.2
	StatusProcessing                    = 102 // RFC 2518, 10.1
	StatusEarlyHints                    = 103 // RFC 8297
	StatusOK                            = 200 // RFC 7231, 6.3.1
	StatusCreated                       = 201 // RFC 7231, 6.3.2
	StatusAccepted                      = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInformation   = 203 // RFC 7231, 6.3.4
	StatusNoContent                     = 204 // RFC 7231, 6.3.5
	StatusResetContent                  = 205 // RFC 7231, 6.3.6
	StatusPartialContent                = 206 // RFC 7233, 4.1
	StatusMultiStatus                   = 207 // RFC 4918, 11.1
	StatusAlreadyReported               = 208 // RFC 5842, 7.1
	StatusIMUsed                        = 226 // RFC 3229, 10.4.1
	StatusMultipleChoices               = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently              = 301 // RFC 7231, 6.4.2
	StatusFound                         = 302 // RFC 7231, 6.4.3
	StatusSeeOther                      = 303 // RFC 7231, 6.4.4
	StatusNotModified                   = 304 // RFC 7232, 4.1
	StatusUseProxy                      = 305 // RFC 7231, 6.4.5
	StatusTemporaryRedirect             = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect             = 308 // RFC 7538, 3
	StatusBadRequest                    = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                  = 401 // RFC 7235, 3.1
	StatusPaymentRequired               = 402 // RFC 7231, 6.5.2
	StatusForbidden                     = 403 // RFC 7231, 6.5.3
	StatusNotFound                      = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed              = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                 = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired             = 407 // RFC 7235, 3.2
	StatusRequestTimeout                = 408 // RFC 7231, 6.5.7
	StatusConflict                      = 409 // RFC 7231, 6.5.8
	StatusGone                          = 410 // RFC 7231, 6.5.9
	StatusLengthRequired                = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed            = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge         = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong             = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType          = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable  = 416 // RFC 7233, 4.4
	StatusExpectationFailed             = 417 // RFC 7231, 6.5.14
	StatusTeapot                        = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest            = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity           = 422 // RFC 4918, 11.2
	StatusLocked                        = 423 // RFC 4918, 11.3
	StatusFailedDependency              = 424 // RFC 4918, 11.4
	StatusTooEarly                      = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired               = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired          = 428 // RFC 6585, 3
	StatusTooManyRequests               = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge   = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons    = 451 // RFC 7725, 3
	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes were copied from net/http.

View Source
const (
	HeaderAuthorization                   = "Authorization"
	HeaderProxyAuthenticate               = "Proxy-Authenticate"
	HeaderProxyAuthorization              = "Proxy-Authorization"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	HeaderAge                             = "Age"
	HeaderCacheControl                    = "Cache-Control"
	HeaderClearSiteData                   = "Clear-Site-Data"
	HeaderExpires                         = "Expires"
	HeaderPragma                          = "Pragma"
	HeaderWarning                         = "Warning"
	HeaderAcceptCH                        = "Accept-CH"
	HeaderAcceptCHLifetime                = "Accept-CH-Lifetime"
	HeaderContentDPR                      = "Content-DPR"
	HeaderDPR                             = "DPR"
	HeaderEarlyData                       = "Early-Data"
	HeaderSaveData                        = "Save-Data"
	HeaderViewportWidth                   = "Viewport-Width"
	HeaderWidth                           = "Width"
	HeaderETag                            = "ETag"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderLastModified                    = "Last-Modified"
	HeaderVary                            = "Vary"
	HeaderConnection                      = "Connection"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderAccept                          = "Accept"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderCookie                          = "Cookie"
	HeaderExpect                          = "Expect"
	HeaderMaxForwards                     = "Max-Forwards"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderOrigin                          = "Origin"
	HeaderTimingAllowOrigin               = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies   = "X-Permitted-Cross-Domain-Policies"
	HeaderDNT                             = "DNT"
	HeaderTk                              = "Tk"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentType                     = "Content-Type"
	HeaderForwarded                       = "Forwarded"
	HeaderVia                             = "Via"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedHost                  = "X-Forwarded-Host"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXForwardedProtocol              = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                   = "X-Forwarded-Ssl"
	HeaderXUrlScheme                      = "X-Url-Scheme"
	HeaderLocation                        = "Location"
	HeaderFrom                            = "From"
	HeaderHost                            = "Host"
	HeaderReferer                         = "Referer"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderUserAgent                       = "User-Agent"
	HeaderAllow                           = "Allow"
	HeaderServer                          = "Server"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderContentRange                    = "Content-Range"
	HeaderIfRange                         = "If-Range"
	HeaderRange                           = "Range"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderLastEventID                     = "Last-Event-ID"
	HeaderNEL                             = "NEL"
	HeaderPingFrom                        = "Ping-From"
	HeaderPingTo                          = "Ping-To"
	HeaderReportTo                        = "Report-To"
	HeaderTE                              = "TE"
	HeaderTrailer                         = "Trailer"
	HeaderTransferEncoding                = "Transfer-Encoding"
	HeaderSecWebSocketAccept              = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions          = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey                 = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol            = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion             = "Sec-WebSocket-Version"
	HeaderAcceptPatch                     = "Accept-Patch"
	HeaderAcceptPushPolicy                = "Accept-Push-Policy"
	HeaderAcceptSignature                 = "Accept-Signature"
	HeaderAltSvc                          = "Alt-Svc"
	HeaderDate                            = "Date"
	HeaderIndex                           = "Index"
	HeaderLargeAllocation                 = "Large-Allocation"
	HeaderLink                            = "Link"
	HeaderPushPolicy                      = "Push-Policy"
	HeaderRetryAfter                      = "Retry-After"
	HeaderServerTiming                    = "Server-Timing"
	HeaderSignature                       = "Signature"
	HeaderSignedHeaders                   = "Signed-Headers"
	HeaderSourceMap                       = "SourceMap"
	HeaderUpgrade                         = "Upgrade"
	HeaderXDNSPrefetchControl             = "X-DNS-Prefetch-Control"
	HeaderXPingback                       = "X-Pingback"
	HeaderXRequestID                      = "X-Request-ID"
	HeaderXRequestedWith                  = "X-Requested-With"
	HeaderXRobotsTag                      = "X-Robots-Tag"
	HeaderXUACompatible                   = "X-UA-Compatible"
)

HTTP Headers were copied from net/http.

View Source
const (
	DefaultDateFormat     = "2006-01-02"
	DefaultDateTimeFormat = "2006-01-02 15:04"
)

Revel's default date and time constants

Variables

View Source
var (
	ErrBadRequest                    = NewError(StatusBadRequest)                    // RFC 7231, 6.5.1
	ErrUnauthorized                  = NewError(StatusUnauthorized)                  // RFC 7235, 3.1
	ErrPaymentRequired               = NewError(StatusPaymentRequired)               // RFC 7231, 6.5.2
	ErrForbidden                     = NewError(StatusForbidden)                     // RFC 7231, 6.5.3
	ErrNotFound                      = NewError(StatusNotFound)                      // RFC 7231, 6.5.4
	ErrMethodNotAllowed              = NewError(StatusMethodNotAllowed)              // RFC 7231, 6.5.5
	ErrNotAcceptable                 = NewError(StatusNotAcceptable)                 // RFC 7231, 6.5.6
	ErrProxyAuthRequired             = NewError(StatusProxyAuthRequired)             // RFC 7235, 3.2
	ErrRequestTimeout                = NewError(StatusRequestTimeout)                // RFC 7231, 6.5.7
	ErrConflict                      = NewError(StatusConflict)                      // RFC 7231, 6.5.8
	ErrGone                          = NewError(StatusGone)                          // RFC 7231, 6.5.9
	ErrLengthRequired                = NewError(StatusLengthRequired)                // RFC 7231, 6.5.10
	ErrPreconditionFailed            = NewError(StatusPreconditionFailed)            // RFC 7232, 4.2
	ErrRequestEntityTooLarge         = NewError(StatusRequestEntityTooLarge)         // RFC 7231, 6.5.11
	ErrRequestURITooLong             = NewError(StatusRequestURITooLong)             // RFC 7231, 6.5.12
	ErrUnsupportedMediaType          = NewError(StatusUnsupportedMediaType)          // RFC 7231, 6.5.13
	ErrRequestedRangeNotSatisfiable  = NewError(StatusRequestedRangeNotSatisfiable)  // RFC 7233, 4.4
	ErrExpectationFailed             = NewError(StatusExpectationFailed)             // RFC 7231, 6.5.14
	ErrTeapot                        = NewError(StatusTeapot)                        // RFC 7168, 2.3.3
	ErrMisdirectedRequest            = NewError(StatusMisdirectedRequest)            // RFC 7540, 9.1.2
	ErrUnprocessableEntity           = NewError(StatusUnprocessableEntity)           // RFC 4918, 11.2
	ErrLocked                        = NewError(StatusLocked)                        // RFC 4918, 11.3
	ErrFailedDependency              = NewError(StatusFailedDependency)              // RFC 4918, 11.4
	ErrTooEarly                      = NewError(StatusTooEarly)                      // RFC 8470, 5.2.
	ErrUpgradeRequired               = NewError(StatusUpgradeRequired)               // RFC 7231, 6.5.15
	ErrPreconditionRequired          = NewError(StatusPreconditionRequired)          // RFC 6585, 3
	ErrTooManyRequests               = NewError(StatusTooManyRequests)               // RFC 6585, 4
	ErrRequestHeaderFieldsTooLarge   = NewError(StatusRequestHeaderFieldsTooLarge)   // RFC 6585, 5
	ErrUnavailableForLegalReasons    = NewError(StatusUnavailableForLegalReasons)    // RFC 7725, 3
	ErrInternalServerError           = NewError(StatusInternalServerError)           // RFC 7231, 6.6.1
	ErrNotImplemented                = NewError(StatusNotImplemented)                // RFC 7231, 6.6.2
	ErrBadGateway                    = NewError(StatusBadGateway)                    // RFC 7231, 6.6.3
	ErrServiceUnavailable            = NewError(StatusServiceUnavailable)            // RFC 7231, 6.6.4
	ErrGatewayTimeout                = NewError(StatusGatewayTimeout)                // RFC 7231, 6.6.5
	ErrHTTPVersionNotSupported       = NewError(StatusHTTPVersionNotSupported)       // RFC 7231, 6.6.6
	ErrVariantAlsoNegotiates         = NewError(StatusVariantAlsoNegotiates)         // RFC 2295, 8.1
	ErrInsufficientStorage           = NewError(StatusInsufficientStorage)           // RFC 4918, 11.5
	ErrLoopDetected                  = NewError(StatusLoopDetected)                  // RFC 5842, 7.2
	ErrNotExtended                   = NewError(StatusNotExtended)                   // RFC 2774, 7
	ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // RFC 6585, 6
)

Errors

View Source
var (
	// Log default global log interface
	Log log.Interface
)

Methods methods slice

Functions

func BytesToString

func BytesToString(b []byte) string

BytesToString returns a string pointer without allocation

func CopyBytes

func CopyBytes(b []byte) []byte

CopyBytes copies a slice to make it immutable

func CopyString

func CopyString(s string) string

CopyString copies a string to make it immutable

func EqualFold

func EqualFold(b, s string) (equals bool)

EqualFold the equivalent of strings.EqualFold

func EqualFoldBytes

func EqualFoldBytes(b, s []byte) (equals bool)

EqualFoldBytes the equivalent of bytes.EqualFold

func GetMIME

func GetMIME(extension string) (mime string)

GetMIME returns the content-type of a file extension

func GetTrimmedParam

func GetTrimmedParam(param string) string

GetTrimmedParam trims the ':' & '?' from a string

func Go

func Go(goroutine func())

Go starts a recoverable goroutine.

func GoWithRecover

func GoWithRecover(goroutine func(), customRecover func(err interface{}))

GoWithRecover starts a recoverable goroutine using given customRecover() function.

func LoadConfigFile

func LoadConfigFile(confFile string) map[string]interface{}

LoadConfigFile load yml config

func ReadFile

func ReadFile(path string, fs http.FileSystem) ([]byte, error)

ReadFile returns the raw content of a file

func RegisterModule

func RegisterModule(inst Module)

RegisterModule 注册模块

func SaveConfigFile

func SaveConfigFile(conf map[string]interface{}) error

func StatusMessage

func StatusMessage(status int) string

StatusMessage returns the correct message for the provided HTTP statuscode

func StringToBytes

func StringToBytes(s string) (bs []byte)

StringToBytes returns a byte pointer without allocation

func ToHandle

func ToHandle(src string) string

ToHandle 转换名称为handle

func ToLower

func ToLower(b string) string

ToLower is the equivalent of strings.ToLower

func ToLowerBytes

func ToLowerBytes(b []byte) []byte

ToLowerBytes is the equivalent of bytes.ToLower

func ToUpper

func ToUpper(b string) string

ToUpper is the equivalent of strings.ToUpper

func ToUpperBytes

func ToUpperBytes(b []byte) []byte

ToUpperBytes is the equivalent of bytes.ToUpper

func Trim

func Trim(s string, cutset byte) string

Trim is the equivalent of strings.Trim

func TrimBytes

func TrimBytes(b []byte, cutset byte) []byte

TrimBytes is the equivalent of bytes.Trim

func TrimLeft

func TrimLeft(s string, cutset byte) string

TrimLeft is the equivalent of strings.TrimLeft

func TrimLeftBytes

func TrimLeftBytes(b []byte, cutset byte) []byte

TrimLeftBytes is the equivalent of bytes.TrimLeft

func TrimRight

func TrimRight(s string, cutset byte) string

TrimRight is the equivalent of strings.TrimRight

func TrimRightBytes

func TrimRightBytes(b []byte, cutset byte) []byte

TrimRightBytes is the equivalent of bytes.TrimRight

func Walk

func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error

Walk walks the filesystem rooted at root, calling walkFn for each file or directory in the filesystem, including root. All errors that arise visiting files and directories are filtered by walkFn. The files are walked in lexical order.

Types

type Array

type Array []interface{}

Array 数组类型

func (Array) GormDataType

func (Array) GormDataType() string

GormDataType schema.Field DataType

func (*Array) Scan

func (d *Array) Scan(src interface{}) error

Scan 数据驱动接口

func (Array) String

func (d Array) String() []string

Strings 转换为 []string

func (Array) StringsJoin

func (d Array) StringsJoin(sp string) string

StringsJoin 链接为字符串

func (Array) Value

func (d Array) Value() (driver.Value, error)

Value 数据驱动接口

type Cookie struct {
	Name     string    `json:"name"`
	Value    string    `json:"value"`
	Path     string    `json:"path"`
	Domain   string    `json:"domain"`
	MaxAge   int       `json:"max_age"`
	Expires  time.Time `json:"expires"`
	Secure   bool      `json:"secure"`
	HTTPOnly bool      `json:"http_only"`
	SameSite string    `json:"same_site"`
}

Cookie data for c.Cookie

type Core

type Core struct {
	*Options
	*fasthttp.Server
	// contains filtered or unexported fields
}

Core cola core

func New

func New(opts ...interface{}) *Core

New Create cola web instance.

func (*Core) Add

func (c *Core) Add(method, path string, handlers ...Hand)

Add add some method.

func (*Core) Serve

func (c *Core) Serve(args ...interface{}) error

Serve start cola

addr 0.0.0.0:8080

8080
:8080

func (*Core) Static

func (c *Core) Static(prefix, root string, config ...Static) *Core

Static register a new route with path prefix to serve static files from the provided root directory.

func (*Core) Use

func (c *Core) Use(args ...interface{}) *Core

Use register a other plugin middware module TODO:

type Ctx

type Ctx struct {
	*Core // reference to *Core
	*fasthttp.RequestCtx
	// contains filtered or unexported fields
}

Ctx Extends fasthttp RequestCtx

func (*Ctx) Append

func (c *Ctx) Append(field string, values ...string)

Append the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value.

func (*Ctx) Body

func (c *Ctx) Body() []byte

Body contains the raw body submitted in a POST request. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Ctx) ClearCookie

func (c *Ctx) ClearCookie(key ...string)

ClearCookie expires a specific cookie by key on the client side. If no key is provided it expires all cookies that came with the request.

func (*Ctx) ClearCookies

func (c *Ctx) ClearCookies(key ...string)

ClearCookies clear cookie set default path /

if ClearCookie failed.

If no key is provided it expires all cookies that came with the request.

func (*Ctx) ContentType

func (c *Ctx) ContentType(extension string, charset ...string) *Ctx

ContentType sets the Content-Type HTTP header(map[string] helper line 525 ) to the MIME type specified by the file extension.

func (*Ctx) Cookie

func (c *Ctx) Cookie(cookie *Cookie)

Cookie sets a cookie by passing a cookie struct.

func (*Ctx) Cookies

func (c *Ctx) Cookies(key string, defaultValue ...string) string

Cookies is used for getting a cookie value by key. Defaults to the empty string "" if the cookie doesn't exist. If a default value is given, it will return that value if the cookie doesn't exist. The returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.

func (*Ctx) DelCookie

func (c *Ctx) DelCookie(k string, path ...string)

DelCookie delete cookie with path

func (*Ctx) FileBuf

func (c *Ctx) FileBuf(fh *multipart.FileHeader) ([]byte, error)

FileBuf Read request file

func (*Ctx) FormFile

func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error)

FormFile returns the first file by key from a MultipartForm.

func (*Ctx) FormValue

func (c *Ctx) FormValue(key string, defaultValue ...string) string

FormValue returns the first value by key from a MultipartForm. Defaults to the empty string "" if the form value doesn't exist. If a default value is given, it will return that value if the form value does not exist. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Ctx) Fresh

func (c *Ctx) Fresh() bool

Fresh returns true when the response is still “fresh” in the client's cache, otherwise false is returned to indicate that the client cache is now stale and the full response should be sent. When a client sends the Cache-Control: no-cache request header to indicate an end-to-end reload request, this module will return false to make handling these requests transparent. https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33

func (*Ctx) Get

func (c *Ctx) Get(key string, defaultValue ...string) string

Get returns the HTTP request header specified by field. Field names are case-insensitive Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Ctx) Hostname

func (c *Ctx) Hostname() string

Hostname contains the hostname derived from the Host HTTP header. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Ctx) IP

func (c *Ctx) IP() string

IP returns the remote IP address of the request.

func (*Ctx) JSON

func (c *Ctx) JSON(data interface{}) error

JSON converts any interface or string to JSON. Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value. This method also sets the content header to application/json.

func (*Ctx) JSONP

func (c *Ctx) JSONP(data interface{}, callback ...string) error

JSONP sends a JSON response with JSONP support. This method is identical to JSON, except that it opts-in to JSONP callback support. By default, the callback name is simply callback.

func (*Ctx) MultipartForm

func (c *Ctx) MultipartForm() (*multipart.Form, error)

MultipartForm parse form entries from binary. This returns a map[string][]string, so given a key the value will be a string slice.

func (*Ctx) Next

func (c *Ctx) Next()

Next method in the stack that match

func (*Ctx) OriginalURL

func (c *Ctx) OriginalURL() string

OriginalURL contains the original request URL. Returned value is only valid within the handler. Do not store any references.

func (*Ctx) Params

func (c *Ctx) Params(key string, defaultValue ...string) string

Params is used to get the route parameters. Defaults to empty string "" if the param doesn't exist. If a default value is given, it will return that value if the param doesn't exist. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.

func (*Ctx) Path

func (c *Ctx) Path(override ...string) string

Path returns the path part of the request URL. Optionally, you could override the path.

func (*Ctx) ReadBody

func (c *Ctx) ReadBody(out interface{}) error

ReadBody binds the request body to a struct. It supports decoding the following content types based on the Content-Type header: application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data If none of the content types above are matched, it will return a ErrUnprocessableEntity error

func (*Ctx) Render

func (c *Ctx) Render(f string, optionalBind ...interface{}) error

Render Render View Engine

func (*Ctx) RenderString

func (c *Ctx) RenderString(src string, optionalBind ...interface{}) (string, error)

RenderString Parse template string to string

e.g:

  ```go
  c.RenderString(`<div>Your price: {{ .price }}</div>`, map[string]interface{}{
	   "price": 12.5,
  })
  // or use vars
  c.Vars("price", 12.5)
  c.RenderString(`<div>Your price: {{ .price }}</div>`)
  ```

func (*Ctx) SaveFile

func (c *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error

SaveFile saves any multipart file to disk.

func (*Ctx) Send

func (c *Ctx) Send(body []byte) error

Send sets the HTTP response body without copying it. From this point onward the body argument must not be changed.

func (*Ctx) SendFile

func (c *Ctx) SendFile(file string, compress ...bool) error

SendFile transfers the file from the given path. The file is not compressed by default, enable this by passing a 'true' argument Sets the Content-Type response HTTP header field based on the filenames extension.

func (*Ctx) SendStatus

func (c *Ctx) SendStatus(status int) error

SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.

func (*Ctx) SendString

func (c *Ctx) SendString(body string) error

SendString sets the HTTP response body for string types. This means no type assertion, recommended for faster performance

func (*Ctx) Set

func (c *Ctx) Set(key string, val string)

Set sets the response's HTTP header field to the specified key, value.

func (*Ctx) Status

func (c *Ctx) Status(status int) *Ctx

Status sets the HTTP status for the response. This method is chainable.

func (*Ctx) ToJSON

func (c *Ctx) ToJSON(data interface{}, err error) error

ToJSON send json add status

func (*Ctx) Vars

func (c *Ctx) Vars(key string, value ...interface{}) (val interface{})

Vars makes it possible to pass interface{} values under string keys scoped to the request and therefore available to all following routes that match the request.

func (*Ctx) ViewTheme

func (c *Ctx) ViewTheme(theme string)

ViewTheme 使用模版风格

func (*Ctx) Write

func (c *Ctx) Write(p []byte) (int, error)

Write appends p into response body.

func (*Ctx) WriteString

func (c *Ctx) WriteString(s string) (int, error)

WriteString appends s to response body.

type DB

type DB = gorm.DB

func Conn

func Conn() *DB

func NewModel

func NewModel(dsn string, debug bool) (*DB, error)

func Where

func Where(whr *map[string]interface{}, db ...*DB) (*DB, int, int)

type Dict

type Dict map[string]interface{}

Dict map[string]interface{}

func (Dict) GormDataType

func (Dict) GormDataType() string

GormDataType schema.Field DataType

func (*Dict) Scan

func (d *Dict) Scan(src interface{}) error

Scan 数据驱动接口

func (Dict) Value

func (d Dict) Value() (driver.Value, error)

Value 数据驱动接口

type Engine

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

Engine Module engine

func NewEngine

func NewEngine(opts ...interface{}) *Engine

NewEngine 创建

func (*Engine) Core

func (e *Engine) Core() *Core

Core 返回 core对象

func (*Engine) Exit

func (e *Engine) Exit()

func (*Engine) Serve

func (e *Engine) Serve(port interface{}) error

Serve 启动服务 如果modules 定义 prefix 为 module. 这里则加载

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

Error represents an error that occurred while handling a request.

func NewError

func NewError(code int, message ...string) *Error

NewError creates a new Error instance with an optional message

func (*Error) Error

func (e *Error) Error() string

Error makes it compatible with the `error` interface.

type ErrorHandler

type ErrorHandler = func(*Ctx, error) error

ErrorHandler defines a function that will process all errors returned from any handlers in the stack

type Hand

type Hand func(*Ctx)

Hand Handler

type Handler

type Handler struct {
	Handlers map[string]struct{}
	// contains filtered or unexported fields
}

Handler Sample Handler

func (*Handler) Core

func (h *Handler) Core(c ...*Core) *Core

Core 设置或获得Core

func (*Handler) HandName

func (h *Handler) HandName() string

HandName 获得HandName

func (*Handler) Init

func (h *Handler) Init()

Init use once called

func (*Handler) Prefix

func (h *Handler) Prefix() string

Prefix set prefix path

func (*Handler) Preload

func (h *Handler) Preload(c *Ctx)

Preload 预处理使用 必须配置 Next结尾

func (*Handler) PushPath

func (h *Handler) PushPath(method, path string)

func (*Handler) SetHandName

func (h *Handler) SetHandName(name string)

SetHandName 设置Handler 名称

func (*Handler) SetPrefix

func (h *Handler) SetPrefix(prefix string)

SetPrefix set prefix path

type Map

type Map = map[string]interface{}

type Model

type Model struct {
	ID        uid.UID `gorm:"primaryKey"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt *gorm.DeletedAt `json:",omitempty"`
}

func (*Model) BeforeCreate

func (m *Model) BeforeCreate(tx *DB) error

type Module

type Module interface {
	Module() ModuleInfo
}

Module interface

type ModuleInfo

type ModuleInfo struct {
	ID  string
	New func() Module
}

ModuleInfo ModuleInfo

func GetModule

func GetModule(name string) (ModuleInfo, error)

GetModule 通过ID获得模块

获得后自己定义接口再调用某方法

func GetModules

func GetModules(scope string) []ModuleInfo

GetModules 获取指定开头的模块

type Options

type Options struct {
	Prefork bool

	LogPath string

	Config interface{}

	UseCheck bool

	Layout string

	// Debug Default false
	Debug bool

	Views Views

	// Case sensitive routing, all to lowercase
	CaseSensitive bool

	// Nginx Caddy some proxy header X-Real-IP  X-Forwarded-For
	// Default: ""
	ProxyHeader string
	// Server: cola
	ServerName string
	// Default: false
	ETag bool `json:"etag"`
	// Max body size that the server accepts.
	// -1 will decline any body size
	//
	// Default: 4 * 1024 * 1024
	BodyLimit int `json:"body_limit"`
	// Maximum number of concurrent connections.
	//
	// Default: 256 * 1024
	Concurrency int `json:"concurrency"`

	// When set to true, converts all encoded characters in the route back
	// before setting the path for the context, so that the routing,
	// the returning of the current url from the context `ctx.Path()`
	// and the paramters `ctx.Params(%key%)` with decoded characters will work
	//
	// Default: false
	UnescapePath bool `json:"unescape_path"`

	// The amount of time allowed to read the full request including body.
	// It is reset after the request handler has returned.
	// The connection's read deadline is reset when the connection opens.
	//
	// Default: unlimited
	ReadTimeout time.Duration `json:"read_timeout"`

	// The maximum duration before timing out writes of the response.
	// It is reset after the request handler has returned.
	//
	// Default: unlimited
	WriteTimeout time.Duration `json:"write_timeout"`

	// The maximum amount of time to wait for the next request when keep-alive is enabled.
	// If IdleTimeout is zero, the value of ReadTimeout is used.
	//
	// Default: unlimited
	IdleTimeout time.Duration `json:"idle_timeout"`

	// Per-connection buffer size for requests' reading.
	// This also limits the maximum header size.
	// Increase this buffer if your clients send multi-KB RequestURIs
	// and/or multi-KB headers (for example, BIG cookies).
	//
	// Default: 4096
	ReadBufferSize int `json:"read_buffer_size"`

	// Per-connection buffer size for responses' writing.
	//
	// Default: 4096
	WriteBufferSize int `json:"write_buffer_size"`

	// CompressedFileSuffix adds suffix to the original file name and
	// tries saving the resulting compressed file under the new file name.
	//
	// Default: ".gz"
	CompressedFileSuffix string `json:"compressed_file_suffix"`
	// contains filtered or unexported fields
}

Options Global options

type Pages

type Pages struct {
	P, L  int
	Total int64
	Data  interface{}
}

type Route

type Route struct {
	Handlers []Hand
	Params   []string
	Path     string
	Method   string
	// contains filtered or unexported fields
}

Route route

type Static

type Static struct {
	// When set to true, the server tries minimizing CPU usage by caching compressed files.
	// Optional. Default value false
	Compress bool `json:"compress"`

	// When set to true, enables byte range requests.
	// Optional. Default value false
	ByteRange bool `json:"byte_range"`

	// When set to true, enables directory browsing.
	// Optional. Default value false.
	Browse bool `json:"browse"`

	// The name of the index file for serving a directory.
	// Optional. Default value "index.html".
	Index string `json:"index"`

	// Expiration duration for inactive file handlers.
	// Use a negative time.Duration to disable it.
	//
	// Optional. Default value 10 * time.Second.
	CacheDuration time.Duration `json:"cache_duration"`

	// The value for the Cache-Control HTTP-header
	// that is set on the file response. MaxAge is defined in seconds.
	//
	// Optional. Default value 0.
	MaxAge int `json:"max_age"`
}

Static defines configuration options when defining static assets.

type StringOrNil

type StringOrNil string

空字符串 存入数据库 存 NULL ,这样会跳过数据库唯一索引的检查

func (*StringOrNil) Scan

func (s *StringOrNil) Scan(src interface{}) error

implements sql.Scanner, will be invoked automatically when read from the db

func (StringOrNil) String

func (s StringOrNil) String() string

func (StringOrNil) Value

func (s StringOrNil) Value() (driver.Value, error)

implements driver.Valuer, will be invoked automatically when written to the db

type ViewEngine

type ViewEngine struct {

	// templates
	Templates *template.Template
	// contains filtered or unexported fields
}

ViewEngine html template engine

func NewView

func NewView(directory, ext string, args ...interface{}) *ViewEngine

NewView Create view engine args:

string theme
bool debug
map[string]interface{} helper fn
http.FileSystem file system

func (*ViewEngine) AddFunc

func (ve *ViewEngine) AddFunc(name string, fn interface{}) *ViewEngine

AddFunc add helper func

func (*ViewEngine) Delims

func (ve *ViewEngine) Delims(l, r string) *ViewEngine

Delims sets the action delimiters to the specified strings Default: {{ var }}

func (*ViewEngine) DoTheme

func (ve *ViewEngine) DoTheme(theme string)

DoTheme 调用已装载的主题

func (*ViewEngine) Execute

func (ve *ViewEngine) Execute(out io.Writer, tpl string, binding interface{}, layout ...string) error

func (*ViewEngine) ExecuteWriter

func (ve *ViewEngine) ExecuteWriter(out io.Writer, tpl string, binding interface{}, layout ...string) error

ExecuteWriter execute render

func (*ViewEngine) Layout

func (ve *ViewEngine) Layout(layout string) *ViewEngine

Layout set layout file Layout

func (*ViewEngine) Load

func (ve *ViewEngine) Load() error

Load load tmpl file

func (*ViewEngine) Reload

func (ve *ViewEngine) Reload(reload bool) *ViewEngine

Reload if set to true the templates are reloading on each render, use it when you're in development and you don't want to restart

func (*ViewEngine) Theme

func (ve *ViewEngine) Theme(theme string)

Theme sets theme

type Views

type Views interface {
	Theme(string)
	DoTheme(string)
	Load() error
	ExecuteWriter(io.Writer, string, interface{}, ...string) error
	AddFunc(name string, fn interface{}) *ViewEngine
}

Views view interface

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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