add buildin function 'concat' for gview

This commit is contained in:
John
2020-01-05 19:55:17 +08:00
parent 506552c3a9
commit bec9f5a847
40 changed files with 49 additions and 1108 deletions

View File

@ -1,3 +0,0 @@
package article
// Fill with you ideas below.

View File

@ -1,68 +0,0 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package article
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/os/gtime"
)
// Entity is the golang structure for table gf_article.
type Entity struct {
Id int `orm:"id,primary" json:"id"` //
CatId int `orm:"cat_id" json:"cat_id"` // 分类ID
Uid int `orm:"uid" json:"uid"` // 用户ID
Title string `orm:"title" json:"title"` // 标题
Content string `orm:"content" json:"content"` // 内容
Order int `orm:"order" json:"order"` // 排序
Brief string `orm:"brief" json:"brief"` // 摘要
Thumb string `orm:"thumb" json:"thumb"` // 缩略图
Tags string `orm:"tags" json:"tags"` // 标签
Referer string `orm:"referer" json:"referer"` // 内容来源
Status int `orm:"status" json:"status"` // 状态\n0: 禁用\n1: 正常
CreateTime *gtime.Time `orm:"create_time" json:"create_time"` // 创建时间
UpdateTime *gtime.Time `orm:"update_time" json:"update_time"` // 修改时间
}
// Article is alias of Entity, which some developers say they just want.
type Article = Entity
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (r *Entity) OmitEmpty() *arModel {
return Model.Data(r).OmitEmpty()
}
// Inserts does "INSERT...INTO..." statement for inserting current object into table.
func (r *Entity) Insert() (result sql.Result, err error) {
return Model.Data(r).Insert()
}
// Replace does "REPLACE...INTO..." statement for inserting current object into table.
// If there's already another same record in the table (it checks using primary key or unique index),
// it deletes it and insert this one.
func (r *Entity) Replace() (result sql.Result, err error) {
return Model.Data(r).Replace()
}
// Save does "INSERT...INTO..." statement for inserting/updating current object into table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Save() (result sql.Result, err error) {
return Model.Data(r).Save()
}
// Update does "UPDATE...WHERE..." statement for updating current object from table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Update() (result sql.Result, err error) {
return Model.Data(r).Where(gdb.GetWhereConditionOfStruct(r)).Update()
}
// Delete does "DELETE FROM...WHERE..." statement for deleting current object from table.
func (r *Entity) Delete() (result sql.Result, err error) {
return Model.Where(gdb.GetWhereConditionOfStruct(r)).Delete()
}

View File

