GoFrame simple API development

Be your own porter

Creating a Web service

  1. Initialize the project

    This example uses Xgo. Create an xgo directory and run gf init xgo

    gf init xgo
    Copy the code
  2. The new API

    This example uses welcome. In the./app/ API directory, create a new function directory. Create a new API code file in the new function directory.

    Code file path: / app/API/welcome/welcome. Go

    Code content:

    package welcome
    
    import (
        "github.com/gogf/gf/net/ghttp"
    )
    
    // 
    func Welcome(r *ghttp.Request) {
        r.Response.Writeln("Welcome to goframe!")
    }
    Copy the code

    Use welcome for the package name. Introduce goFrame encapsulated GHTTP. Write an API handler that takes a pointer to the gttp.request wrapped by goFrame.

  3. Writing middleware

    This example writes a cross-domain middleware in the root directory to create a new directory middleware. Create a new Cers.go in the Middleware directory

    Code content:

    Package middleware import "github.com/gogf/gf/net/ghttp" / / allow the interface cross-domain Request func CORS (r * GHTTP. Request) { r.Response.CORSDefault() r.Middleware.Next() }Copy the code
  4. Registered routing

    The default routing file is in./router/router.go.

    Note from the official example:

    // You can manage the route registration in a single file, // you can also manage the route registration in different files by module, // but all in the router directory.

    This example starts in a single file.

    Code content:

    package router
    
    import (
        "github.com/gogf/gf/frame/g"
        "github.com/gogf/gf/net/ghttp"
    
        "xgo/app/api/hello"
        "xgo/app/api/welcome"
    
        "xgo/middleware"
    )
    
    func init() {
        s := g.Server()
        s.Group("/", func(group *ghttp.RouterGroup) {
    
            group.Middleware(middleware.CORS)
    
            group.ALL("/", hello.Hello)
            group.ALL("/welcome", welcome.Welcome)
        })
    }
    
    Copy the code
  5. Run the service

    go run main.go
    Copy the code

    Routes for all services can be seen on the console after running the service.

  6. To access the URL

    Go to http://localhost:8199/welcome

    Output result:

    Welcome to goframe!
    Copy the code
  7. API return JSON

    Use GHTTP. Request. The Response. WriteJson () method returns a JSON. Modify the/app/API/welcome/welcome. Go

    package welcome
    
    import (
        "github.com/gogf/gf/net/ghttp"
    )
    
    type WelcomeInfo struct {
        Message string `json:"message"`
    }
    
    func Welcome(r *ghttp.Request) {
        var welcomeInfo WelcomeInfo
        welcomeInfo.Message = "Welcome to goframe!"
    
        r.Response.WriteJson(welcomeInfo)
    }
    Copy the code

    Start by defining the WelcomeInfo structure, adding an exportable property Message, and specifying key values for JSON parsing. In the Welcome method, set a value to the Message property of the WelcomeInfo instance. Then use the GHTTP. Request. The Response. WriteJson () returns a JSON.

    The raw data returned after accessing the URL is:

    {"message":"Welcome to goframe!"}
    Copy the code

The use of the Controller

Based on the previous project

  1. Add the Controller

    In/app/API/welcome/welcome. Go to define an empty structure Controller as the API management object. Route registration simply registers Controller with/Welcome, and all Controller pointer export functions are automatically mapped to the corresponding URL. Non-derived functions are not mapped.

    Mapping rules:

    • The function name is capitalized and mapped to the corresponding URL in lowercase.
    • Function names with uppercase letters are mapped to dash + lowercase letters.

    Example: The WelcomeMessage() function maps the URL to /welcome/welcome-message.

    For example, welcome. Go defines a method for Controller:

    package welcome
    
    import (
        "github.com/gogf/gf/net/ghttp"
    )
    
    type Controller struct{}
    
    func (c *Controller) Come(r *ghttp.Request) {
    
        r.Response.Writeln("Come to goframe!")
    }
    
    Copy the code
  2. Change the route registration mode

    Create a new Welcome Controller instance. Then register the Controller instance with/Welcome.

    package router
    
    import (
        "github.com/gogf/gf/frame/g"
        "github.com/gogf/gf/net/ghttp"
    
        "xgo/app/api/hello"
        "xgo/app/api/welcome"
    
        "xgo/middleware"
    )
    
    func init() {
        s := g.Server()
        s.Group("/", func(group *ghttp.RouterGroup) {
    
            ctlWelcome := new(welcome.Controller)
    
            group.Middleware(middleware.CORS)
    
            group.ALL("/", hello.Hello)
            group.ALL("/welcome", ctlWelcome)
        })
    }
    Copy the code
  3. Run the service

    Routes for all services can be seen on the console after running the service. As you can see, the/app/API/welcome/welcome. Go inside the Controller has functions of automatic registration to/welcome/last Come URL.

  4. To access the URL

    Go to http://localhost:8199/welcome/come

    Output result:

    Come to goframe!
    Copy the code

