Quickly build restful api__swagger based on Beego and swagger on the Centos6.9

Source: Internet
Author: User
Tags install go
1. Install go 1.1 Download Source package: Go1.7rc3.linux-amd64.tar.gz 1.2 Extract the downloaded source package to the/usr/local directory. 1.3 Add the/usr/local/go/bin directory to the PATH environment variable: 1.4 View version information 2. Download Beego, bee tools and MySQL driver 3. Create an API project and run 4. Modify the code to implement Ormapping 4.1 new student model and corresponding Table 4.2 initialize ORM module 4.3 provide database query student method 4.4 Create Studentcontroller to provide student to add, delete, Modify, query one, query all of the method 4.5 will studentcontroller registration route run by 4.6 and through the swagger test recently gradually learning rest, RESTful Api, MVC Framework, Beego, swagger, Prepare the summary application to the project. In view of the official online beego orm default support MySQL, Sqlite, PostgreSQL three kinds of databases, the example of MySQL as a database benchmark, quickly build a RESTful API website. 1. Install Go

Decompression installation 1.1 Download source package: go1.7rc3.linux-amd64.tar.gz 1.2 Unzip the downloaded source pack to the/usr/local directory.

Tar-c/usr/local-xzf go1.7rc3.linux-amd64.tar.gz
1.3 Add the/usr/local/go/bin directory to the PATH environment variable:

To open the environment variable configuration file:

Vim/etc/profile

Add code:

Export path= $PATH:/usr/local/go/bin

Refresh Environment Variables:

Source/etc/profile 1.4 View version Information

Note: If the exit and then enter the system environment variable does not take effect, input source/etc/profile effect.

Workaround: You can simply add Source/etc/profile to the. bashrc file. 2. Download Beego, bee tools and MySQL driver

Execute the following command:

$ go get-u github.com/astaxie/beego 
$ go get-u Github.com/beego/bee
Where Beego is the source code for the framework, and Bee is a quick tool to create a Beego project.
Our goal is to implement ormapping, so connecting to the database is essential and requires another download of the go version of the MySQL driver:
$ go Get github.com/go-sql-driver/mysql
All the files downloaded through go get are in ~/go/src, and the Bee tool is in ~/go/bin.
3. Create API projects and run

Directly using the Bee tool to create a simple RESTful API project is an option, assuming that our project name is TESTAPI, then just execute:

Bee API Testapi

Then the program creates the corresponding file in the directory ~/go/src/testapi

Next we need to run this project. First switch to the project folder, and then run the Bee Run command:

CD ~/go/src/testapi 
Bee Run-gendoc=true-downdoc=true

