当前位置:网站首页>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 waitgroup
beego 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)
}

 

原网站

版权声明
本文为[Favorite truffle chocolate]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200524235510.html