Use Controller and call Service

Based on the previous project

  1. Create a new Service code file

    Create a welcome directory under the./app/ API /service directory and a welcome file under the welcome directory.

    Code path: / app/API/service/welcome/welcome. Go

    Code content:

    package welcome
    
    type WelcomeInfo struct {
        Message string `json:"message"`
    }
    
    func Message() string {
        return "Welcome to goframe!"
    }
    
    func Info() WelcomeInfo {
    
        var welcomeInfo WelcomeInfo
        welcomeInfo.Message = "Welcome to goframe!"
    
        return welcomeInfo
    }
    Copy the code
  2. Call Service in a function of the API file Controller

    Function packs that need to be imported.

    package welcome import ( "github.com/gogf/gf/net/ghttp" "xgo/app/service/welcome" ) type Controller struct{} func (c *Controller) Message(r *ghttp.Request) { message := welcome.Message() r.Response.Writeln(message) } func (c *Controller)  Info(r *ghttp.Request) { welcomeInfo := welcome.Info() r.Response.WriteJson(welcomeInfo) }Copy the code
  3. Access URL validation after running the service.

    • Go to http://localhost:8199/welcome/message

    Output result:

    Welcome to goframe!
    Copy the code
    • Go to http://localhost:8199/welcome/info

    Output result:

    {"message":"Welcome to goframe!"}
    Copy the code

Accessing the database

Based on the previous project

  1. Creating a database

MySQL

CREATE SCHEMA `db_xgo` DEFAULT CHARACTER SET utf8mb4 ;
Copy the code
  1. Modify the database connection in the configuration file
# Database.
[database]
    link  = "Mysql: root: 123456 @ TCP (127.0.0.1:3306)/db_xgo"
    debug = true
    # Database logger.
    [database.logger]
        Path   = "/tmp/log/gf-app/sql"
        Level  = "all"
        Stdout = true
Copy the code
  1. The new table

    Create the system user table sys_user.

CREATE TABLE `db_xgo`.`sys_user` (
  `id` INT NOT NULL,
  `user_id` VARCHAR(45) NULL,
  `password` VARCHAR(45) NULL,
  `user_name` VARCHAR(45) NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `user_id_UNIQUE` (`user_id` ASC));
Copy the code
  1. Run the GoFrame command to generate code for database table operations

    Official documentation of the GoFrame command: goframe.org/toolchain/c…

    Start the command line in the Go program root directory to execute the command

    gf gen model ./app/model
    Copy the code

    The operation code for all tables is generated. The execution process of the preceding commands.

    E:\develop\github.com\bettersun\xgo\xgo>gf gen model ./app/model path './app/model' is not empty, files might be overwrote, continue? [y/n]: Y 2020-07-28 16:48:41.084 [DEBU] [2 ms] SHOW COLUMNS FROM [DEBU] [2 ms] SHOW COLUMNS FROM [DEBU] SHOW COLUMNS FROM [DEBU] [2 ms] SHOW COLUMNS FROM [DEBU] SHOW COLUMNS FROM [DEBU] [2 ms] SHOW COLUMNS FROM [DEBU `sys_user` generated: ./app/model\sys_user\sys_user.go generated: ./app/model\sys_user\sys_user_entity.go generated: ./app/model\sys_user\sys_user_model.go done!Copy the code
  2. Add table operation code

    In. / app/service/welcome/welcome. Go add function, performing queries on the table in the function.

    func WelecomeUser() string { var message string sysUser, err := sys_user.FindAll() if err ! = nil { fmt.Println(err) message = "Error" return message } if len(sysUser) > 0 { message = "Welcome, " + sysUser[0].UserName + "." } else { message = "No user." } return message }Copy the code
  3. Adding a routing function

    In/app/API/welcome/welcome. Go add function, call the function in the Service in the function.

    func (c *Controller) WelcomeUser(r *ghttp.Request) {
    
        WelecomeUser := welcome.WelecomeUser()
        r.Response.Writeln(WelecomeUser)
    }
    Copy the code
  4. Run the service access URL

    Go to http://localhost:8199/welcome/welcome-user

    Output result:

    No user.
    Copy the code
  5. Add data to a database table

    INSERT INTO `db_xgo`.`sys_user` (`id`, `user_id`, `password`, `user_name`) VALUES ('1'.'bettersun'.'123456'.'This heart is bright');
    Copy the code

    Make sure it is submitted.

  6. Revisit the URL

    Go to http://localhost:8199/welcome/welcome-user

    Output result:

    Welcome, this heart is bright.Copy the code