This time we can see that the system is already running at Port 8080, we switch to the browser and visit the swagger address of this website (http://localhost:8080/swagger/):

4. Modify code to achieve ormapping

If we come to the Testapi project folder, we see a structure similar to MVC, but since the Web API does not require real view, all view folders are replaced by swagger. Below we will create a new student object and implement the Web API for student additions and deletions. 4.1 New student model and corresponding table

We can create the student table in MySQL first:

CREATE table ' student ' (
  ' Id ' int (one) not NULL,
  ' Name ' varchar (
  ' birthdate ' date,
  ' Gender ' tinyint (1),
  ' Score ' int (one),
  PRIMARY KEY (' Id ')
)

Then create a new Student.go file under the Model folder, adding Student objects:

Type Student struct {
        Id int
       Name string
       Birthdate string
       Gender bool
       Score int
} 4.2 Initialize ORM module

We're going to manipulate objects and databases through ORM, but ORM needs to be initialized to use, and we need to add the following in the Main.go file:

Import (
"Github.com/astaxie/beego/orm"
_ "Github.com/go-sql-driver/mysql"
)
Func init () {
Orm. Registerdriver ("MySQL", Orm.) Drmysql)
Orm. RegisterDatabase ("Default", "MySQL", "zengyi:123@tcp (127.0.0.1:3306)/testdb?charset=utf8")
}
It should be noted here that the database connection string is not the same as the ordinary one, to be written in the following format:
Username: password @tcp (MySQL server address: port)/database name? Charset=utf8 4.3 method to provide database query student

The next step is the database access method. We can imitate the User.go, the method is written in the Student.go file. This is the complete Student.go file:

Package Models

Import (
"Github.com/astaxie/beego/orm"
"FMT"
"Time"
)

Type Student struct {
Id int
Name string
Birthdate string
Gender BOOL
Score int
}

Func getallstudents () []*student {
o: = orm. Neworm ()
O.using ("Default")
VAR students []*student
q:= o.querytable ("student")
Q.all (&students)
Return students

}
Func Getstudentbyid (id int) student{
U:=student{id:id}
o: = orm. Neworm ()
O.using ("Default")
ERR: = O.read (&u)
If Err = = orm. errnorows {
Fmt. Println ("Not in Query")
else if Err = = orm. ERRMISSPK {
Fmt. PRINTLN ("PRIMARY key not Found")
}
return u
}
Func addstudent (student *student) int{
o: = orm. Neworm ()
O.using ("Default")
O.insert (Student)
return student. Id
}
Func updatestudent (student *student) {
o: = orm. Neworm ()
O.using ("Default")
O.update (Student)
}

Func deletestudent (id int) {
o: = orm. Neworm ()
O.using ("Default")
O.delete (&student{id:id})
}

Func init () {
Need to register the defined model in Init
Orm. Registermodel (New (Student))
}4.4 Create Studentcontroller external to provide student add, delete, modify, query A, query all the methods

Here we can also imitate Usercontroller, directly rewrite into the studentcontroller.go we need. This is the content:

Package controllers

Import "Github.com/astaxie/beego"
Import (
"Testapi/models"
"Encoding/json"
)

Type Studentcontroller struct {
Beego. Controller
}
@Title get all the students
@Description return all student data
@Success {Object} models. Student
@router/[Get]
Func (U *studentcontroller) GetAll () {
SS: = models. Getallstudents ()
u.data["JSON" = SS
U.servejson ()
}
@Title get a student
@Description return a student's data
@Param ID Path int true "The key for Staticblock"
@Success {Object} models. Student
@router/:id [Get]
Func (U *studentcontroller) GetByID () {
ID, _:= u.getint (": id")
S: = models. Getstudentbyid (ID)
u.data["JSON"] = s
U.servejson ()
}
@Title Create a user
@Description Create a description of the user
@Param body models. Student true "Body for user Content"
@Success {int} models. Student.id
@Failure 403 body is empty
@router/[post]
Func (U *studentcontroller) Post () {
var s models. Student
Json. Unmarshal (U.ctx.input.requestbody, &s)
UID: = models. Addstudent (&s)
u.data["json" = UID
U.servejson ()
}
@Title Modify User
@Description Modify the user's content
@Param body models. Student true "Body for user Content"
@Success {int} models. Student
@Failure 403 body is empty
@router/[Put]
Func (U *studentcontroller) Update () {
var s models. Student
Json. Unmarshal (U.ctx.input.requestbody, &s)
Models. Updatestudent (&s)
u.data["JSON"] = s
U.servejson ()
}
@Title Delete a student
@Description Delete a student's data
@Param ID Path int true "The key for Staticblock"
@Success {Object} models. Student
@router/:id [Delete]
Func (U *studentcontroller) Delete () {
ID, _:= u.getint (": id")
Models. Deletestudent (ID)
u.data["JSON" = True
U.servejson ()
}
It should be noted here that the comments above the function are very important, there is a certain format requirements, swagger is based on these comments to show, so must be written correctly.4.5 will studentcontroller registration route by

Now that most of the work is done, we simply need to studentcontroller the new registration route by opening the Router.go and adding the following:

Beego. Nsnamespace ("/student",
Beego. Nsinclude (
&controllers. studentcontroller{},
),
),

Of course for the system default user and object, if we do not need, we can comment out. 4.6 Run and pass the swagger test

Our code has been completed. Next, use the Bee command to run our project:

Bee Run-gendoc=true-downdoc=true

We can see our new student controller. And you can do crud operations on the student table by calling the API.



Reference Link: http://studygolang.com/articles/10021


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.