Experience Beego API development and automation documentation

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

When I learned the basic grammar of go, I saw some blogs about the simple and friendly use of go to develop APIs. Google a bit, then saw that the Beego framework can be used to develop the API and can also be combined with Swagger automation to generate documents. There was no time or no response to the basic knowledge experience, the recent time is much more generous. Don't talk much, follow the official documents to experience it. However, the official documentation for the basic database knowledge of the introduction of a pen.

Data import

Be sure to install, configure the database locally, and write the data information. We choose MYSQL database, after all, this is still quite a lot of. The installation configuration of the specific MAC platform is Goolge. Also recommend a database visualizer under the MAC platform-sequel Pro. I personally have just come into contact with this visual tool, there are many unfamiliar, side by side groping it. Specific information about the use of this data management software can be found here.

The following statement of the database's build table (the build table name is app) is as follows:

CREATE TABLE `app` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `create_date` datetime NOT NULL,  `app_code` varchar(255) COLLATE utf8_unicode_ci NOT NULL,  `app_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,  `publish_date` date DEFAULT NULL,  PRIMARY KEY (`id`),  UNIQUE KEY `app_code` (`app_code`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Insert two data into the app table:

INSERT INTO `app` VALUES ('1', NOW(), '100000', '神庙逃亡', '2015-08-06');INSERT INTO `app` VALUES ('2', NOW(), '100001', '愤怒的小鸟', '2015-08-06');

The corresponding terminals are as follows:

Creating an API Project

With the above created database tables, and continuing to combine the Beego framework, we execute the following named Build API project:

bee api go-api -conn="root:123456@tcp(127.0.0.1:3306)/api"

Where the project name is called GO-API, the database name is called API. The Mysql user name is root and the password is 123456. The command line resembles the following:

We open the specified directory to see if the API project is automatically generated, and the following items are generated under the specified directory for successful generation:

Integrated Swagger UI

First we turn on local debugging:

bee run -downdoc=true

The swagger UI is the best tool for generating and testing an API-generated document online, and the evaluation is also very good. After the API designer finishes the project, it can be far away from the painful writing of the document.

We are here to download swagger compressed package, unzip. Assign the contents to the Swagger folder in the project we just built. Last visited Http://127.0.0.1:8080/swagger. Can enter the following interface, how, the first feeling is not very cool? Next, let's take a look at the full range of features.

Try the sledgehammer, try the get operation, get all the content. The two data in the database table is shown as follows:

Then try the limit operation for each request for the limited data. Limit only one piece of data per request as shown:

Haha, is not very simple. Testing and developers are very convenient. There are some other common network request operation, do not do too much to explain, the experience you can feel convenient.

Code interpretation

Find the auto-generated project path, the code in the Main file looks like this, no different from the General Beego project, introduced the Swagger file.

 Package MainImport (_ "Beego-api/routers""Github.com/astaxie/beego""Github.com/astaxie/beego/orm"_ "Github.com/go-sql-driver/mysql")func Init() {ORM.RegisterDatabase("Default", "MySQL", "Root:123456@tcp (127.0.0.1:3306)/api")}func Main() {if Beego.Bconfig.RunMode == "Dev" {Beego.Bconfig.Webconfig.DirectoryIndex = trueBeego.Bconfig.Webconfig.Staticdir["/swagger"] = "Swagger"}Beego.Run()}

The code in Router.go is as follows:

//@APIVersion 1.0.0//@Title beego Test API//@Description Beego have a very cool tools to autogenerate documents for your API//@Contact astaxie@gmail.com//@TermsOfServiceUrl http://beego.me///@License Apache 2.0//@LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html Package RoutersImport ("Beego-api/controllers""Github.com/astaxie/beego")func Init() {  //Note one placeNS := Beego.Newnamespace("/v1",//Note two placesBeego.Nsnamespace("/app",Beego.Nsinclude(&Controllers.AppController{},),),)Beego.AddNamespace(NS)}

For the two code comments above, introduce some description of the official documentation:

Let's take a look at the route code, which is a hierarchy of nested functions, the first parameter is, that is, the /v1 /v1 beginning of the route tree, the second argument is that the beego.NSNamespace third parameter is also, that is, the beego.NSNamespace routing tree nested the routing tree, and our beego.NSNamespace inside is the NewNamespace same parameter , the first parameter is the route prefix, and the second parameter is the slice parameter. Here we call the beego.NSInclude introduction of annotated routing, this function is specifically for the annotated route design, we can see that the design we do not have any routing information, just set the prefix, then where is this route set? We then analyze what is annotation routing.

Next, take a look at the App.go file in controllers.

//GetOne ...//@Title Get One//@Description get App by ID//@Paramidpath stringtrue "The key for Staticblock"//@Success models {object}. APP//@Failure 403:id is empty//@router/:id [get]func (C *AppController) GetOne() {Idstr := C.Ctx.Input.Param(": id")ID, _ := StrConv.Atoi(Idstr)v, Err := Models.Getappbyid(ID)if Err != Nil {C.Data["JSON"] = Err.Error()} Else {C.Data["JSON"] = v}C.Servejson()}

The official explanation is still the best. Note In order to streamline the code, replace the operation with the following post Get :

We see that each of our functions has a large section of comments, annotation routing is actually focused on the last line // @router / [post] , this line of comment is that the function is registered to the route / , the support method is post .

And we usually use beego.Router("/", &ObjectController{},"post:Post") the same effect, but this time the framework to help you automatically register such a route, how the framework to automatically register it? When the application starts, it will determine whether there is a call NSInclude , in the call, to determine whether the RunMode is a dev pattern, the words will determine whether the previous analysis, and the analysis of the object directory has been updated, using Go's AST for source analysis (of course, only the analysis of NSInclude the call controller), and then generate the file routers/commentsRouter.go , which automatically registers the routing information we need. This completes the entire annotation route registration.

Note routing is declared using the beginning, and // @router  must be placed above the function you want to register, regardless of the order of the other annotations @Title @Description , either in the first row or in the last line. There are two parameters, the first is the route that needs to be registered, and the second is the supported method.

Routes can support arbitrary rules supported by Beego, such as /object/:key parameter routing, fixed routing /object , or regular routing/cms_:id([0-9]+).html

The other important thing is the Model folder in the file, is the entity content, in fact, it is based on the database of the app this table generated.

All right, here's how to build an API project with the Beego framework and automate the building of your document's instance content. There is much to explore and continue to refuel.

Above, thank you for reading.

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.