Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of beego in golang

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the example analysis of beego in golang, which is very detailed and has certain reference value. Friends who are interested must finish it!

1.http.HandleFunc stores pattern and our custom handler in a map in DefaultServeMux.

two。 When the handler of http.ListenAndServe is nil, the system will obtain the corresponding handler from the matching pattern in the map in which the DefaultServeMux stores information, and then make a connection request.

If we summarize the above two items in simpler terms, they are: storage and matching of routes

Beego, as a framework based on golang (here only discusses the core http and routing part of the processing), must not be separated from the underlying support of the language. Therefore, we can boldly guess that the routing processing of beego is mainly on the encapsulation of HandleFunc, that is, how to better encapsulate HandlerFunc and be easy to use, which should also be the characteristic of beego supporting multiple routing methods.

1. Beego.Run

Let's first verify a simple guess from the source code that beego handles network requests based on http.ListenAndServe (this time it only analyzes the processing of http protocol, which is similar to https protocol).

Beego.Run ()-> BeeApp.Run ()

/ / Run beego application.

Func (app * App) Run () {

...

App.Server.Handler = app.Handlers

App.Server.ReadTimeout = time.Duration (BConfig.Listen.ServerTimeOut) * time.Second

App.Server.WriteTimeout = time.Duration (BConfig.Listen.ServerTimeOut) * time.Second

App.Server.ErrorLog = logs.GetLogger ("HTTP")

/ / run graceful mode

If BConfig.Listen.Graceful {

HttpsAddr: = BConfig.Listen.HTTPSAddr

App.Server.Addr = httpsAddr

If BConfig.Listen.EnableHTTPS {

Go func () {

...

If err: = server.ListenAndServeTLS (BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile); err! = nil {

Logs.Critical ("ListenAndServeTLS:", err, fmt.Sprintf ("% d", os.Getpid ()

Time.Sleep (100 * time.Microsecond)

EndRunning p.addToRouter

Where p is BeeApp.Handlers, so the main purpose of this series of operations is to store router information in BeeApp.Handlers.

(2) beego.Router

Beego.Router- > BeeApp.Handlers.Add- > p.addWithMethodParams-> p.addToRouter

In the same way as (1)

(3) beego.AutoRouter

Beego.AutoRouter- > BeeApp.Handlers.AddAuto- > p.AddAutoPrefixture-> p.addToRouter

In the same way as (1)

(4) beego.Include

Beego.Include- > BeeApp.Handlers.Include- > p.addWithMethodParams-> p.addToRouter

In the same way as (1)

(5) beego.AddNamespace

Beego.AddNamespace- > BeeApp.Handlers.routers [k]

Save the prefix in namespace.handlers.routers directly into BeeApp.Handlers.routers.

AddNamespace, NSNamespace and a series of internal NSNamespace method sets eventually still call the method set of n.handlers, and then go through AddNamespace and save it to BeeApp.Handlers

III. ServeHTTP

Since the request has been processed through http.ListenAndServe, according to our analysis of ListenAndServe, the final request will be processed by the ServeHTTP of server.Handler. The Handler in beego is BeeApp.Handlers, and its type is ControllerRegister, which means that the request is eventually processed by the ServeHTTP implementation of ControllerRegister. Here we will only talk about the processing process, and we will discuss the details in the later analysis article.

III. Summary

From the use of the two entrances beego.Run and router, we can see that the logic of beego processing is basically the same as that of the underlying http.ListenAndServe and http.HandleFunc of golang, except that there is a higher level of encapsulation and more convenient routing declaration and processing. In the following articles, we will make a further analysis of the processing of beego.

Finally, we can make a few simple summaries:

(1) routers package mainly generates routing and processing information, and saves it to BeeApp.Handler.

(2) beego.Run is a service that starts http with BeeApp.Handler.

(3) after receiving the request, the ServeHTTP of BeeApp.Handler will process the request and respond accordingly.

In fact, the entrance to beego is only beego.Run, how is it specifically related to routers?

one

Let's take a step-by-step look at the logic behind beego.Run.

1. Import & init

Let's start with the import section at the beginning of the program.

Import (

_ "test/routers"

"github.com/astaxie/beego"

)

We know that the direction of initialization of golang is as follows:

In this direction, we can see that we call routers package init first and import "github.com/astaxie/beego" again within routers, so we call beego package init first and then routers package init.

1.beego init

The code is as follows:

Var (

/ / BeeApp is an application instance

BeeApp * App

)

Func init () {

/ / create beego application

BeeApp = NewApp ()

}

Func NewApp () * App {

Cr: = NewControllerRegister ()

App: & App {Handlers: cr, Server: & http.Server {}}

Return app

}

Func NewControllerRegister () * ControllerRegister {

Cr: = & ControllerRegister {

Routers: make (map [string] * Tree)

Policies: make (map [string] * Tree)

}

Cr.pool.New = func () interface {} {

Return beecontext.NewContext ()

}

Return cr

}

The above init completes the initialization of BeeApp and initializes the values of Handler and Server (these are two very heavy parameters, which will be used later). Here we can see that the type of Handler is ControllerRegister, which will be used when processing requests.

2.routers init

Routers init is mainly a declaration of a route, for example:

Ns: =

Beego.NewNamespace ("/ v1"

Beego.NSCond (func (ctx * context.Context) bool {

If ctx.Input.Domain () = = "api.beego.me" {

Return true

}

Return false

})

Beego.NSBefore (auth)

Beego.NSGet ("/ notallowed", func (ctx * context.Context) {

Ctx.Output.Body ([] byte ("notAllowed"))

})

Beego.NSRouter ("/ version", & AdminController {}, "get:ShowAPIVersion")

Beego.NSRouter ("/ changepassword", & UserController {})

Beego.NSNamespace ("/ shop"

Beego.NSBefore (sentry)

Beego.NSGet ("/: id", func (ctx * context.Context) {

Ctx.Output.Body ([] byte ("notAllowed"))

})

),

Beego.NSNamespace ("/ cms"

Beego.NSInclude (

& controllers.MainController {}

& controllers.CMSController {}

& controllers.BlockController {}

),

),

)

/ / sign up for namespace

Beego.AddNamespace (ns)

We also mentioned in the preliminary study that the routes declared by beego.Get, beego.Router, beego.AutoRouter, beego.Include, beego.AddNamespace and so on are eventually stored in BeeApp.Handlers.routers.

II. Beego.Run

The beego.Run code is as follows:

Func Run (params... string) {

...

BeeApp.Run ()

}

Beego.Run finally calls the previously initialized BeeApp

/ / Run beego application.

Func (app * App) Run () {

...

App.Server.Handler = app.Handlers

App.Server.ReadTimeout = time.Duration (BConfig.Listen.ServerTimeOut) * time.Second

App.Server.WriteTimeout = time.Duration (BConfig.Listen.ServerTimeOut) * time.Second

App.Server.ErrorLog = logs.GetLogger ("HTTP")

/ / run graceful mode

If BConfig.Listen.Graceful {

HttpsAddr: = BConfig.Listen.HTTPSAddr

App.Server.Addr = httpsAddr

If BConfig.Listen.EnableHTTPS {

Go func () {

...

If err: = server.ListenAndServeTLS (BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile); err! = nil {

Logs.Critical ("ListenAndServeTLS:", err, fmt.Sprintf ("% d", os.Getpid ()

Time.Sleep (100 * time.Microsecond)

EndRunning

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report