This is a creation in Article, where the information may have evolved or changed.
In a recent study of go, the intention is to make a web API based on go, so after a preliminary survey, we intend to use the framework of Beego, and then combine the ORM provided with the integration of swagger, can quickly build a restful API site.
Here are the specific practices:
1. Install go 1.8 in Ubuntu
The default Ubuntu Apt-get offers go 1.6, and we want to use the latest go 1.8 to do the following:
1.1 Add Apt-get Source and Refresh
sudo add-apt-repository ppa:gophers/sudo apt-get update
1.2 Installing GO 1.8
sudo Install golang-1.8
1.3 Setting environment variables
When the installation is complete, go will be installed into the/usr/lib/go-1.8 directory. We need to add some environment variables to execute the GO command and build our own project.
After we put the code in the Go directory under the current user, we need to create 2 directories first:
mkdir -P~/go/mkdir -P ~/GO/SRC
Then set the environment variables for the current user:
VI ~/.profile
Add the following at the end:
Export goroot=/usr/lib/go-1.8 export PATH="$PATH: $GOROOT/bin" Export Gopath= $HOME/go export PATH="$PATH: $GOPATH/bin"
After saving, refresh the environment variable again
SOURCE ~/.profile
Next we verify our Go version, enter
Go version
I am currently returning to go version go1.8.1 LINUX/AMD64 instructions our go 1.8 has been successfully installed
2. Download Beego, bee tools and MySQL driver
Beego is a very good web framework for Go beginners, providing a lot of features, some people say he is bloated, but for me this go beginner, do not care whether bloated, and care whether to solve the problem quickly, whether simple. Let's install Beego, which is simple, just execute the following command:
$ go get-u github.com/astaxie/-u Github.com/beego/bee
其中beego是框架的源代码,而bee是一个快速创建运行Beego项目的工具。
我们的目标是要实现ORMapping,那么连接数据库是必不可少的,需要另外下载Go版的MySQL驱动:
$ go Get github.com/go-sql-driver/mysql
These files downloaded through go get are in ~/go/src, while the Bee tool is in ~/go/bin.
3. Create an API project and run
Creating a simple RESTful API project directly using the Bee tool is a choice, assuming that our project name is Testapi, then we just need to do:
Bee API Testapi
Then the program will create 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 running command:
CD ~/go/src/-gendoc=true -downdoc=true
This time we can see that the system is already running on port 8080, we switch to the browser and visit the swagger address of this website:
http://192.168.100.129:8080/swagger/
You can see the swagger interface we are familiar with:
4. Modify the code to achieve ormapping
If we come to the Testapi project folder, we'll see a structure like MVC, but because the Web API doesn't need a real view, all the view folders are swagger replaced. Below we are going to 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 (11 ) not null , ' Name ' varchar ( tinyint< /span> (1 int (11 primary key (' Id '))
Then create a new Student.go file under the Model folder and add the Student object:
type Student struct { int Name string Birthdate string Gender bool int }
4.2 Initializing the ORM module
We want to manipulate objects and databases through ORM, but ORM needs to be initialized for use, and we need to add the following to 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 is important to note that the database connection string is not the same as the normal notation, to be written in the following format:
Username: password @tcp (MySQL server address: port)/database name? Charset=utf8
4.3 How to provide database query student
The next step is the database access method. We can imitate User.go, the method is written in the Student.go file. This is the complete Student.go file:
Package Modelsimport ("Github.com/astaxie/beego/orm" "FMT" " Time") Type Studentstruct{IdintNamestringBirthdatestringGenderBOOLscoreint}func getallstudents () []*Student {o:=ORM. Neworm () o.using ("default") varStudents []*Student Q:= O.querytable ("Student") Q.all (&students)returnstudents}func Getstudentbyid (IDint) student{u:=Student{id:id} o:=ORM. Neworm () o.using ("default") Err:= O.read (&u)ifErr = =ORM. errnorows {fmt. Println ("query not reached") } Else ifErr = =ORM. ERRMISSPK {fmt. Println ("primary key not found") } returnu}func addstudent (student*student)int{o:=ORM. Neworm () o.using ("default") O.insert (student)returnstudent. Id}func updatestudent (Student*Student) {o:=ORM. Neworm () o.using ("default") o.update (student)}func deletestudent (IDint) {o:=ORM. Neworm () o.using ("default") O.delete (&Student{id:id})} Func init () {//you need to register the defined model in initOrm. Registermodel (New(Student))}
4.4 Create Studentcontroller to provide student to add, delete, modify, query one, query all methods
Here we can also imitate Usercontroller, directly rewrite into the studentcontroller.go we need. This is the content:
Package Controllersimport"Github.com/astaxie/beego"Import ("Testapi/models" "Encoding/json") Type Studentcontrollerstruct{Beego. Controller}//@Title Get all the students//@Description to return all student data//@Success models {object}. 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 models {object}. 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 user's description//@Param body Body models. Student true "Body for user Content"//@Success models {int}. Student.id//@Failure 403 body is empty//@router/[post]Func (U *Studentcontroller) Post () {vars models. Student JSON. Unmarshal (U.ctx.input.requestbody,&s) UID:= Models. Addstudent (&s) u.data["JSON"] =uid U.servejson ()}//@Title Modifying Users//@Description Modify the user's content//@Param body Body models. Student true "Body for user Content"//@Success models {int}. Student//@Failure 403 body is empty//@router/[put]Func (U *Studentcontroller) Update () {vars 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 models {object}. Student//@router/:id [delete]Func (U *Studentcontroller) Delete () {ID, _:= U.getint (": ID") models. Deletestudent (ID) u.data["JSON"] =trueU.servejson ()}
Note here that the comments above the function are important, there are certain formatting requirements, and the swagger is based on these annotations, so it must be written correctly.
4.5 Registering the Studentcontroller in the route
Now that most of the work is done, we just need to register the new Studentcontroller, open the Router.go and add the following:
Beego. Nsnamespace ("/student", Beego. Nsinclude ( &controllers. studentcontroller{} ,),
Of course, for the system default user and object, if we do not need, can be commented out.
4.6 Run and pass swagger test
Our code is complete. Next use the Bee command to run our project:
Bee run-gendoc=true -downdoc=true
So we can see our new student controller. And you can do crud operations on the student table by invoking the API.