Beego Building API Services

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

Beego Introduction

Beego is a Golang implementation of the open-source Go application Development framework, he can be used to quickly develop APIs, WEB and backend services and other applications, is a restful framework, the main design inspiration from the tornado, Sinatra and flask three frameworks, But a framework designed to incorporate some of the features of Go itself (interface, struct embedding, etc.).

Beego Framework:
An open source framework that uses go thinking to help you build and develop your go applications
Beego Introduction

Beego installation, Bee command

Installing Beego

#go get github.com/astaxie/beego

Installing the Bee tool, the Bee tool is a project created to assist in the rapid development of BEEGO projects, with the ability to quickly create projects, implement thermal compilation, develop tests, and package releases from creation, development, and deployment through bee.

#go get github.com/beego/bee

The Bee command is installed by default under $gopath/bin to add this path to path.

In practice, the main use of the Bee three sub-commands: Api,run,pack.

  1. The
  2. API command is used to create an API app that generates the default Beego API application framework.

      # Bee API snmpcheck# Tree snmpcheck/snmpcheck/├──conf│  └──app.conf├──controllers│ & nbsp ├──object.go│  └──user.go├──docs│  └──doc.go├──main.go├──models│  ├──object.go│& Nbsp; └──user.go├──routers│  └──router.go└──tests└──default_test.go  

    Where routers/ Router.go is the related configuration of the route, the controllers directory under the various API routing related controller.

  3. The
  4. Run command is used to compile and run the Beego project, and through the fsnotify monitoring of the source code changes to achieve hot compilation, the development process can be real-time to see the effect of the project after the modification.

      # Bee Runbee:1.4.1beego:1.6.1go:go version go1.5.1 Linux/amd64[info] Uses ' snmpcheck ' as ' appname ' [ INFO] Initializing Watcher ... [TRAC] Directory (/home/lab/src/snmpcheck/controllers) [Trac] directory (/home/lab/src/snmpcheck) [Trac] directory (/home/ Lab/src/snmpcheck/models) [Trac] directory (/home/lab/src/snmpcheck/routers) [Trac] directory (/home/lab/src/ snmpcheck/tests) [INFO] Start building ... [SUCC] Build was successful[info] restarting Snmpcheck ... [INFO]./snmpcheck is running ... [Parser.go:61] [I]/home/lab/src/snmpcheck/controllers no changed [Parser.go:61][i]/home/lab/src/snmpcheck/controllers no changed [ Asm_amd64.s:1696][i] HTTP Server Running on:7070  
  5. Pack command is used when publishing apps.

    # bee packapp path: /home/lab/src/snmpcheckbuild snmpcheckGOOS linux GOARCH amd64build successexclude relpath prefix: .exclude relpath suffix: .go:.DS_Store:.tmpfile write to `/home/lab/src/snmpcheck/snmpcheck.tar.gz`

    The packaged tar package has an application executable file and configuration file that you can upload directly to your deployment.

    # tar -tf snmpcheck.tar.gz snmpcheckconf/app.conf

RESTful routing

Beego's routing settings are flexible, including fixed routing, regular matching routing, and automatic routing through the Go Reflection mechanism (which can lead to performance loss, which is not recommended) and annotation routing.

In practice, it is convenient to use annotation routing method. Use of annotation routes:

    1. First, the controller is registered in the router with the namespace method. Here, under /v1/user , import the usercontroller controller.

      ns := beego.NewNamespace("/v1",    ...    beego.NSNamespace("/user",        beego.NSInclude(            &controllers.UserController{},        ),    ),    ...)beego.AddNamespace(ns)
    2. The route is registered with annotations on the corresponding method in the controller.

      // @Title logout// @Description Logs out current logged in user session// @Success 200 {string} logout success// @router /logout [get]func (u *UserController) Logout() {    u.Data["json"] = "logout success"    u.ServeJSON()}

      Note Routing uses the keyword * * * @router.
      Here "@router/logout [get]" registers a route such as "Get/v1/user/logout, Usercontroller.logout ()".
      If the Beego is running in dev mode (which can be configured in conf), the routers directory generates the parsed results of the route commentsrouter.go, which can be used as a reference when debugging.

In-process monitoring

Beego provides monitoring and presentation of application information such as QPS, health status, program performance-related (GOROUTINE,GC,CPU, etc.), and can view static information such as routing configuration, conf configuration information, filter information, and view and trigger tasks.
Process monitoring is turned off by default and can be opened in a simple configuration, which is convenient:

EnableAdmin = trueAdminHttpAddr = 0.0.0.0 #默认监听地址是localhostAdminHttpPort = 8088

This will provide a monitoring display service on port 8088 after the app starts.

Automation documentation

Beego can realize the effect of automatic document through swagger and internal annotation parsing, using method:

    1. Routers/router.go Middle can only use namespace+include notation, and only support two-level resolution, the first-level version number, two-level respectively represents the application module. The global application information is set in the

    2. Routers/router.go file. Note that it must be written at the top of the file. The format of the

    3. Comment (the meaning of each field can be referred to auto Docs):

       //@Title login//@Description Logs user into the system//@P Aram Username Query string True "the username for login"//@Param password query string tru E "The password for login"//@Success $ {string} login success//@Failure 403 user not exist//@router/login [ge T]func (U *usercontroller) Login () {username: = u.getstring ("username") Password: = u.getstring ("password") if M Odels.    Login (username, password) {u.data["json"] = "Login Success"} else {u.data["json"] = "User not exist" } U.servejson ()}  
    4. Open the automatic document configuration in the configuration file:

        Enabledocs = True  
    5. Add automatic document parameters at startup:

        bee run-gendoc=true  

To meet the above configuration, Beego automatically resolves comments in the controller, launches the swagger service, and provides a generated JSON string on the /docs interface.
Access the Swagger service and access the /docs interface in swagger to see the documentation for the interface and to test the interface.

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.