gf

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

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

Go to latest
Published: Jun 9, 2017 License: MIT Imports: 41 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Golang simple framework

Start using it

  1. Download and install it:
$ go get github.com/goframework/gf
  1. Create server.cfg
Server.EnableHttp		= 1
Server.Addr 			= :8016
Server.ReadTimeout		= 120
Server.WriteTimeout		= 120
Server.MaxHeaderBytes	= 65536
Server.StaticDir		= ./static
Server.StaticWebPath	= /static
Server.ViewDir			= ./view
Server.CookieSecret		= Your cookie secret (any string)
Server.SessionStoreDir	= ./session_store

Server.EnableGzip		= 1
Server.ForceHttps		= 0

Server.EnableHttps		= 0
#IF Server.EnableHttps = 1, set bellow:
#Server.AddrHttps 		= :44316
#Server.CertFile		= fullchain.pem
#Server.KeyFile			= key.pem
#Create cert.pem and key.pem by:
#  openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout key.pem -out cert.pem

  1. Create view/helloworld.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world from GF</title>
</head>
<body>
<p>Hello {{.name}} !</p>
</body>
</html>
  1. Create main.go
package main

import (
  "github.com/goframework/gf"
)

func main() {
  gf.HandleGet("/", func(ctx *gf.Context) {
  	ctx.View = "helloworld.html"
  })
  
  gf.HandleGet("/{name}", func(ctx *gf.Context) {
  	ctx.ViewData["name"] = ctx.RouteVars["name"]
  	ctx.View = "helloworld.html"
  })
  
  gf.Run()
}
  1. Build, run, then open browser and go to address:

http://localhost:8016

http://localhost:8016/your_name

Documentation

Index

Constants

View Source
const (
	CFG_KEY_SERVER_STATIC_DIR          = "Server.StaticDir"
	CFG_KEY_SERVER_STATIC_MAX_CACHE_FZ = "Server.StaticMaxCacheFileSize"
	CFG_KEY_SERVER_VIEW_DIR            = "Server.ViewDir"
	CFG_KEY_SERVER_STATIC_WEB_PATH     = "Server.StaticWebPath"
	CFG_KEY_SERVER_ADDR                = "Server.Addr"
	CFG_KEY_SERVER_READ_TIMEOUT        = "Server.ReadTimeout"
	CFG_KEY_SERVER_WRITE_TIMEOUT       = "Server.WriteTimeout"
	CFG_KEY_SERVER_MAX_HEADER_BYTES    = "Server.MaxHeaderBytes"
	CFG_KEY_SERVER_MAX_CONTENT_LENGTH  = "Server.MaxContentLength"
	CFG_KEY_COOKIE_SECRET              = "Server.CookieSecret"
	CFG_KEY_SESSION_STORE_DIR          = "Server.SessionStoreDir"
	CFG_KEY_CACHE_STORE_DIR            = "Server.CacheStoreDir"
	CFG_KEY_SERVER_ENABLE_HTTP         = "Server.EnableHttp"
	CFG_KEY_SERVER_ENABLE_HTTPS        = "Server.EnableHttps"
	CFG_KEY_SERVER_ADDR_HTTPS          = "Server.AddrHttps"
	CFG_KEY_SERVER_CERT_FILE           = "Server.CertFile"
	CFG_KEY_SERVER_KEY_FILE            = "Server.KeyFile"
	CFG_KEY_SERVER_ENABLE_GZIP         = "Server.EnableGzip"
	CFG_KEY_SERVER_ENABLE_MINIFY       = "Server.EnableMinify"
	CFG_KEY_SERVER_FORCE_HTTPS         = "Server.ForceHttps"
	CFG_KEY_SERVER_ENABLE_CSRF_PROTECT = "Server.EnableCsrfProtect"
	CFG_KEY_SERVER_IP_REQUEST_LIMIT    = "Server.IPRequestLimit" //Limit request per IP per second (except static file requests), over limit will be reject with "429 Too Many Requests"
	CFG_KEY_DATABASE_DRIVER            = "Database.Driver"
	CFG_KEY_DATABASE_HOST              = "Database.Host"
	CFG_KEY_DATABASE_PORT              = "Database.Port"
	CFG_KEY_DATABASE_SERVER            = "Database.Server"
	CFG_KEY_DATABASE_USER              = "Database.User"
	CFG_KEY_DATABASE_PWD               = "Database.Pwd"
	CFG_KEY_DATABASE_SCHEMA            = "Database.DatabaseName"
)
View Source
const (
	DEFAULT_HTTP_PORT                  = ":80"
	DEFAULT_HTTPS_PORT                 = ":443"
	DEFAULT_SERVER_CONFIG_FILE         = "./server.cfg"
	DEFAULT_SERVER_STATIC_DIR          = "./static"
	DEFAULT_SERVER_STATIC_MAX_CACHE_FZ = 512 * 1024 //512KB
	DEFAULT_SERVER_STATIC_WEB_PATH     = "/static"
	DEFAULT_SERVER_VIEW_DIR            = "./view"
	DEFAULT_SERVER_ADDR                = ":8026"
	DEFAULT_SERVER_ADDR_HTTPS          = ":44326"
	DEFAULT_SERVER_CERT_FILE           = "./cert.pem"
	DEFAULT_SERVER_KEY_FILE            = "./key.pem"
	DEFAULT_SERVER_READ_TIMEOUT        = 120              //120s
	DEFAULT_SERVER_WRITE_TIMEOUT       = 120              //120s
	DEFAULT_SERVER_MAX_HEADER_BYTES    = 16 * 1024        //16KB
	DEFAULT_SERVER_MAX_CONTENT_LENGTH  = 10 * 1024 * 1024 //10MB
	DEFAULT_SERVER_ENABLE_GZIP         = true
	DEFAULT_SERVER_ENABLE_MINIFY       = false
	DEFAULT_SERVER_FORCE_HTTPS         = false
	DEFAULT_SERVER_ENABLE_CSRF_PROTECT = true
	DEFAULT_SERVER_IP_REQUEST_LIMIT    = 100 //100 request per second per IP
	DEFAULT_COOKIE_SECRET              = "COOKIE_SECRET"
	DEFAULT_SESSION_STORE_DIR          = "./session_store"
	DEFAULT_CACHE_STORE_DIR            = "./cache_store"
	DEFAULT_SERVER_ENABLE_HTTP         = true
	DEFAULT_SERVER_ENABLE_HTTPS        = false
	DEFAULT_SERVER_ENABLE_HTTP2        = true
)
View Source
const (
	SERVER_SESSION_ID         = "session_id"
	SERVER_SESSION_MAX_LENGTH = 128 * 1024 //128KB
	SERVER_SESSION_KEEP_DAY   = 7          // 1 week

	METHOD_GET  = "GET"
	METHOD_POST = "POST"
)
View Source
const (
	MAX_URL_PATH_LENGTH    = 2048
	MAX_HTTP_METHOD_LENGTH = 7 //method OPTIONS
)
View Source
const FORM_TAG = "form"
View Source
const MAX_MULTIPART_MEMORY = 1024 * 1024 * 5

