Go Web Development Basics

Source: Internet
Author: User
Tags abstract define function manual min require nginx reverse proxy
1.Abstract

There are a lot of difficulties in learning web development, so write an article like a review category. As a roadmap, start with index of web development essentials to introduce the learning process of golang development and the example code. Many of the descriptions in the description use code to describe how the usage method does not do too much. Finally, you can easily copy the code to achieve your own needs.

This article adapts to the object: people who have some experience in web development have the flexibility to use Ajax (at least know how to detach) Golang Web Development has a certain understanding, at least skim over some golang web development books

After reading this article you will reap: Some tips for Golang web Development Golang Some useful APIs for web development

In this article, the explanation is written in the code comment in order to explain it as detailed as possible.

2.golang Web Development Check list

Skipped parts: Basic Process Control, OOP and other basic grammar knowledge. 2.1 This section provides a knowledge reference for Golang Web development. 1.Abstract 2.golang Web Development Check List 2.1 This section provides a knowledge reference for Golang_web development. 3. Router 3.1 Manual route 3.2 manually routed bindings 3.2.1 static files 3.2.2 fixed function and resource Acquisition 4. Page load 4.1 Pure static page (HTML) 4.2 template page load 5. Presentation Layer Script 5.1 require.js 5.1.1 Load 5.1.2 Page Business 5.2 JQuery 6. Operational Layer 7. Persistence Layer 7.1 Mysql 7.2 Mongod B 8. Unit Test Considerations 9.LOG Summary 3. Routers

Routers are the soul of the entire Web site, if the route does not make the bad URLs will be very disgusting.
So this part is designed to be the first one to say something.

Two types of routing are manual routing in order to be fixed by TUL, and the other is resources
Gets the resource (like get) by parsing the URL to mimic a static page

Automatic routing, mainly using the command mode of OOP to achieve. All features use post,
Unified portal, convenient rights management, security management, cross-domain management. But such a powerful feature is still
Give it to the framework to do it. This is not a reference for beginners. 3.1 Manual Routing

1 2 3 4 5 6 7 8 9 10 11 12 Package main import ("Log" "Net/http") func main () {routerbinding ()//route-binding function ERR: = http. Listenandserve (": 9090", nil)//Set the listening port if err! = Nil {log. Fatal ("Listenandserve:", Err)}}

Bind Route 3.2 manually routed bindings 3.2.1 Static files before Httpserver runs

1 http. Handle ("/pages/", http. Stripprefix ("/pages/", http. Fileserver (http. Dir ("./pages"))))
3.2.2 Fixed function and resource acquisition

They're all the same.

1 http. Handlefunc ("/images/", fileupload.downloadpictureaction)
4. Page Loading 4.1 Pure static pages (HTML)

Just give the route to the line. The folder is accessed automatically. But the production environment really has to be a CDN, if its own server more. Can be nginx reverse proxy.
The main benefits before and after separation, can be CDN is the number of communications. But it's OK to improve things by optimizing. 4.2 Loading of template pages provides only critical code.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 Commonpage, err: = template. Parsefiles ("Pages/common/head.gtpl",//Load Template "Pages/common/navbar.gtpl", "PAGES/COMMON/TAIL.GTPL") if err! = Nil {Pani C (Err. Error ()} Navargs: = map[string]string{"Home": "Home", "User": "Yupengfei"}///complex parameters start to plug knowledgepage, err: = Templ Ate. Parsefiles ("Pages/knowledge/knowledge.gtpl") Knowledgeargs: = Map[string] Interface {} {"Head": "This is a test title" , "Author": "Kun.wang", "Publishdatetime": "2014-09-14", "Content": template. HTML ("<p style=\" text-indent:2em\ "> Why should it be semantic? </p> ")}//Not bad, just do string analysis will affect engineering efficiency commonpage.executetemplate (W," header ", nil)//render Start Commonpage.executetemplate (W, "NavBar", Navargs) knowledgepage.executetemplate (W, "knowledge", Knowledgeargs) Commonpage.executetemplate (W, "tail", nil)
Provide only critical code. string array as input parameter error more difficult summary: Although reduced communication times, but no way on the Cdn egg pain, in addition, the template mapping egg pain. 5. Presentation Layer Script

The presentation layer scripts are difficult to do and not very studious.
But once this is done, the reusability of the code can be significantly improved.

In the ordinary case, JS development efficiency is very high flexibility, and the use of the client's CPU
Good performance, free resources, learning more people, good recruitment. 5.1 require.js 5.1.1 Loading

1 <script data-main= "/reqmod/login_main" language= "JavaScript" defer async= "true" src= "Js/r.js" ></script>

The entire page is left so a loading script of the portal (each page preferably only one JS file)

The advantage of JS is lazy loading. Maximum use of caching does not occur when the Web card is dead. (HTTP 304) A Web page uses only one JS DOM event binding, without having to write JS bindings on the HTML control

The disadvantage of learning more difficult site updates always have a browser that is not updated by the cache. Cause errors (so in some cases the customer knows how to refresh several times, has become accustomed to the user)

The parameter interprets the ' Data-main ' business logic entry, loading the current string. js this file ' language ' does not explain ' defer async ' literally means ' src ' r.js is require.js meaning. The code can be got everywhere. 5.1.2 Page Business

Load dependent files

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Require.baseurl = "/" Require.config ({baseUrl:require.baseUrl, paths: {"jquery": "Js/jquery-1.10.2.min", "Domready": "Reqmod/domready", "PM": "Reqmod/pmodal", "Cookie": "Reqmod/cookie", "User": "Reqmod/user", "Bootstrap": "reqmod/ Bootstrap.min "," NAV ":" Reqmod/nav "}, Shim: {' bootstrap ': {deps: [' jquery ']}}}); Direct copy is all done.

Execute page Business

The best thing to do is DOM and event binding. Load various JS library direct references.
The code is beautiful, the development efficiency, the execution efficiency are all very good.

1 2 3 4 5 6 7 8 require ([' Nav ', ' domready ', ' jquery ', ' user ', ' pm '], function (Nav,doc, $, user,pm) {//This function's first ' array ' parameter is the chosen dependent module. 1. Website absolute path. 2. When loading a dependent module, select Export content//array in order to match the function order, if there are two modules rely on such as jquery plug-ins, it is written that the last variable, directly using the ' $ ' doc (function () {//Domready Pm.load (); Loading various plugins HTML templates such as OK $ (' #btn_login ') [0].onclick = function () {User.login ();}//button event Binding}); });

Page model

1 2 3 4 5 6 7 8 9-one for each of the ten, and the define ( [' jquery ', ' Reqmod/cookie ', ' user ', ' bootstrap '], function ($,cookie,user) {//define function's parameter content require is the same. The module to be relied on here has a path configuration in the module that calls this module. Otherwise you will die very miserable, when the error will not say what is missing what place is wrong. var nav_load = function () {///Note functions are defined in the way that copy is the line $. Get ('/nav.html ', function (result) {var newNode = Document.createele ment ("div"); newnode.innerhtml = result; $ (' body ') [0].insertbefore (newnode,$ (' body ') [0].firstchild); Document.body.innerHTML = result + Document.body.innerHTML; $ (' #btn_login ') [0].onclick = function () {User.login ()} $ (' #btn_reg ') [0].onclick = function () {window.location= '/ Register.html '} $.post ('/login_check ', {}, function (data) {if (data==
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.