当前位置:网站首页>Beego--- notes
Beego--- notes
2022-06-25 13:52:00 【Favorite truffle chocolate】


map and chan, Slices are all pointer types , So you can directly assign values to functions , No need to take the address
When the pointer operates , No need to go again *p Value operation , You can directly call methods and variables with pointers , because GO Automatically added
DB *gorm.DB Is a pointer to operate the database
Function names and structure fields can only be accessed if they are capitalized
What is retrieved from the database is added to the structure variable , It's very important
By go The marked function is equivalent to creating a concurrent , Parallel use in concurrency waitgroupbeego The routing namespace is the common part , Adoption under this path NS It begins with
NSCond( This path is executed only when the condition is true );
NSbefore( This is for the method set token verification filter )
beego.NSRouter( The conventional way of writing )
beego.NSNamespace( Path under path )
vs :=beego.NewNamespace("/v1",
beego.NSCond(func(ctx context.ConText){
if ctx.Input.Domain() == ""{
return true
}
}),
beego.NSbefore(&user.token)
beego.NSRouter("/hello",&user.name{},"get:Login")
beego.NSGet("/www",&user.fun)
beego.NSNamespace("v2",
beego.NSGet("v22",&www,name{})
)
)
beegp.AddNamespace(vs)
process :id,name,status,context, sort
status:run,wait,allready
Scheduling algorithm It can be based on order, queue , Rotation
That is to say, every time the coordination process is switched , Will switch to the scheduler first , Then switch from the scheduler to the next collaboration .
Added GO Add a synergy to the tag
Load balancing : Load ( A lot of requests ) Even 、 Balanced allocation to multiple service nodes for processing .
Reverse and forward The difference between :
The key difference between the two : Proxy object of proxy server .
The proxy in the forward proxy is to access the server instead of the client .
The proxy in the reverse proxy is to replace the server to deal with the access of the client .controller You can also define two structures in , One for printout
Models Define the role of two structures : One for combining beego.controller One is used to display to the front end
beeBind It is equivalent to that the assignment has been initialized
beego Use cros Allow cross domain requests before routing
this.Ctx.output Corresponding response;this.Ctx.input Corresponding request
tag:json Go back to the previous paragraph ,form Is the initialization structure
The current user logs in to generate token And back to token, When the user requests the rest of the pages, the back-end parses token return ID And weight and name , Then you can check the permissions to determine what the current user can do
beego.info() It is used to save in the log
Front end calls API when , You can get it directly id Etc , And every monitoring method should use model. Structure calls method
.First(this) And other query methods bring the results to this
The interface type can accept any parameter
If there is beego.Controller, that this.ctx.Output.JSON({ } ) ; otherwise Ctx.Output.JSON({ } )
count Must use &, Because no need & Relative to outside the function count The value is still empty
You can change the time first when creating and modifying , Before creating the modification function
DB.Where("user_id = ? and class_id = ?", this.UserId, this.ClassId).Find(&user)
Methods under the same package , Global functions can be called directly
controller of use models. Structure { } Assign a value to a variable , Call methods with variables
When routing is dynamic ID When Router(“/:id”) use this.Ctx.Input.Param(“:id”)
The defined function returns bool, Type assertions are available
ctx.Input.Query Waiting is all return string
Redis yes key-value database ,10 Ten thousand times ops request , Save in Redis in , Persistence can be put over a period of time Into disk , The next refresh call is at Redis in ;
1. The periodic deletion is every 100ms Just randomly choose whether there are expired key
2. Lazy deletion is to get a key Judge whether it is overdue
3. The elimination mechanism is to avoid being full of Redis Make something clear
Define constants constant x int =10
controller In the definition of get() It's rewriting
beego.run() Turn on monitoring
controller Realized controllerface{} Interface form and json There are two ways to get front-end content :
if err := beeBind.Bind(ctx, &member); err != nil
article := models.Article{ }
data := ctx.Input.RequestBody
if err := json.Unmarshal(data, &article); err != nil
json.Unmarshal And json.Marshal : One holds data , One for printing JSON// Get the value from the front end :
post perhaps put:
account := ctx.Request.FormValue("account")
pwd := ctx.Request.FormValue("pwd")
token := ctx.Request.Header.Get("Authorization")
ctx.Request.Header.Set("name", name)
ctx.Request.Header.Set("super", super)
get perhaps delete:
ctx.Input.Query("id")
ctx.Inout.Param(":id")
ctx.Input.RequestBody()MVC Pattern : from main,controllers,models, views, Route composition ;
Route call control , Control call model ,main Calling the model MySQL
controller Is to get the request data , And initialize the structure
models It is used to store the structure , And operate the database (DB)
&controllers.UserController{} Is to get the address after the call
controllers Medium this yes beego.controller Variable ,models Of the inner structure this It's a structural variable
gorm.model Bring it with you ID, Time and so on , It can exist directly in the structure
gorm.open Back to db yes *gorm.DB type
Methods of controlling layers and models , All fields must be capitalized , To be called
beego.Router(“/x”, &controllers.UserController{}, post:”Login”)
controller Medium this.Data[ ] To render to the view layer
gorm relation : Watch ID, Large table array , Many to many does not need anyone's ID
If now A Big ,B Small
What is equivalent to a query is :select * form A where A_id= 111
Contains the equivalent of a query :select * form B where A_id =1111
In the query A I hope that B The table will also query and bring out the results :
Preload(Bs).Find(&a) ( Be careful Bs It's a defined variable Bs []*B; Preload small tables or associated tables )
Belong to :A The structure contains B Structure variables and B Structure BID
contain :A Structure contains BID,B Structure contains A Structure
Containing multiple is the slice structure
Many to many :A The structure contains B Structure variable slice
b []B `gorm “many2many: a_b ; `
surface :
ID The default is table primary key
Table name is the plural form of structure name
The column name is the serpentine lowercase of the field name , Query fields
// Determine whether the name is repeated
func (this *Member) Repeat() bool {
var count int
NewConn().Table(this.TableName()).Where("iphone = ?", this.Iphone).Count(&count)
return count == 1
}
// Generally, only types are returned , Special way of writing :
// Function definition ( Returns with variable names and direct returns )
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
MD5:
user.Salt = string([]byte(getMd5(strconv.Itoa(rand.Intn(1000))))[:8]) // Take random number - Convert to string - take md5- Before interception 8 Bit slice - Convert to string
user.Pwd = getMd5(fmt.Sprintf("%s%s", user.Pwd, user.Salt)) // Password splicing salt value - take md5
func getMd5(temp string) string {
md5Ctx := md5.New()
md5Ctx.Write([]byte(temp))
return hex.EncodeToString(md5Ctx.Sum(nil))
}
You can return the value to the front end or to the rest controller
// Query data source details
func (this *DataSourceControllers) GetDataSource(id uint) (data_source models.DataSource, err error) {
data_source.Id = id
err = data_source.GetDataSource()
return
}
// Get all data sources ( But everything Find To define an array , And all you get is the address , External needs *p Value ; If you get a structure, you don't have to , Direct is the value )
func (this *DataSource) GetAllDataSource() (*[]DataSource, error) {
var data_sources []DataSource
conn := NewConn().Table(this.TableName()).Where(this).Find(&data_sources)
return &data_sources, conn.Error
}
// there wordLibraryId It's an array of pointers
// According to the incoming Thesaurus id Array to find the corresponding keyword list
func (this *KeywordController) GetKeywordsByWordLibraryId(WordLibraryId *[]uint) (*[]string, error) {
keyword := models.Keyword{}
keyword_list, err := keyword.GetKeyword(WordLibraryId)
if err != nil {
zeusLog.Error(" Failed to find keyword ", err.Error())
return nil, err
}
return keyword_list, nil
}
// Get a list of keywords
func (this *Keyword) GetKeyword(id_list *[]uint) (keywords *[]string, err error) {
err = NewConn().Select("word").Table(this.TableName()).Where("word_library_id in (?)", *id_list).Find(&keywords).Error
return
}
Paged fuzzy query
func (this *OperationLog) GetOperationLog(page, size int, keyword string) (operation_logs *[]OperationLog, count int, err error) {
var db = NewConn().Table(this.TableName())
if len(keyword) != 0 {
db = db.Where("operation_name like %s", "%"+keyword+"%")
}
err = db.Where(this).Count(&count).Error
err = db.Where(this).Order("id desc").Offset((page - 1) * size).Limit(size).Find(&operation_logs).Error
return
}
The conversion method between string and number
func main() {
// about ctx.Input.Query("id") The resulting value string type , So we need to stroconv.Atoi conversion
i, err := strconv.Atoi("12345")
if err != nil {
panic(err)
}
i += 3
println(i)
s := strconv.Itoa(12345)
s += "3"
println(s)
}
边栏推荐
- 一次性讲清楚 Handler 可能导致的内存泄漏和解决办法 | 开发者说·DTalk
- 多台云服务器的 Kubernetes 集群搭建
- API in Nova
- Syntax 'trap'
- 学习编程的起点。
- 多臺雲服務器的 Kubernetes 集群搭建
- Rust, le meilleur choix pour un programmeur de démarrer une entreprise?
- Asp. Net webform exporting excel using npoi
- Untiy force refresh UI
- 1251- client does not support authentication protocol MySQL error resolution
猜你喜欢

【Proteus仿真】51单片机+DS1302+lcd1602显示

多臺雲服務器的 Kubernetes 集群搭建

触觉智能分享-RK3568在金融自助终端的应用

Explication d'un problème de manuel

关于猜数字游戏的实现

Explain the possible memory leaks caused by the handler at one time and the solutions | the developer said · dtalk

Prototype and prototype chain - constructor and instanceof

关于三子棋游戏的简易实现与N子棋胜利判断方法

Scope of ES6 variable

多台云服务器的 Kubernetes 集群搭建
随机推荐
多台云服务器的 Kubernetes 集群搭建
论文阅读:Graph Contrastive Learning with Augmentations
Discuz copy today's headlines template /discuz news and information business GBK template
Websocket -- reverse proxy to solve cross domain problems
Simple realization of mine sweeping
leetcode:918. Maximum sum of circular subarray [reverse thinking + maximum subarray sum]
Openstack learning notes -nova component insight
1024 hydrology
Suanli & NFT trading platform f3 The exclusive NFT project of XYZ, hash eagle, will be grandly launched
Application of tactile intelligent sharing-rk3568 in financial self-service terminal
[pit avoidance means "difficult"] antd select fuzzy search
[data visualization] antv L7 realizes map visualization, drilldownlayer drill asynchronously obtains data, and suspends the warning box
Rust,程序员创业的最佳选择?
OpenStack-----Nova源码分析之创建虚拟机
Shenzhen mintai'an intelligent second side_ The first offer of autumn recruitment
【开源鸿蒙系统展示】RK3568开发板搭载OpenHarmony 3.1 Release
API in Nova
阻止深度神经网络过拟合(Mysteries of Neural Networks Part II)
Download File blob transcoding
Vscode--- format setting configuration