Gin
Gin is a lightweight, high-performance web framework written in Go. Its main function is to handle HTTP requests and responses, helping developers quickly build web applications and API services.
Common explanation
The Gin framework is like a waiter who receives the customer's orders (HTTP requests), and passes the orders to the appropriate chef (processing function) according to the menu (routing rules). After the chef prepares the food (generates the response data), the waiter then passes the food to the customer (returns the HTTP response).
1. Main functions
- Routing: Gin allows you to define different URL paths and HTTP methods (such as GET, POST) and map them to corresponding processing functions.
- Middleware: Multiple middleware functions can be inserted during the request processing process for authentication, logging and other operations.
- Parameter binding: Supports obtaining parameters from URLs, forms, JSON and other locations and binding them to structures.
- Error handling: Provides a convenient error handling mechanism to manage error responses in a unified manner.
2. Workflow
- Definition routing: Developers define various routes and their corresponding processing functions.
- Start the server: The Gin framework starts an HTTP server and listens for specific ports.
- Receive request: When an HTTP request arrives, Gin finds the corresponding processing function based on the request path and method.
- Execute middleware: Before the processing function is executed, the registered middleware is executed in turn.
- Processing request: Call the corresponding processing function to generate response data.
- Return response: Return response data to the client.
3. Example
package main import ( "/gin-gonic/gin" "net/http" ) func main() { r := () ("/ping", func(c *) { (, { "message": "pong", }) }) (":8080") }
Gorm
Gorm is an ORM (Object Relational Mapping) library written in Go. Its main function is to simplify database operations. Gorm maps database tables into Go structures, allowing developers to use Go code to perform database additions, deletions, modifications and searches, without directly writing SQL statements.
Common explanation: Gorm is like a translator, which translates Go code written by developers into SQL statements that the database can understand, and is responsible for executing these SQL statements and translating the results back to the Go data structure.
1. Main functions
- Model definition: Map the database table into a Go structure, defining fields and their properties.
- Query: Provides concise query methods, such as creating records, reading records, updating records, deleting records, etc.
- Relationship: Supports relationships between database tables, such as one-to-one, one-to-many, and many-to-many relationships.
- Migration: Automatically migrate the database table structure to keep it synchronized with the Go structure.
2. Workflow
- Definition model: The developer defines the Go structure corresponding to the database table.
- Initialize database connection: Configure database connection information and establish a connection.
- Perform operations: Use the methods provided by Gorm to perform database operations, such as creation, query, update, delete, etc.
- Processing results: Map the results of database operations back into the Go structure for use by business logic.
3. Example
package main import ( "/driver/mysql" "/gorm" "log" ) type User struct { ID uint `gorm:"primaryKey"` Name string `gorm:"size:255"` Email string `gorm:"uniqueIndex"` Age int } func main() { dsn := "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local" db, err := ((dsn), &{}) if err != nil { (err) } // Automatic migration (&User{}) // Create a record (&User{Name: "John", Email: "john@", Age: 25}) // Read records var user User (&user, 1) // Query the user with primary key of 1 (user) // Update records (&user).Update("Age", 26) // Delete records (&user) }
Gin+Gorm project practice
1. Project directory structure
my-gin-gorm-project/ │ ├── cmd/ │ └── // Main program entry│ ├── config/ │ └── // Configuration file parsing│ ├── controllers/ │ └── // User-related controller│ ├── models/ │ └── // User model definition│ ├── routes/ │ └── //Route definition│ ├── middlewares/ │ └── // Certification middleware│ ├── services/ │ └── // User-related business logic│ ├── repositories/ │ └── // User data access layer│ ├── utils/ │ └── // Tool function│ ├── .env // Environment variable file├── // Go module file└── // Depend on files
2. Main program entry (cmd/)
package main import ( "my-gin-gorm-project/config" "my-gin-gorm-project/routes" "/gin-gonic/gin" "/gorm" ) var db * func main() { // parse configuration file () // Initialize the database connection db = () // Set up the Gin engine r := () // Register a route (r) // Start the server () }
3. Configuration file parsing (config/)
package config import ( "log" "os" "/joho/godotenv" "/driver/mysql" "/gorm" ) var Config struct { ServerPort string DBUser string DBPassword string DBName string DBHost string DBPort string } // LoadConfig parses configuration filefunc LoadConfig() { if err := (); err != nil { ("Error loading .env file") } = ("SERVER_PORT") = ("DB_USER") = ("DB_PASSWORD") = ("DB_NAME") = ("DB_HOST") = ("DB_PORT") } // InitDB initializes the database connectionfunc InitDB() * { dsn := + ":" + + "@tcp(" + + ":" + + ")/" + + "?charset=utf8mb4&parseTime=True&loc=Local" db, err := ((dsn), &{}) if err != nil { ("Failed to connect to database:", err) } return db }
4. User model definition (models/)
package models import "/gorm" // User User Model Definitiontype User struct { Name string `gorm:"size:255"` Email string `gorm:"uniqueIndex"` Age int }
5. User-related controllers (controllers/)
package controllers import ( "my-gin-gorm-project/models" "my-gin-gorm-project/services" "net/http" "/gin-gonic/gin" ) // GetUsers Get all usersfunc GetUsers(c *) { users := () (, users) } // CreateUser Create new userfunc CreateUser(c *) { var user if err := (&user); err != nil { (, {"error": ()}) return } if err := (&user); err != nil { (, {"error": ()}) return } (, user) }
6. User data access layer (repositories/)
package repositories import ( "my-gin-gorm-project/models" "/gorm" ) var DB * // SetDB sets the database instancefunc SetDB(db *) { DB = db } // GetAllUsers Get all usersfunc GetAllUsers() ([], error) { var users [] if err := (&users).Error; err != nil { return nil, err } return users, nil } // CreateUser Create new userfunc CreateUser(user *) error { if err := (user).Error; err != nil { return err } return nil }
7. User-related business logic (services/)
package services import ( "my-gin-gorm-project/models" "my-gin-gorm-project/repositories" ) // GetAllUsers Get all usersfunc GetAllUsers() [] { users, _ := () return users } // CreateUser Create new userfunc CreateUser(user *) error { return (user) }
8. Route definition (routes/)
package routes import ( "my-gin-gorm-project/controllers" "/gin-gonic/gin" ) // RegisterRoutes Register all routesfunc RegisterRoutes(r *) { // User-related routing userRoutes := ("/users") { ("/", ) ("/", ) } }
9. Environment variable file (.env)
SERVER_PORT=:8080 DB_USER=root DB_PASSWORD=password DB_NAME=mydb DB_HOST=localhost DB_PORT=3306
10. Supplement: About the difference between utils and Middlewares and the use of
Utils (Tools)
Function: The tool class directory is used to store commonly used tool functions and general modules in projects. These functions and modules are usually independent of business logic and can be reused in various parts of the project.
-
Store content:
General tool functions: such as string processing functions, date-time processing functions, encryption and decryption functions, etc.
Configure parsing functions: Functions used to parse configuration files or environment variables.
Logging function: a tool for handling logging.
Token processing: such as token generation, analysis, verification, etc.
Other general modules: such as error handling functions, file operation functions, etc.
Example
package utils import ( "time" "/dgrijalva/jwt-go" "os" "errors" ) var jwtSecret = []byte(("JWT_SECRET")) // Claims Custom statementtype Claims struct { UserID uint } // GenerateToken GenerateTokenfunc GenerateToken(userID uint) (string, error) { expirationTime := ().Add(24 * ) claims := &Claims{ UserID: userID, StandardClaims: { ExpiresAt: (), }, } token := (jwt.SigningMethodHS256, claims) tokenString, err := (jwtSecret) if err != nil { return "", err } return tokenString, nil } // ParseToken parses Tokenfunc ParseToken(tokenString string) (*Claims, error) { claims := &Claims{} token, err := (tokenString, claims, func(token *) (interface{}, error) { return jwtSecret, nil }) if err != nil { return nil, err } if ! { return nil, ("invalid token") } return claims, nil }
Middlewares
Function: The middleware directory is used to store additional operations that need to be performed during HTTP request processing. These operations are usually performed before or after the request reaches the specific business logic processing, and are mainly used for pre-processing and post-processing of the request.
-
Store content:
Authentication middleware: For example, the token verification middleware ensures that the request carries a valid token.
Log middleware: record request logs, including request paths, methods, response time, etc.
Error handling middleware: Unified error handling and return standard error response.
CORS middleware: handles cross-domain requests.
Other preprocessing or postprocessing operations: such as requesting current limiting, compression response, etc.
Example
package middlewares import ( "my-gin-gorm-project/utils" "net/http" "strings" "/gin-gonic/gin" ) // AuthMiddleware authentication middlewarefunc AuthMiddleware() { return func(c *) { tokenString := ("Authorization") if tokenString == "" { (, {"error": "Token is missing in the request header"}) () return } tokenString = (tokenString, "Bearer ") claims, err := (tokenString) if err != nil { (, {"error": "Invalid Token"}) () return } ("userID", ) () } }
11. Project operation process
- Configure parsing and database connection: In the main program entrance, first load the configuration file and initialize the database connection.
- Routing Registration: Next, register all routes.
- Calls of controller and service layer: When a route is accessed, the controller will call the corresponding service layer method.
- Data access: The service layer performs database operations through the data access layer (Repository).
This is the article about the sample code of gin+gorm implementing goweb project. For more related content related to gin+gorm implementing goweb, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!