Variables

View Source
var SqlScanStruct = db.SqlScanStruct

deprecated, use db.SqlScanStruct instead

Functions

func Filter

func Filter(pattern string, f func(*Context))

Filter add a filter to request handler, - pattern used wildcard matching with ? and * - all request methods (GET/POST/PUT/HEAD/...) will be applied

func Handle404

func Handle404(f func(http.ResponseWriter, *http.Request))

func HandleGet

func HandleGet(pattern string, f func(*Context))

func HandleGetPost

func HandleGetPost(pattern string, f func(*Context))

func HandleMethod

func HandleMethod(pattern string, f func(*Context), method string)

func HandlePost

func HandlePost(pattern string, f func(*Context))

func ParseTemplateFiles

func ParseTemplateFiles(templateFunc map[string]interface{}, filenames ...string) (*template.Template, error)

func Run

func Run()

Start web server

func Set404View

func Set404View(viewPath string)

Types

type Context

type Context struct {
	Config         *cfg.Cfg
	RouteVars      map[string]ext.Var
	FinishFilter   bool
	RedirectPath   string
	RedirectStatus int
	Session        *sessions.Session
	ViewBases      []string
	View           string
	ViewData       map[string]interface{}
	JsonResponse   interface{}
	UrlPath        string
	Method         string
	IsGetMethod    bool
	IsPostMethod   bool
	IsUsingTSL     bool
	Form           Form
	Host           string

	TemplateFunc map[string]interface{}
	DB           *sql.DB
	// contains filtered or unexported fields
}

func (*Context) AddResponseHeader

func (ctx *Context) AddResponseHeader(key string, value string)

func (*Context) Cleanup

func (ctx *Context) Cleanup()

func (*Context) ClearSession

func (ctx *Context) ClearSession()

func (*Context) DeleteCookie

func (ctx *Context) DeleteCookie(key string)

Unset cookie

func (*Context) Get

func (ctx *Context) Get(key string) (interface{}, bool)

func (*Context) GetBool

func (ctx *Context) GetBool(key string) (bool, bool)

func (*Context) GetBrowserAgent

func (ctx *Context) GetBrowserAgent() string

func (*Context) GetCookie

func (ctx *Context) GetCookie(key string) string

Get cookie

func (*Context) GetInt

func (ctx *Context) GetInt(key string) (int, bool)

func (*Context) GetRequestForwardedIP

