Golang sample program developed using Beego and Mgo

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

Blog Original source : Http://wuwen.org/article/3/sample-web-application-using-beego-and-mgo

Listen, I feel very excited when I find the beego frame. It took me about 4 hours to port an existing WEB application to the framework and make some call extensions for end-to-end testing. I want to share this Beego-based site with you.

I built a sample WEB application with the following features Order:

    1. Implemented 2 Web calls to pull MongoDB data through a MGO drive.

    2. Use Envconfig to configure environment variables as parameters.

    3. Write test cases by Goconvey.

    4. Combined with my logging bag.

The code for this example can be found in the GitHub repository under the Goinggo account: Https://github.com/goinggo/beego-mgo.

You can pull and run it. It uses the public MongoDB database that I created in Mongolab. You will need to install Git and bazaar to ensure that you can use go get to install it on your system.

get github.com/goinggo/beego-mgo

Use the footsteps in the Zscripts folder to quickly run or test your WEB application.

WEB Application code Structure

Let's look at the project structure and the features of different folders:

    • App: Includes business, model, and service tiers.

    • App/models: Data structures for business and service tiers.

    • App/services: Used to provide basic functions for different services. Can be a function for a database or Web call.

    • App/business: Called by the Controller and the function that handles business rules. A combination of multiple services calls can be used to implement functionality at a larger level.

    • A pointcut for Controllers:url or Web API calls. The controller directly invokes the function of the business layer to process the request directly.

    • Routes: A mapping for URL and controller code.

    • Static: Used to hold statically-resourced resources such as scripts, CSS, and pictures.

    • Test: You can use the tests run with go test.

    • Utilities: Code that is used to support WEB applications. Sample and abstract code for database operations and panic processing.

    • Views: Used to store template files.

    • Zscripts: Scripts to help build, run, and test Web applications more easily.

controllers, models, and services

The code for these layers consists of a Web application. The idea behind my framework is to try to abstract code as a template. This requires me to implement a base controller package and a base service pack.

Base Controller Package

The base controller package consists of the default abstract controller behavior required by all controllers:

type (basecontroller struct {beego. Controller Services. Service}) func (this *basecontroller) Prepare () {this. UserId = "Unknown" tracelog. TRACE (this. UserId, "Before", "userid[%s] path[%s]", this. UserId, this. Ctx.Request.URL.Path) var err error this. Mongosession, err = MONGO. Copymonotonicsession (this. USERID) If err! = Nil {tracelog. Errorf (Err, this.) UserId, "before", this. Ctx.Request.URL.Path) this.        Serveerror (Err)}} func (this *basecontroller) Finish () {defer func () { If this. Mongosession! = Nil {mongo. CloseSession (this. UserId, this. Mongosession) this. Mongosession = nil}} () Tracelog.completedf (this. UserId, "Finish", this. Ctx.Request.URL.Path)} 

A BaseController new type named directly consists of type beego.Controller and services.Service embedding. This gives you direct access to all fields and methods of both types BaseController , and directly manipulate these fields and methods.

Service Pack

Service packs are used to model the code required for all services:

Type (    Service struct {        mongosession *mgo. Session        UserId       string    })                               func (this *service) dbaction (DatabaseName string, CollectionName string, Mongocall MONGO. Mongocall) (err error) {    return MONGO. Execute (this. UserId, this. Mongosession, DatabaseName, CollectionName, Mongocall)}

in the Service type , contains the Mongo session and the user ID. DBActionThe function provides an abstraction layer that runs MongoDB commands and queries.

Implement a Web call

Based on the base type and boilerplate functions, we can now implement a WEB call:

Buoy Controller

BuoyControllerthe type implements two binding BaseController and business layer Web API calls. Our main concern is called Station Web invocation.

Type buoycontroller struct {    BC. Basecontroller}                         func (this *buoycontroller) station () {    buoybusiness.station (&this. Basecontroller, this. GetString (": StationId"))}

type Buoycontroller directly by a separate basecontroller is composed. By this combination, automatically obtained the custom implementation of the prepare and finish method as well as all beego. The field of the Controller .