@ -1,362 +0,0 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package article
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/frame/g"
"time"
)
// arModel is a active record design model for table gf_article operations.
type arModel struct {
M *gdb.Model
}
var (
// Table is the table name of gf_article.
Table = "gf_article"
// Model is the model object of gf_article.
Model = &arModel{g.DB("default").Table(Table).Safe()}
)
// FindOne is a convenience method for Model.FindOne.
// See Model.FindOne.
func FindOne(where ...interface{}) (*Entity, error) {
return Model.FindOne(where...)
}
// FindAll is a convenience method for Model.FindAll.
// See Model.FindAll.
func FindAll(where ...interface{}) ([]*Entity, error) {
return Model.FindAll(where...)
}
// FindValue is a convenience method for Model.FindValue.
// See Model.FindValue.
func FindValue(fieldsAndWhere ...interface{}) (gdb.Value, error) {
return Model.FindValue(fieldsAndWhere...)
}
// FindCount is a convenience method for Model.FindCount.
// See Model.FindCount.
func FindCount(where ...interface{}) (int, error) {
return Model.FindCount(where...)
}
// Insert is a convenience method for Model.Insert.
func Insert(data ...interface{}) (result sql.Result, err error) {
return Model.Insert(data...)
}
// Replace is a convenience method for Model.Replace.
func Replace(data ...interface{}) (result sql.Result, err error) {
return Model.Replace(data...)
}
// Save is a convenience method for Model.Save.
func Save(data ...interface{}) (result sql.Result, err error) {
return Model.Save(data...)
}
// Update is a convenience method for Model.Update.
func Update(dataAndWhere ...interface{}) (result sql.Result, err error) {
return Model.Update(dataAndWhere...)
}
// Delete is a convenience method for Model.Delete.
func Delete(where ...interface{}) (result sql.Result, err error) {
return Model.Delete(where...)
}
// TX sets the transaction for current operation.
func (m *arModel) TX(tx *gdb.TX) *arModel {
return &arModel{m.M.TX(tx)}
}
// Master marks the following operation on master node.
func (m *arModel) Master() *arModel {
return &arModel{m.M.Master()}
}
// Slave marks the following operation on slave node.
// Note that it makes sense only if there's any slave node configured.
func (m *arModel) Slave() *arModel {
return &arModel{m.M.Slave()}
}
// LeftJoin does "LEFT JOIN ... ON ..." statement on the model.
func (m *arModel) LeftJoin(joinTable string, on string) *arModel {
return &arModel{m.M.LeftJoin(joinTable, on)}
}
// RightJoin does "RIGHT JOIN ... ON ..." statement on the model.
func (m *arModel) RightJoin(joinTable string, on string) *arModel {
return &arModel{m.M.RightJoin(joinTable, on)}
}
// InnerJoin does "INNER JOIN ... ON ..." statement on the model.
func (m *arModel) InnerJoin(joinTable string, on string) *arModel {
return &arModel{m.M.InnerJoin(joinTable, on)}
}
// Fields sets the operation fields of the model, multiple fields joined using char ','.
func (m *arModel) Fields(fields string) *arModel {
return &arModel{m.M.Fields(fields)}
}
// FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.
func (m *arModel) FieldsEx(fields string) *arModel {
return &arModel{m.M.FieldsEx(fields)}
}
// Option sets the extra operation option for the model.
func (m *arModel) Option(option int) *arModel {
return &arModel{m.M.Option(option)}
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (m *arModel) OmitEmpty() *arModel {
return &arModel{m.M.OmitEmpty()}
}
// Filter marks filtering the fields which does not exist in the fields of the operated table.
func (m *arModel) Filter() *arModel {
return &arModel{m.M.Filter()}
}
// Where sets the condition statement for the model. The parameter <where> can be type of
// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times,
// multiple conditions will be joined into where statement using "AND".
// Eg:
// Where("uid=10000")
// Where("uid", 10000)
// Where("money>? AND name like ?", 99999, "vip_%")
// Where("uid", 1).Where("name", "john")
// Where("status IN (?)", g.Slice{1,2,3})
// Where("age IN(?,?)", 18, 50)
// Where(User{ Id : 1, UserName : "john"})
func (m *arModel) Where(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Where(where, args...)}
}
// And adds "AND" condition to the where statement.
func (m *arModel) And(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.And(where, args...)}
}
// Or adds "OR" condition to the where statement.
func (m *arModel) Or(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Or(where, args...)}
}
// Group sets the "GROUP BY" statement for the model.
func (m *arModel) Group(groupBy string) *arModel {
return &arModel{m.M.Group(groupBy)}
}
// Order sets the "ORDER BY" statement for the model.
func (m *arModel) Order(orderBy string) *arModel {
return &arModel{m.M.Order(orderBy)}
}
// Limit sets the "LIMIT" statement for the model.
// The parameter <limit> can be either one or two number, if passed two number is passed,
// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]"
// statement.
func (m *arModel) Limit(limit ...int) *arModel {
return &arModel{m.M.Limit(limit...)}
}
// Offset sets the "OFFSET" statement for the model.
// It only makes sense for some databases like SQLServer, PostgreSQL, etc.
func (m *arModel) Offset(offset int) *arModel {
return &arModel{m.M.Offset(offset)}
}
// Page sets the paging number for the model.
// The parameter <page> is started from 1 for paging.
// Note that, it differs that the Limit function start from 0 for "LIMIT" statement.
func (m *arModel) Page(page, limit int) *arModel {
return &arModel{m.M.Page(page, limit)}
}
// Batch sets the batch operation number for the model.
func (m *arModel) Batch(batch int) *arModel {
return &arModel{m.M.Batch(batch)}
}
// Cache sets the cache feature for the model. It caches the result of the sql, which means
// if there's another same sql request, it just reads and returns the result from cache, it
// but not committed and executed into the database.
//
// If the parameter <duration> < 0, which means it clear the cache with given <name>.
// If the parameter <duration> = 0, which means it never expires.
// If the parameter <duration> > 0, which means it expires after <duration>.
//
// The optional parameter <name> is used to bind a name to the cache, which means you can later
// control the cache like changing the <duration> or clearing the cache with specified <name>.
//
// Note that, the cache feature is disabled if the model is operating on a transaction.
func (m *arModel) Cache(expire time.Duration, name ...string) *arModel {
return &arModel{m.M.Cache(expire, name...)}
}
// Data sets the operation data for the model.
// The parameter <data> can be type of string/map/gmap/slice/struct/*struct, etc.
// Eg:
// Data("uid=10000")
// Data("uid", 10000)
// Data(g.Map{"uid": 10000, "name":"john"})
// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
func (m *arModel) Data(data ...interface{}) *arModel {
return &arModel{m.M.Data(data...)}
}
// Insert does "INSERT INTO ..." statement for the model.
// The optional parameter <data> is the same as the parameter of Model.Data function,
// see Model.Data.
func (m *arModel) Insert(data ...interface{}) (result sql.Result, err error) {
return m.M.Insert(data...)
}
// Replace does "REPLACE INTO ..." statement for the model.
// The optional parameter <data> is the same as the parameter of Model.Data function,
// see Model.Data.
func (m *arModel) Replace(data ...interface{}) (result sql.Result, err error) {
return m.M.Replace(data...)
}
// Save does "INSERT INTO ... ON DUPLICATE KEY UPDATE..." statement for the model.
// It updates the record if there's primary or unique index in the saving data,
// or else it inserts a new record into the table.
//
// The optional parameter <data> is the same as the parameter of Model.Data function,
// see Model.Data.
func (m *arModel) Save(data ...interface{}) (result sql.Result, err error) {
return m.M.Save(data...)
}
// Update does "UPDATE ... " statement for the model.
//
// If the optional parameter <dataAndWhere> is given, the dataAndWhere[0] is the updated
// data field, and dataAndWhere[1:] is treated as where condition fields.
// Also see Model.Data and Model.Where functions.
func (m *arModel) Update(dataAndWhere ...interface{}) (result sql.Result, err error) {
return m.M.Update(dataAndWhere...)
}
// Delete does "DELETE FROM ... " statement for the model.
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) Delete(where ...interface{}) (result sql.Result, err error) {
return m.M.Delete(where...)
}
// Count does "SELECT COUNT(x) FROM ..." statement for the model.
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) Count(where ...interface{}) (int, error) {
return m.M.Count(where...)
}
// All does "SELECT FROM ..." statement for the model.
// It retrieves the records from table and returns the result as []*Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) All(where ...interface{}) ([]*Entity, error) {
all, err := m.M.All(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// One retrieves one record from table and returns the result as *Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) One(where ...interface{}) (*Entity, error) {
one, err := m.M.One(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// Value retrieves a specified record value from table and returns the result as interface type.
// It returns nil if there's no record found with the given conditions from table.
//
// If the optional parameter <fieldsAndWhere> is given, the fieldsAndWhere[0] is the selected fields
// and fieldsAndWhere[1:] is treated as where condition fields.
// Also see Model.Fields and Model.Where functions.
func (m *arModel) Value(fieldsAndWhere ...interface{}) (gdb.Value, error) {
return m.M.Value(fieldsAndWhere...)
}
// FindOne retrieves and returns a single Record by Model.WherePri and Model.One.
// Also see Model.WherePri and Model.One.
func (m *arModel) FindOne(where ...interface{}) (*Entity, error) {
one, err := m.M.FindOne(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindAll retrieves and returns Result by by Model.WherePri and Model.All.
// Also see Model.WherePri and Model.All.
func (m *arModel) FindAll(where ...interface{}) ([]*Entity, error) {
all, err := m.M.FindAll(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// FindValue retrieves and returns single field value by Model.WherePri and Model.Value.
// Also see Model.WherePri and Model.Value.
func (m *arModel) FindValue(fieldsAndWhere ...interface{}) (gdb.Value, error) {
return m.M.FindValue(fieldsAndWhere...)
}
// FindCount retrieves and returns the record number by Model.WherePri and Model.Count.
// Also see Model.WherePri and Model.Count.
func (m *arModel) FindCount(where ...interface{}) (int, error) {
return m.M.FindCount(where...)
}
// Chunk iterates the table with given size and callback function.
func (m *arModel) Chunk(limit int, callback func(entities []*Entity, err error) bool) {
m.M.Chunk(limit, func(result gdb.Result, err error) bool {
var entities []*Entity
err = result.Structs(&entities)
if err == sql.ErrNoRows {
return false
}
return callback(entities, err)
})
}

View File

@ -1,33 +0,0 @@
{
"viewpath" : "/home/www/templates/",
"database" : {
"default" : [
{
"host" : "127.0.0.1",
"port" : "3306",
"user" : "root",
"pass" : "123456",
"name" : "test",
"type" : "mysql",
"role" : "master",
"charset" : "utf8",
"priority" : "1"
},
{
"host" : "127.0.0.1",
"port" : "3306",
"user" : "root",
"pass" : "123456",
"name" : "test",
"type" : "mysql",
"role" : "master",
"charset" : "utf8",
"priority" : "1"
}
]
},
"redis" : {
"disk" : "127.0.0.1:6379,0",
"cache" : "127.0.0.1:6379,1"
}
}

View File

@ -1,11 +0,0 @@
viewpath = "/home/www/templates"
# MySQL数据库配置
[database]
debug = true
link = "mysql:root:12345678@tcp(127.0.0.1:3306)/gf"
[redis]
disk = "127.0.0.1:6379,0"
cache = "127.0.0.1:6379,1"

View File

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<config>
<!-- 模板引擎目录 -->
<viewpath>/home/www/templates/</viewpath>
<!-- MySQL数据库配置 -->
<database>
<default>
<host>127.0.0.1</host>
<port>3306</port>
<user>root</user>
<pass>123456</pass>
<name>test</name>
<role>master</role>
<type>mysql</type>
<charset>utf8</charset>
<priority>1</priority>
</default>
<default>
<host>127.0.0.1</host>
<port>3306</port>
<user>root</user>
<pass>123456</pass>
<name>test</name>
<role>master</role>
<type>mysql</type>
<charset>utf8</charset>
<priority>1</priority>
</default>
</database>
<!-- Redis数据库配置 -->
<redis>
<disk>127.0.0.1:6379,0</disk>
<cache>127.0.0.1:6379,1</cache>
</redis>
</config>

View File

@ -1,27 +0,0 @@
# 模板引擎目录
viewpath: /home/www/templates/
# MySQL数据库配置
database:
default:
- host: 127.0.0.1
port: 3306
user: root
pass: "8692651"
name: test
type: mysql
role: master
charset: utf8
priority: 1
- host: 127.0.0.1
port: 3306
user: root
pass: "8692651"
name: test
type: mysql
role: master
charset: utf8
priority: 1
# Redis数据库配置
redis:
default: 127.0.0.1:6379,0
cache : 127.0.0.1:6379,2

View File

@ -1,25 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
func init() {
s := g.Server()
s.BindHandler("/apple", Apple)
s.BindHandler("/pen", Pen)
s.BindHandler("/apple-pen", ApplePen)
}
func Apple(r *ghttp.Request) {
r.Response.Write("Apple")
}
func Pen(r *ghttp.Request) {
r.Response.Write("Pen")
}
func ApplePen(r *ghttp.Request) {
r.Response.Write("Apple-Pen")
}

View File

@ -1,16 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
type Order struct{}
func init() {
g.Server().BindObject("/{.struct}-{.method}", new(Order))
}
func (o *Order) List(r *ghttp.Request) {
r.Response.Write("List")
}

View File

@ -1,12 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/gins"
"github.com/gogf/gf/net/ghttp"
)
func init() {
ghttp.GetServer().BindHandler("/config", func(r *ghttp.Request) {
r.Response.Write(gins.Config().GetString("database.default.0.host"))
})
}

View File

@ -1,16 +0,0 @@
package demo
import (
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/os/gtime"
)
func init() {
ghttp.GetServer().BindHandler("/cookie", Cookie)
}
func Cookie(r *ghttp.Request) {
datetime := r.Cookie.Get("datetime")
r.Cookie.Set("datetime", gtime.Datetime())
r.Response.Write("datetime:" + datetime)
}

View File

@ -1,20 +0,0 @@
package demo
import (
"github.com/gogf/gf/net/ghttp"
)
type ControllerDomain struct{}
// 初始化控制器对象并绑定操作到Web Server
func init() {
// 只有localhost域名下才能访问该对象
// 对应URL为http://localhost:8199/test/show
// 通过该地址将无法访问到内容http://127.0.0.1:8199/test/show
ghttp.GetServer().Domain("localhost").BindObject("/domain", &ControllerDomain{})
}
// 用于对象映射
func (d *ControllerDomain) Show(r *ghttp.Request) {
r.Response.Write("It's show time bibi!")
}

View File

@ -1,24 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/gmvc"
"github.com/gogf/gf/net/ghttp"
)
type ControllerExit struct {
gmvc.Controller
}
func (c *ControllerExit) Init(r *ghttp.Request) {
c.Controller.Init(r)
c.Response.Write("exit, it will not print \"show\"")
c.Request.Exit()
}
func (c *ControllerExit) Show() {
c.Response.Write("show")
}
func init() {
ghttp.GetServer().BindController("/exit", &ControllerExit{})
}

View File

@ -1,36 +0,0 @@
package demo
import (
"fmt"
"github.com/gogf/gf/net/ghttp"
)
func Form(r *ghttp.Request) {
fmt.Println(r.GetPostMap())
fmt.Println(r.GetPostString("name"))
fmt.Println(r.GetPostString("age"))
}
func FormShow(r *ghttp.Request) {
r.Response.Write(`
<html>
<head>
<title>表单提交</title>
</head>
<body>
<form enctype="application/x-www-form-urlencoded" action="/form" method="post">
<input type="input" name="name" />
<input type="input" name="age" />
<input type="submit" value="submit" />
</form>
</body>
</html>
`)
}
func init() {
ghttp.GetServer().BindHandler("/form", Form)
ghttp.GetServer().BindHandler("/form/show", FormShow)
}

View File

@ -1,9 +0,0 @@
package demo
import "github.com/gogf/gf/net/ghttp"
func init() {
ghttp.GetServer().BindHandler("/", func(r *ghttp.Request) {
r.Response.Write("Hello World!")
})
}

View File

@ -1,30 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
)
type Method struct {
gmvc.Controller
}
func init() {
// 第三个参数指定主要注册的方法,其他方法不注册,方法名称会自动追加到给定路由后面,构成新路由
// 以下注册会中注册两个新路由: /method/name, /method/age
g.Server().BindController("/method", new(Method), "Name, Age")
// 绑定路由到指定的方法执行,以下注册只会注册一个路由: /method-name
g.Server().BindControllerMethod("/method-name", new(Method), "Name")
}
func (c *Method) Name() {
c.Response.Write("John")
}
func (c *Method) Age() {
c.Response.Write("18")
}
func (c *Method) Info() {
c.Response.Write("Info")
}

View File

@ -1,20 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
type Object struct{}
func init() {
g.Server().BindObject("/object", new(Object))
}
func (o *Object) Index(r *ghttp.Request) {
r.Response.Write("object index")
}
func (o *Object) Show(r *ghttp.Request) {
r.Response.Write("object show")
}

View File

@ -1,31 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
type ObjectMethod struct{}
func init() {
obj := &ObjectMethod{}
g.Server().BindObject("/object-method", obj, "Show1, Show2, Show3")
g.Server().BindObjectMethod("/object-method-show1", obj, "Show1")
g.Server().Domain("localhost").BindObject("/object-method", obj, "Show4")
}
func (o *ObjectMethod) Show1(r *ghttp.Request) {
r.Response.Write("show 1")
}
func (o *ObjectMethod) Show2(r *ghttp.Request) {
r.Response.Write("show 2")
}
func (o *ObjectMethod) Show3(r *ghttp.Request) {
r.Response.Write("show 3")
}
func (o *ObjectMethod) Show4(r *ghttp.Request) {
r.Response.Write("show 4")
}

View File

@ -1,30 +0,0 @@
package demo
import "github.com/gogf/gf/net/ghttp"
// 测试绑定对象
type ObjectRest struct{}
func init() {
ghttp.GetServer().BindObjectRest("/object-rest", &ObjectRest{})
}
// RESTFul - GET
func (o *ObjectRest) Get(r *ghttp.Request) {
r.Response.Write("RESTFul HTTP Method GET")
}
// RESTFul - POST
func (c *ObjectRest) Post(r *ghttp.Request) {
r.Response.Write("RESTFul HTTP Method POST")
}
// RESTFul - DELETE
func (c *ObjectRest) Delete(r *ghttp.Request) {
r.Response.Write("RESTFul HTTP Method DELETE")
}
// 该方法无法映射,将会无法访问到
func (c *ObjectRest) Hello(r *ghttp.Request) {
r.Response.Write("Hello")
}

View File

@ -1,25 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
type Product struct {
total int
}
func init() {
p := &Product{}
g.Server().BindHandler("/product/total", p.Total)
g.Server().BindHandler("/product/list/{page}.html", p.List)
}
func (p *Product) Total(r *ghttp.Request) {
p.total++
r.Response.Write("total: ", p.total)
}
func (p *Product) List(r *ghttp.Request) {
r.Response.Write("page: ", r.Get("page"))
}

View File

@ -1,34 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
)
type Rest struct {
gmvc.Controller
}
func init() {
g.Server().BindControllerRest("/rest", &Rest{})
}
// RESTFul - GET
func (c *Rest) Get() {
c.Response.Write("RESTFul HTTP Method GET")
}
// RESTFul - POST
func (c *Rest) Post() {
c.Response.Write("RESTFul HTTP Method POST")
}
// RESTFul - DELETE
func (c *Rest) Delete() {
c.Response.Write("RESTFul HTTP Method DELETE")
}
// 该方法无法映射,将会无法访问到
func (c *Rest) Hello() {
c.Response.Write("Hello")
}

View File

@ -1,18 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
)
type ControllerRule struct {
gmvc.Controller
}
func init() {
g.Server().BindController("/rule/{method}/:name", &ControllerRule{})
}
func (c *ControllerRule) Show() {
c.Response.Write(c.Request.Get("name"))
}

View File

@ -1,17 +0,0 @@
package demo
import (
"strconv"
"github.com/gogf/gf/net/ghttp"
)
func init() {
ghttp.GetServer().BindHandler("/session", Session)
}
func Session(r *ghttp.Request) {
id := r.Session.GetInt("id")
r.Session.Set("id", id+1)
r.Response.Write("id:" + strconv.Itoa(id))
}

View File

@ -1,23 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/gmvc"
"github.com/gogf/gf/net/ghttp"
)
type ControllerTemplate struct {
gmvc.Controller
}
func (c *ControllerTemplate) Info() {
c.View.Assign("name", "john")
c.View.Assigns(map[string]interface{}{
"age": 18,
"score": 100,
})
c.View.Display("view/user/index.tpl")
}
func init() {
ghttp.GetServer().BindController("/template", &ControllerTemplate{})
}

