Back-end initialization--go (full stack) development of enterprise-level backend management system

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Abstract:

Finally to go with the language, to this, the author is a little excited about it, do not know why!
Regardless of whether you have been engaged in web-related development before, I believe you must have heard the word "framework", not why, because with the development and progress of society, by the predecessors summed up the structure, experience and so on, the system, reusable things, we can think of it as a framework. Now that we have a framework, there is no doubt that we have to use the framework here, do not ask me why, because the time is precious, we do not need to repeat the wheel, of course, if you want to write the framework, then I would like to wish you good luck!

Python and Go are also written at work. As of now, Python has a longer time than go, and various Python frameworks such as Django, Flask, Tornado, scrapy, and so on. And Go's web framework is not used much, so here I do a few of the framework of go a simple research and comparison, and then do a product selection.

First, Beego https://beego.me/

Frame Features:

    • Simplification: RESTful support, MVC model, you can use the Bee tool to quickly develop applications, including monitoring code modifications for hot compiling, automated test code, and automated packaging deployment.
    • Intelligent: Support Intelligent routing, intelligent Monitoring, can monitor QPS, memory consumption, CPU usage, in order to goroutine the health, so that your online application in control.
    • Modularity: Beego built-in powerful modules, including sessions, cache operations, logging, configuration parsing, performance monitoring, contextual operations, ORM modules, request simulations and other powerful modules to support any of your applications.
    • High performance: Beego uses the Go native HTTP package to handle requests, Goroutine's concurrency is high enough to handle large-volume WEB applications and API applications, and is now used in a large number of highly concurrent products.

Second, Revel http://revel.github.io/

Frame Features:

    • Hot compilation: When editing, saving, and refreshing, Revel automatically compiles code and templates, and if the code compiles incorrectly, it gives an error and captures the run-time error.
    • Full stack Features: Revel support: Routing, parameter resolution, validation, Session/flash, templates, caching, scheduled tasks, testing, internationalization and other functions.
    • High performance: Revel is built on Go HTTP server. This is the latest evaluation results released by Techempower. Up to three to 10 request load tests are carried out in a variety of different scenarios.
    • Modularity: The Revel framework consists of middleware called filters, which implements almost all of the request processing functions. Developers are free to use custom filters, such as custom routers, to replace the Revel default route filter.

Third, Martini Http://martini.codegangsta.io

Others like Goji,gin,traffic,faygo,essgo, Macaron, Goink, BAA and so on, if you are interested in can search to see their own.
In this article, taking into account the wide degree of document use, completeness of the document, and other unexplained reasons, this article decided to use the Beego framework

安装: 需要安装Beego和Bee的开发工具 go get -u github.com/astaxie/beego go get -u github.com/beego/bee

After the installation is complete, entering bee on the command line will have the following output:

Create a new Web project, the project name is simply called Systemadmin!

Look at the hints to know that we have successfully created a project named Systemadmin, and we'll look at the directory structure of the initialized project:

See this directory structure is not very clear? Yes, it is clear and clean, unlike the front-end code we initialized before, there are a lot of things.

Next we run the project with bee running to see:

Open the browser, we can see that the project has been launched at the http://localhost:8080/address, and then we look at the Beego MVC architecture, for our next development lay a good foundation, but also understand if you want to achieve a framework of their own, Perhaps we can learn about the design of an architecture.

