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
andGoFrame v2.8.0
. Even if your versions differ, there's no need to worry asGo
andGoFrame
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
orGoLand
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 Name | Type | Description |
---|---|---|
api | API | Definition of input/output data structures for providing external services. Due to version management needs, it often exists as api/xxx/v1... . |
hack | Tools | Directory for project development tools and scripts, such as CLI tool configurations, various shell/bat scripts, etc. |
internal | Logic | Directory for business logic. It hides visibility from the outside using Golang’s internal feature. |
cmd | Commands | Command-line management directory, can manage and maintain multiple command lines. |
consts | Constants | Directory for all project constants. |
controller | Controller | Layer for receiving/parsing user input parameters, the entrance/interface layer. |
dao | Data Access | Data Access Objects, an abstraction layer for interacting with the underlying database and only includes the most basic CRUD methods. |
logic | Logic | Management and encapsulation of business logic, often the most complex part of the project. |
model | Model | Data structure management module, managing data entities, and input/output data structure definitions. |
do | Domain Objects | Models for converting between business models and instance models within DAO operations. Maintained by tools, not editable by users. |
entity | Entity | Data models represent a one-to-one relationship between a model and a data set. Maintained by tools, not editable by users. |
service | Service | Interface definition layer for business module decoupling. Specific interface implementations are injected in logic. |
manifest | Manifest | Includes files for compiling, deploying, running, and configuring the program. Common contents include: |
config | Config | Directory for storing configuration files. |
docker | Docker | Files related to Docker images, such as dependence files, and script files. |
deploy | Deploy | Files related to deployment. By default, Kubernetes’ yaml templates for cluster deployment managed by kustomize are provided. |
protobuf | Protobuf | Protobuf protocol definition files used in GRPC protocol, compiled into go files in the api directory. |
resource | Resource | Static resources files. These files can often be injected into published files through resource packaging/image compilation. |
go.mod | Dependency Management | Description file for dependency management, using Go Module package management. |
main.go | Entry File | Program 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
},
}
)