View File

@ -1,16 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
func init() {
ghttp.GetServer().BindHandler("/template2", func(r *ghttp.Request) {
content, _ := g.View().Parse("index.tpl", map[string]interface{}{
"id": 123,
"name": "john",
})
r.Response.Write(content)
})
}

View File

@ -1,17 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/gins"
"github.com/gogf/gf/net/ghttp"
)
func init() {
gins.View().SetPath("/home/www/template/")
ghttp.GetServer().BindHandler("/template3", func(r *ghttp.Request) {
content, _ := gins.View().Parse("index.tpl", map[string]interface{}{
"id": 123,
"name": "john",
})
r.Response.Write(content)
})
}

View File

@ -1,40 +0,0 @@
package demo
import (
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/os/gfile"
)
func Upload(r *ghttp.Request) {
if f, h, e := r.FormFile("upload-file"); e == nil {
defer f.Close()
fname := gfile.Basename(h.Filename)
buffer := make([]byte, h.Size)
f.Read(buffer)
gfile.PutBytes("/tmp/"+fname, buffer)
r.Response.Write(fname + " uploaded successly")
} else {
r.Response.Write(e.Error())
}
}
func UploadShow(r *ghttp.Request) {
r.Response.Write(`
<html>
<head>
<title>上传文件</title>
</head>
<body>
<form enctype="multipart/form-data" action="/upload" method="post">
<input type="file" name="upload-file" />
<input type="submit" value="upload" />
</form>
</body>
</html>
`)
}
func init() {
ghttp.GetServer().BindHandler("/upload", Upload)
ghttp.GetServer().BindHandler("/upload/show", UploadShow)
}