The text is described as follows:

  1. The listening port receives the data, and the default listener is on port 8080.

  2. A user request arrives at port 8080 and then enters Beego's processing logic.

  3. Initializes the Context object, determines whether the request is a WebSocket request, if so, sets Input, and determines whether the requested method is in the standard request method (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD), Prevent users from malicious forgery request attacks that cause unnecessary impact.

  4. Implement Beforerouter filter, of course, there are switch settings in Beego. If the user has a filter set, the switch is turned on, which can improve execution efficiency without the filter turned on. If the responsewriter already has data output during the execution of the filter, the request is terminated ahead of time and jumps directly to the monitoring judgment.

  5. Begins the processing of the static file to see if the user's request URL matches the prefix registered in the static file processing Staticdir. If so, use the default Servefile in the HTTP package to handle the static files.

  6. If it is not a static file to start initializing the session module (if you open the session), you need to be aware of this, if your beforerouter filter to the session will be error, you should add it to the afterstatic filter.

  7. Start the execution of the afterstatic filter, if in the execution of the filter process, Responsewriter already have data output, then the early end of the request, jump directly to the monitoring judgment.

  8. After the filter has been executed, the object that matches the URL is started to be found and requested from a fixed routing rule. This match is the full match rule, that is, if the URL requested by the user is/hello/world, then/hello in the fixed rule will not match, only the exact match will be counted. If the match goes into logical execution, if it does not match the regular match into the next link.

  9. Regular matching is the full match of the regular match, which is matched according to the user's added Beego routing order, that is, if you add the route, your order will affect your match. As with a fixed match, if the match is executed logically, if the mismatch goes into Auto match.

  10. If the user registers the Autorouter, then through the Controller/method way to find the corresponding controller and his built-in method, if found to start the execution of logic, if not found to jump to the monitoring judgment.

  11. If the Controller is found, then start to execute the logic, first execute the beforeexec filter, if in the execution of the filter process, Responsewriter already has data output, then the early end of the request, jump directly to the monitoring judgment.

  12. The Controller starts executing the Init function and initializes some basic information, which is generally beego. Controller initialization, it is not recommended to modify the function when the user inherits.

  13. If XSRF is turned on, the Controller's Xsrftoken is invoked, and then the Checkxsrfcookie method is called if it is a POST request.

  14. Continue to execute the controller's Prepare function, which is usually reserved for the user, to do some of the parameters in the controller initialization and other work. If the output is responsewriter in the initialization, it goes directly to the Finish function logic.

  15. If there is no output, then according to the user registration method to execute the corresponding logic, if the user is not registered, then call HTTP. Method (Get/post, etc.). Execute the appropriate logic, such as data reading, data assignment, template display, or direct output of JSON or XML.

  16. If the responsewriter does not have output, then call the Render function for the template output.

  17. Executes the Controller's Finish function, which is reserved for use by the user to override, freeing up some resources. Releases the information data initialized in Init.

  18. Executes the afterexec filter and, if there is output, jumps to the monitoring judgment logic.

  19. Executes the destructor of the Controller to release some of the data initialized in Init.

  20. If the route is not found on this path, then 404 will be called to show that the page cannot be found.

  21. Finally all the logic is gathered to monitor the judgment, if the user turned on the monitoring module (by default, open a 8088 port for in-process monitoring), so that the access to the request link to the monitoring program to record the current access to the QPS, the corresponding link access execution time, request links and so on.

Now that we know the structure of the entire framework, then we simply implement the Get/post request as the practiced hand of our entire project initialization:

     GET /POST:       从前面了解到整个框架的入口函数为main.go   路由函数为router.go       所以我们首先需要在router.go中设置好路由 代码如下:
package routersimport (    "github.com/astaxie/beego"    "systemAdmin/controllers")func init() {    beego.Router("/", &controllers.MainController{})    beego.Router("/username", &controllers.UserController{})    beego.Router("/login", &controllers.LoginController{})}

Set up the route, the next need to implement the controller, respectively, Usercontroller and Logincontroller, the code is as follows:

 PackageControllersImport("Github.com/astaxie/beego"    "StrConv"    "Strings")typeMaincontrollerstruct{Beego. Controller}func(c *maincontroller) Get () {c.data["Website"] ="Magic.chen"c.data["Email"] ="Cfqcsunng@gmail.com"C.tplname ="Index.tpl"}//Basic GET request to get user nametypeUsercontrollerstruct{Beego. Controller}typeDatestruct{NamestringAgeintSexstring}func(c *usercontroller) Get () {data: = date{"Magic", -,"Male"Content: = Strings. Join ([]string{"Name:"+ Data.name,"Gender:"+ Data.sex,"Age:"+ StrConv. Itoa (Data.age)}," ") c.ctx.writestring (content)}//Basic POST requesttypeLogincontrollerstruct{Beego. Controller}func(c *logincontroller) Post () {username: = c.getstring ("username") Password: = c.getstring ("Password") Content: = Strings. Join ([]string{"User name:"+ Username,"Password:"+ Password}," ") c.ctx.writestring (content)}

To view the access results:
GET:

POST:
Post we use the Postman tool to test:

You can see that the output is consistent with our input. OK, here is a simple introduction of the use of the Beego framework to initialize a project, and simple implementation of the two most common Web requests, get/post, to this end, our backend project initialization work, even if the basic completion, since the front and back of the project has been set up OK, the next work is really on the right track , in the next series of courses, we will see in detail, if the front-end interaction, how to develop a sound enterprise management system.

So, look forward to it!

Reference directory:

    • Https://beego.me/docs/mvc/
    • https://www.zhihu.com/question/27370112
    • Build-web-application-with-golang
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.