function station The is distributed through the following route. stationid As the last item in the URL. When this route is requested, a object is instantiated and executes the function station .

beego.Router("/station/:stationId", &controllers.BuoyController{}, "get:Station")

The function calls the business Station layer's code at the bottom to process the request.

Buoy Business

buoy business package implements buoycontroller Business layer. Let me look at station :

Func Station (Controller *BC. Basecontroller, stationId string) {    defer BC. Catchpanic (Controller, "station")                          TraceLog. STARTEDF (Controller. UserId, "station", "stationid[%s]", StationId)                          buoystation, err: = Buoyservice.findstation (&controller. Service, stationId)    if err! = Nil {        serveerror (err)        return    }                             controller. data["json"] = &buoystation    controller. Servejson ()    tracelog.completed (Controller. UserId, "Station")}

You can see that the function of the business layer handles the logic of the Station entire request. This function also uses the buoy service to handle the interaction with MongoDB.

Buoy Service

The Buoy Service package implements the interaction with MongoDB. Let's look at the code of the Station function called by the function of the business layer FindStation :

func findstation (service *services. Service, stationId String) (Buoystation *buoymodels.buoystation, err error) {Defer helper. Catchpanic (&err, service. UserId, "Findstation") tracelog. STARTED (service. UserId, "Findstation") QueryMap: = Bson. m{"station_id": StationId} tracelog. TRACE (service. UserId, "Findstation", "Query:%s", MONGO. ToString (querymap)) buoystation = &buoymodels.buoystation{} err = service. Dbaction (Config.database, "Buoy_stations", Func (collection *mgo. Collection) Error {return Collection. Find (QueryMap). One (buoystation)}) if Err! = Nil {tracelog.completed_error (Err, service. UserId, "Findstation") return buoystation, err} tracelog.completed (service. UserId, "Findstation") return buoystation, err} 

The function FindStation is used to prepare DBAction queries and perform operations with MongoDB through functions.

End-to-end testing

We now have a URL that can be routed to a controller and the logic of the corresponding business and service layer, which can be tested in the following ways:

func teststation (t *testing. T) {r, _: = http. Newrequest ("GET", "/station/42002", nil) W: = Httptest. Newrecorder () Beego. BeeApp.Handlers.ServeHTTP (W, r) Err: = struct {Error string} {} json. Unmarshal (W.body.bytes (), &err) convey ("Subject:test station endpoint\n", T, func () {convey (  "Status Code should is", func () {So (W.code, shouldequal,)}) convey ("the                       Result should not being Empty ", func () {SO (W.body.len (), Shouldbegreaterthan, 0)}) Convey ("The should is No Error in the Result", func () {SO (Len (err). Error), shouldequal, 0)})})} 

The test creates a virtual call to a route. This is great because we don't really have to launch a WEB app to test the code. With Goconvey we are able to create very elegant outputs and are easy to read.

The following is a sample of a test failure:

Subject:test Station Endpoint  Status Code should is the   Result should not being Empty the   should be No Error In the Result failures:*/users/bill/spaces/go/projects/src/github.com/goinggo/beego-mgo/test/endpoints/ Buoyendpoints_test.goline 35:expected: ' $ ' Actual: ' + ' (should be equal)         */users/bill/spaces/go/projects/src/ Github.com/goinggo/beego-mgo/test/endpoints/buoyendpoints_test.goline 37:expected: ' 0 ' Actual: ' 9 ' (Should be equal)                  3 Assertions thus far         ---fail:teststation-8 (0.03 seconds)

Here is an example of a successful test:

Subject:test Station Endpoint       Status Code should is the   Result should not being Empty the   should be No Error In the Result      3 assertions thus far     ---pass:teststation-8 (0.05 seconds)

Conclusion

Take the time to download the project and see for yourself. I try my best to give you a clear view of the focus I want to show you. The Beego framework allows you to implement abstraction and boilerplate code very easily, and integrate go testing, running, and deployment in the Go style.


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.