View File

@ -1,29 +0,0 @@
package demo
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
)
type User struct {
gmvc.Controller
}
func init() {
s := g.Server()
s.BindController("/user", new(User))
s.BindController("/user/{.method}/{uid}", new(User), "Info")
s.BindController("/user/{.method}/{page}.html", new(User), "List")
}
func (u *User) Index() {
u.Response.Write("User")
}
func (u *User) Info() {
u.Response.Write("Info - Uid: ", u.Request.Get("uid"))
}
func (u *User) List() {
u.Response.Write("List - Page: ", u.Request.Get("page"))
}

View File

@ -1,19 +0,0 @@
package stats
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
var (
total int
)
func init() {
g.Server().BindHandler("/stats/total", showTotal)
}
func showTotal(r *ghttp.Request) {
total++
r.Response.Write("total:", total)
}

View File

@ -1,10 +0,0 @@
package main
import (
"github.com/gogf/gf/.example/frame/mvc/app/model/article"
)
func main() {
m := article.Model
m.All()
}

View File

@ -1,11 +0,0 @@
<html>
<head>
<title>上传文件</title>
</head>
<body>
<form enctype="multipart/form-data" action="/upload" method="post">
<input type="file" name="upload-file" />
<input type="submit" value="upload" />
</form>
</body>
</html>