func (ctx *Context) GetRequestForwardedIP() string

func (*Context) GetRequestIP

func (ctx *Context) GetRequestIP() string

func (*Context) GetSessionFlash

func (ctx *Context) GetSessionFlash(key string) interface{}

func (*Context) GetString

func (ctx *Context) GetString(key string) (string, bool)

func (*Context) GetUploadFile

func (ctx *Context) GetUploadFile(inputName string) (*FormFile, error)

func (*Context) LoadCache

func (ctx *Context) LoadCache(key string, object interface{}) error

func (*Context) NewSession

func (ctx *Context) NewSession()

func (*Context) Redirect

func (ctx *Context) Redirect(path string)

func (*Context) RedirectPermanently

func (ctx *Context) RedirectPermanently(path string)

func (*Context) SaveCache

func (ctx *Context) SaveCache(key string, object interface{}, secondTimeout int) error

func (*Context) ServeStaticFile

func (ctx *Context) ServeStaticFile(filePath string, isAttachment bool)

func (*Context) Set

func (ctx *Context) Set(key string, value interface{})

func (*Context) SetCookie

func (ctx *Context) SetCookie(key string, value string)

Set temporary cookie

func (*Context) SetPersistentCookie

func (ctx *Context) SetPersistentCookie(key string, value string, duration time.Duration)

Set persistent cookie

func (*Context) SetSessionFlash

func (ctx *Context) SetSessionFlash(key string, value interface{})

func (*Context) Write

func (ctx *Context) Write(data []byte) (int, error)

func (*Context) WriteHttpStatus

func (ctx *Context) WriteHttpStatus(httpStatus int)

func (*Context) WriteS

func (ctx *Context) WriteS(output string)

func (*Context) Writef

func (ctx *Context) Writef(format string, content ...interface{})

type Form

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

func (*Form) Array

func (this *Form) Array(key string) []string

func (*Form) ArrayNoEscape

func (this *Form) ArrayNoEscape(key string) []string

func (*Form) Bool

func (this *Form) Bool(key string) bool

func (*Form) Exist

func (this *Form) Exist(key string) bool

func (*Form) File

func (this *Form) File(key string) *FormFile

func (*Form) Float32

func (this *Form) Float32(key string) float32

func (*Form) Float64

func (this *Form) Float64(key string) float64

func (*Form) Int

func (this *Form) Int(key string) int

func (*Form) Int32

func (this *Form) Int32(key string) int32

func (*Form) Int64

func (this *Form) Int64(key string) int64

func (*Form) IsArray

func (this *Form) IsArray(key string) bool

func (*Form) ReadStruct

func (this *Form) ReadStruct(obj interface{})

Read form values and set to a struct Ex:

Call: ctx.Form.ReadStruct(&formABCVar)
Struct define:
   type FormABC struct {
         FieldA int `form:"this_is_a"`	// read from input name="this_is_a"
         FieldB float `this_is_b` 		// read from input name="this_is_b"
         FieldC string 					// read from input name="FieldC"
         privateField string				// will not read this field
         ArrayVar [] `list_abc`			// read string array from input name="list_abc"
    }

func (*Form) String

func (this *Form) String(key string) string

func (*Form) StringNoEscape

func (this *Form) StringNoEscape(key string) string

type FormFile

type FormFile struct {
	FileName string
	// contains filtered or unexported fields
}

func (*FormFile) Close

func (f *FormFile) Close() error

func (*FormFile) Read

func (f *FormFile) Read(p []byte) (n int, err error)

type NullCloseWriter

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

func (*NullCloseWriter) Close

func (w *NullCloseWriter) Close() error

func (*NullCloseWriter) Write

func (ncw *NullCloseWriter) Write(p []byte) (n int, err error)

Directories

Path Synopsis
Package context stores values shared during a request lifetime.
Package context stores values shared during a request lifetime.
Package csrf (gorilla/csrf) provides Cross Site Request Forgery (CSRF) prevention middleware for Go web applications & services.
Package csrf (gorilla/csrf) provides Cross Site Request Forgery (CSRF) prevention middleware for Go web applications & services.
html
template
Package template (gf/html/template) implements data-driven templates for generating HTML output safe against code injection.
Package template (gf/html/template) implements data-driven templates for generating HTML output safe against code injection.
Package gorilla/securecookie encodes and decodes authenticated and optionally encrypted cookie values.
Package gorilla/securecookie encodes and decodes authenticated and optionally encrypted cookie values.
Package gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.
Package gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.
text
template
Package template implements data-driven templates for generating textual output.
Package template implements data-driven templates for generating textual output.
template/parse
Package parse builds parse trees for templates as defined by gf/text/template and gf/html/template.
Package parse builds parse trees for templates as defined by gf/text/template and gf/html/template.

Jump to

Keyboard shortcuts

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