Skip to main content
Version: 2.8.x(Latest)

Basic Environment


Go Environment

GoFrame is a web backend framework based on the Go language. First, we need a Go development environment to proceed with further learning. Ensure that your Go version is above 1.20.

$ go version
go version go1.22.2 windows/amd64

Database

During software usage, numerous data are generated and eventually need to be stored in a database. You need to prepare a database, and this book uses MySQL as an example, with the database name of the sample project being star.

Besides MySQL, GoFrame also supports various databases like MariaDB, TiDB, PostgreSQL, SQL Server, SQLite, Oracle, ClickHouse, and DM. A simple modification of configurations and the introduction of related drivers are enough, which will be explained in detail during usage.

API Testing Tools

After the development of APIs, I use the curl command to test if the APIs meet expectations. However, command-line testing can be inconvenient, so it is recommended to prepare an API testing tool to transform curl commands into tests within the tool. Popular testing tools like Postman, Apifox, and Apipost have similar functionalities, allowing you to choose based on personal preference.

Install GF CLI Tool


The GoFrame framework offers powerful development assistance tools, which are an essential part of the framework. These tools help with project creation, code generation, project running, etc. The latest version of GF CLI can be installed with the following command:

$ go install github.com/gogf/gf/cmd/gf/v2@latest

After this, run the following command to check if the installation was successful:

$ gf version
v2.8.0
Welcome to GoFrame!
Env Detail:
Go Version: go1.22.2 windows/amd64
GF Version(go.mod): cannot find go.mod
...

The development environment used in this book is Go 1.22.2 and GoFrame v2.8.0. Even if your versions differ, there's no need to worry as Go and GoFrame boast strong backward compatibility.

Unable to Access Github

Due to network issues within China, accessing Github might fail, a common problem for domestic programmers. You can look for a usable Github mirror or use other proxy tools online to resolve this issue.

Project Initialization


Once the environment is ready, we can officially initialize the project. Find the directory where you want to store your program and execute the following command:

$ gf init star
initializing...
initialization done!
you can now run "cd star && gf run main.go" to start your journey, enjoy!

star is the project name, meaning StarBook in English, but you can choose any name you prefer. Next, enter the directory and run the project.

$ cd star && gf run main.go
build: .\main.go
go build -o .\main.exe .\main.go
.\main.exe
build running pid: 13628
2024-11-06 16:45:46.015 [INFO] pid[13628]: http server started listening on [:8000]
2024-11-06 16:45:46.015 [INFO] {4c9b7c33a654051860769a5fdef82a84} swagger ui is serving at address: http://127.0.0.1:8000/swagger/
2024-11-06 16:45:46.015 [INFO] {4c9b7c33a654051860769a5fdef82a84} openapi specification is serving at address: http://127.0.0.1:8000/api.json

ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
----------|--------|------------|-------------------------------------------------------|----------------------------------
:8000 | ALL | /api.json | github.com/gogf/gf/v2/net/ghttp.(*Server).openapiSpec |
----------|--------|------------|-------------------------------------------------------|----------------------------------
:8000 | GET | /hello | star/internal/controller/hello.(*ControllerV1).Hello | ghttp.MiddlewareHandlerResponse
----------|--------|------------|-------------------------------------------------------|----------------------------------
:8000 | ALL | /swagger/* | github.com/gogf/gf/v2/net/ghttp.(*Server).swaggerUI | HOOK_BEFORE_SERVE
----------|--------|------------|-------------------------------------------------------|----------------------------------

As the demonstration uses a Windows system, a main.exe file is generated. If you're using a Mac/Linux system, a main file is generated.

Then enter http://127.0.0.1:8000/hello in the browser or access it using an API testing tool. Seeing Hello, GoFrame! indicates that you have successfully launched a GoFrame project. Congratulations on taking the first step into great programming!

If you are using the IntelliJ IDEA or GoLand editor, you can install the GoFrame Helper plugin for better code suggestions and auto-completion features.

Upgrade Project

The default installed GoFrame may not be the latest version; you can upgrade in the project directory using the up command:

$ gf up

Project Directory Structure


After initializing the project, let's look at the project's directory structure:

Directory/File NameTypeDescription
apiAPIDefinition of input/output data structures for providing external services. Due to version management needs, it often exists as api/xxx/v1....
hackToolsDirectory for project development tools and scripts, such as CLI tool configurations, various shell/bat scripts, etc.
internalLogicDirectory for business logic. It hides visibility from the outside using Golang’s internal feature.
    cmdCommandsCommand-line management directory, can manage and maintain multiple command lines.
    constsConstantsDirectory for all project constants.
    controllerControllerLayer for receiving/parsing user input parameters, the entrance/interface layer.
    daoData AccessData Access Objects, an abstraction layer for interacting with the underlying database and only includes the most basic CRUD methods.
    logicLogicManagement and encapsulation of business logic, often the most complex part of the project.
    modelModelData structure management module, managing data entities, and input/output data structure definitions.
        doDomain ObjectsModels for converting between business models and instance models within DAO operations. Maintained by tools, not editable by users.
        entityEntityData models represent a one-to-one relationship between a model and a data set. Maintained by tools, not editable by users.
    serviceServiceInterface definition layer for business module decoupling. Specific interface implementations are injected in logic.
manifestManifestIncludes files for compiling, deploying, running, and configuring the program. Common contents include:
    configConfigDirectory for storing configuration files.
    dockerDockerFiles related to Docker images, such as dependence files, and script files.
    deployDeployFiles related to deployment. By default, Kubernetes’ yaml templates for cluster deployment managed by kustomize are provided.
    protobufProtobufProtobuf protocol definition files used in GRPC protocol, compiled into go files in the api directory.
resourceResourceStatic resources files. These files can often be injected into published files through resource packaging/image compilation.
go.modDependency ManagementDescription file for dependency management, using Go Module package management.
main.goEntry FileProgram entry file.

It may seem confusing at first, but don't worry, the important directories will be used gradually later.

Now, let's delete all initial sample files, leaving a blank environment for subsequent development. Press CTRL+C to terminate project operation and delete all files in the following directories:

api/*
internal/controller/*

Edit the cmd file to remove unnecessary code.

internal/cmd/cmd.go

package cmd

import (
"context"

"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gcmd"
)

var (
Main = gcmd.Command{
Name: "main",
Usage: "main",
Brief: "start http server",
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
s := g.Server()
s.Group("/", func(group *ghttp.RouterGroup) {
group.Middleware(ghttp.MiddlewareHandlerResponse)
})
s.Run()
return nil
},
}
)