View File

@ -1,2 +0,0 @@
<h3>This is footer</h3>
<div style="color:red">tpl vals: {{.}}</div>

View File

@ -1,11 +0,0 @@
<html>
<head>
<title></title>
</head>
<body>
<h3>This is index</h3>
<p>tpl vals: {{.}}</p>
{{include "user/footer.tpl" }}
</body>
</html>

View File

@ -2,26 +2,15 @@ package main
import (
"fmt"
"github.com/gogf/gf/util/gconv"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/gview"
)
func main() {
type Base struct {
Id int `c:"id"`
CreateTime string `c:"create_time"`
}
type User struct {
Base `c:"base"`
Passport string `c:"passport"`
Password string `c:"password"`
Nickname string `c:"nickname"`
}
user := new(User)
user.Id = 1
user.Nickname = "John"
user.Passport = "johng"
user.Password = "123456"
user.CreateTime = "2019"
fmt.Println(gconv.Map(user))
fmt.Println(gconv.MapDeep(user))
s, err := gview.ParseContent(`{{.a}}`, g.Map{
"a": 1,
"b": 1,
})
fmt.Println(err)
fmt.Println(s)
}

View File

@ -128,7 +128,7 @@ func (r *Response) ClearBuffer() {
r.buffer.Reset()
}
// Output outputs the buffer content to the client.
// Output outputs the buffer content to the client and clears the buffer.
func (r *Response) Output() {
if r.Server.config.ServerAgent != "" {
r.Header().Set("Server", r.Server.config.ServerAgent)

View File

@ -93,6 +93,7 @@ func (r *Response) buildInVars(params ...map[string]interface{}) map[string]inte
}
vars["Form"] = r.Request.GetFormMap()
vars["Query"] = r.Request.GetQueryMap()
vars["Request"] = r.Request.GetMap()
vars["Cookie"] = r.Request.Cookie.Map()
vars["Session"] = r.Request.Session.Map()
return vars

View File

@ -50,7 +50,7 @@ func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.writer.(http.Hijacker).Hijack()
}
// OutputBuffer outputs the buffer to client.
// OutputBuffer outputs the buffer to client and clears the buffer.
func (w *ResponseWriter) OutputBuffer() {
if w.hijacked {
return

View File

@ -138,6 +138,7 @@ func New(path ...string) *View {
view.BindFunc("date", view.funcDate)
view.BindFunc("substr", view.funcSubStr)
view.BindFunc("strlimit", view.funcStrLimit)
view.BindFunc("concat", view.funcConcat)
view.BindFunc("replace", view.funcReplace)
view.BindFunc("compare", view.funcCompare)
view.BindFunc("hidestr", view.funcHideStr)

View File

@ -138,7 +138,7 @@ func (view *View) funcDate(format interface{}, timestamp ...interface{}) string
t = gconv.Int64(timestamp[0])
}
if t == 0 {
t = gtime.Millisecond()
t = gtime.Timestamp()
}
return gtime.NewFromTimeStamp(t).Format(gconv.String(format))
}
@ -148,16 +148,25 @@ func (view *View) funcCompare(value1, value2 interface{}) int {
return strings.Compare(gconv.String(value1), gconv.String(value2))
}
// SubStr implements build-in template function: substr
// funcSubStr implements build-in template function: substr
func (view *View) funcSubStr(start, end, str interface{}) string {
return gstr.SubStr(gconv.String(str), gconv.Int(start), gconv.Int(end))
}
// StrLimit implements build-in template function: strlimit
// funcStrLimit implements build-in template function: strlimit
func (view *View) funcStrLimit(length, suffix, str interface{}) string {
return gstr.StrLimit(gconv.String(str), gconv.Int(length), gconv.String(suffix))
}
// funcConcat implements build-in template function: concat
func (view *View) funcConcat(str ...interface{}) string {
var s string
for _, v := range str {
s += gconv.String(v)
}
return s
}
// funcReplace implements build-in template function: replace
func (view *View) funcReplace(search, replace, str interface{}) string {
return gstr.Replace(gconv.String(str), gconv.String(search), gconv.String(replace), -1)

View File

@ -12,6 +12,7 @@ import (
"github.com/gogf/gf/util/gconv"
"io/ioutil"
"os"
"strings"
"testing"
"time"
@ -169,12 +170,32 @@ func Test_Func(t *testing.T) {
gtest.Assert(err != nil, false)
gtest.Assert(result, `GF;gf`)
str = `{{"Go\nFrame" | nl2br}}`
view := gview.New()
result, err = view.ParseContent(str)
gtest.Assert(err != nil, false)
str = `{{concat "I" "Love" "GoFrame"}}`
result, err = gview.ParseContent(str, nil)
gtest.Assert(err, nil)
gtest.Assert(result, `ILoveGoFrame`)
})
}
func Test_FuncNl2Br(t *testing.T) {
gtest.Case(t, func() {
str := `{{"Go\nFrame" | nl2br}}`
result, err := gview.ParseContent(str, nil)
gtest.Assert(err, nil)
gtest.Assert(result, `Go<br>Frame`)
})
gtest.Case(t, func() {
s := ""
for i := 0; i < 3000; i++ {
s += "Go\nFrame\n中文"
}
str := `{{.content | nl2br}}`
result, err := gview.ParseContent(str, g.Map{
"content": s,
})
gtest.Assert(err, nil)
gtest.Assert(result, strings.Replace(s, "\n", "<br>", -1))
})
}
func Test_FuncInclude(t *testing.T) {