All skills
gogf avatar

/goframe-v2

@911705d
by GoFramegogf/skills81 stars
3

GoFrame v2 development skill. Use only when the target Go project uses or is explicitly adopting GoFrame v2: the nearest go.mod requires github.com/gogf/gf/v2, existing Go files import github.com/gogf/gf/v2 or any github.com/gogf/gf/v2/... component package, or the user asks to scaffold, migrate, or build with GoFrame. Trigger for GoFrame-backed Go work such as APIs/controllers/services, middleware, routing/config, ORM/DAO/DO/entity/database operations, gf CLI/codegen, HTTP/gRPC services, and microservice conventions. Do not trigger for generic Go projects without GoFrame evidence, frontend-only work, shell scripts, or unrelated infrastructure tasks.

Use this Skill: https://skilld.dev/gh/gogf/skills/goframe-v2

This session only. Nothing lands on disk.

examplespracticesuser-http-serviceREADME.MD

≈2.9k tokens on demand. Your agent reads this file only when SKILL.md points to it.

User HTTP Service Practice

Description

This example demonstrates a complete user management service using HTTP RESTful API and GoFrame. It showcases:

  • User registration, sign-in, and sign-out functionality
  • Session-based authentication and authorization
  • HTTP middleware for context injection and authentication
  • Auto-generated OpenAPI documentation with Swagger UI
  • MySQL database integration with DAO pattern
  • Request validation and error handling
  • Production-ready project structure

Structure

.
├── api/                   # API definitions
│   └── user/              # User service API
│       ├── user.go        # API definition for completeness check(auto-generated by "gf gen ctrl")
│       └── v1/            # API definition version v1
├── hack/                  # Development tools
│   └── config.yaml        # CLI tool configuration
├── internal/              # Internal packages
│   ├── cmd/               # Command definitions
│   │   └── cmd.go         # Main command with server setup
│   ├── consts/            # Constants
│   ├── controller/        # HTTP controllers
│   │   └── user/          # User controller(auto-generated + custom implementation)
│   ├── dao/               # Data access objects(auto-generated)
│   ├── model/             # Data models
│   │   ├── do/            # Domain objects(auto-generated)
│   │   └── entity/        # Database entities(auto-generated)
│   └── service/           # Business logic
│       ├── bizctx/        # Business context service
│       ├── middleware/    # Middleware service
│       ├── session/       # Session service
│       └── user/          # User service
├── manifest/              # Deployment manifests
│   ├── config/            # Configuration files
│   │   └── config.yaml    # Application config
│   ├── deploy/            # Deployment files
│   ├── docker/            # Docker files
│   └── sql/               # SQL scripts
│       └── create.sql     # Database schema
├── main.go                # Application entry point
├── go.mod                 # Go module file
└── Makefile               # Build automation

Features

The example showcases the following features:

User Management

  • User registration (SignUp) with duplicate checks
  • User authentication (SignIn) with password verification
  • User sign-out (SignOut) with session cleanup
  • User profile retrieval (Profile) for authenticated users
  • Username/nickname availability checking

Authentication & Authorization

  • Session-based user authentication
  • Custom business context for request handling
  • Middleware-based authorization
  • Protected routes requiring authentication
  • CORS support for cross-origin requests

API Documentation

  • Auto-generated OpenAPI specification
  • Interactive Swagger UI at /swagger
  • API documentation at /api.json
  • Request/response schema definitions
  • Endpoint descriptions and tags

Database Integration

  • MySQL database connection
  • DAO pattern for data access
  • Auto-generated DAO, DO, and Entity code
  • Transaction support
  • Query builder with validation

Request Handling

  • Automatic request/response JSON handling
  • Built-in validation with v tag
  • Standardized response format
  • Error handling and status codes
  • Route mapping with HTTP methods

Requirements

  • Go 1.23 or higher
  • MySQL 5.7 or higher

Prerequisites

Install GoFrame CLI Tool

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

Or use Makefile:

make cli

Setup MySQL Database

Run MySQL database using Docker:

docker run -d \
  --name mysql-user-http \
  -p 3306:3306 \
  -e MYSQL_ROOT_PASSWORD=12345678 \
  -e MYSQL_DATABASE=test \
  mysql:8.0

Initialize Database

Execute the SQL script to create the user table:

# Connect to MySQL
docker exec -i mysql-user-http mysql -uroot -p12345678 test < manifest/sql/create.sql

Or manually execute:

CREATE TABLE `user`(
    `id`        int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
    `passport`  varchar(45) NOT NULL COMMENT 'User Passport',
    `password`  varchar(45) NOT NULL COMMENT 'User Password',
    `nickname`  varchar(45) NOT NULL COMMENT 'User Nickname',
    `create_at` datetime DEFAULT NULL COMMENT 'Created Time',
    `update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Configuration

Update the database configuration in manifest/config/config.yaml:

server:
  address: ":8000"
  openapiPath: "/api.json"
  swaggerPath: "/swagger"

database:
  default:
    link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
    debug: true

Usage

Generate Code

Generate DAO, DO, and Entity code from database:

make dao

Run the Server

Start the HTTP server:

go run main.go

The server will start on port 8000 with the following endpoints:

Test the Service

Using Swagger UI

Open http://localhost:8000/swagger in your browser to interact with the API using the built-in Swagger interface.

Using cURL
  1. Sign Up - Register a new user:

    curl -X POST http://localhost:8000/user/sign-up \
      -H "Content-Type: application/json" \
      -d '{
        "Passport": "user001",
        "Password": "123456",
        "Password2": "123456",
        "Nickname": "Test User"
      }'
  2. Check Passport Availability:

    curl -X POST http://localhost:8000/user/check-passport \
      -H "Content-Type: application/json" \
      -d '{"Passport": "user001"}'
  3. Sign In - Authenticate user:

    curl -X POST http://localhost:8000/user/sign-in \
      -H "Content-Type: application/json" \
      -d '{
        "Passport": "user001",
        "Password": "123456"
      }' \
      -c cookies.txt
  4. Check Sign-In Status:

    curl -X POST http://localhost:8000/user/is-signed-in \
      -b cookies.txt
  5. Get User Profile (requires authentication):

    curl -X GET http://localhost:8000/user/profile \
      -b cookies.txt
  6. Sign Out:

    curl -X POST http://localhost:8000/user/sign-out \
      -b cookies.txt

API Reference

Public Endpoints

SignUp

POST /user/sign-up

Register a new user account.

Request Body:

{
  "Passport": "string (6-16 chars, required)",
  "Password": "string (6-16 chars, required)",
  "Password2": "string (must match Password, required)",
  "Nickname": "string (optional)"
}

Response:

{
  "code": 0,
  "message": "",
  "data": {}
}
SignIn

POST /user/sign-in

Authenticate user and create session.

Request Body:

{
  "Passport": "string (required)",
  "Password": "string (required)"
}

Response:

{
  "code": 0,
  "message": "",
  "data": {}
}
CheckPassport

POST /user/check-passport

Check if passport is available for registration.

Request Body:

{
  "Passport": "string (required)"
}

Response:

{
  "code": 0,
  "message": "",
  "data": {}
}
CheckNickname

POST /user/check-nickname

Check if nickname is available for registration.

Request Body:

{
  "Nickname": "string (required)"
}

Response:

{
  "code": 0,
  "message": "",
  "data": {}
}
IsSignedIn

POST /user/is-signed-in

Check if current user is signed in.

Response:

{
  "code": 0,
  "message": "",
  "data": {
    "OK": true
  }
}
SignOut

POST /user/sign-out

Sign out current user and clear session.

Response:

{
  "code": 0,
  "message": "",
  "data": {}
}

Protected Endpoints

Profile

GET /user/profile

Get profile of currently signed-in user (requires authentication).

Response:

{
  "code": 0,
  "message": "",
  "data": {
    "id": 1,
    "passport": "user001",
    "nickname": "Test User",
    "create_at": "2026-02-10 10:30:00",
    "update_at": "2026-02-10 10:30:00"
  }
}

Implementation Details

Controller Layer

internal/controller/user/ handles HTTP requests:

  • Receives and validates request parameters
  • Calls service layer for business logic
  • Returns standardized JSON responses
  • Auto-binds routes from g.Meta tags

Service Layer

internal/service/ contains business logic:

User Service
  • User creation with validation
  • Authentication and session management
  • Profile retrieval
  • Availability checking for passport/nickname
Middleware Service
  • Context injection for custom business data
  • Authentication middleware for protected routes
  • CORS middleware for cross-origin support
Session Service
  • User session management
  • Session storage and retrieval
  • User context in requests
Business Context Service
  • Custom context data injection
  • User information in request context
  • Session integration

DAO Layer

The internal/dao/ provides database access:

  • Auto-generated from database schema
  • Type-safe database operations
  • Chainable query builder
  • Transaction support

Data Models

  • DO (Domain Object): Used for database operations
  • Entity: Represents database table structure
  • API Models: Request/response structures with validation

Other Operations

Build Docker Image

make image

Deploy to Kubernetes

make deploy

Notes

  • Ensure MySQL is running before starting the application
  • Default database credentials are root:12345678 (change in production)
  • The service uses port 8000 by default
  • Sessions are stored in memory by default (configure Redis for production)
  • Password should be encrypted in production (this is a demo)
  • Swagger UI is available at http://localhost:8000/swagger
  • OpenAPI specification is at http://localhost:8000/api.json
  • SQL schema is in manifest/sql/create.sql

Security Considerations

This is a demonstration project. For production use, consider:

  • Encrypting passwords with bcrypt or similar
  • Using HTTPS for secure communication
  • Implementing rate limiting
  • Adding CSRF protection
  • Using Redis or similar for session storage
  • Implementing proper logging and monitoring
  • Adding input sanitization
  • Using JWT tokens for stateless authentication

Source: SKILL.md on GitHub

1 alert16d5 checks · Risk MEDIUM
  • Gen Agent Trust Hub16d

    The skill provides a comprehensive development guide and code examples for the GoFrame v2 framework. While highly informative for Go developers, it contains several examples with hardcoded placeholder secrets, tokens, and specific local file paths to sensitive configuration files (like Kubernetes credentials). These elements are provided for demonstration purposes but represent insecure practices if used in production without modification.

  • Socket16d

    5 alerts: gptSecurity, gptAnomaly

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer6mo

    227/949 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 911705d. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 months ago.

Steadyupdated 4 months ago
  • Go
  • Database
  • goframe
  • orm
  • http
  • grpc
  • microservices
  • crud
  • scaffolding
  • middleware

README badge

README badge for gogf/skills

Provides instruction and conventions for developing with GoFrame v2, a modular Go framework for building HTTP and gRPC services, microservices, and database operations using its ORM, CLI tooling, and project scaffolding. Use this skill when the target project has GoFrame v2 as a dependency or when the user requests scaffolding, migrations, or service development with GoFrame conventions.

Generated from the current SKILL.md.

When should I use this skill?
Use this skill only when your Go project uses GoFrame v2, indicated by github.com/gogf/gf/v2 in go.mod or imports. Do not use for generic Go projects, frontend work, or infrastructure tasks unrelated to GoFrame.
Should I manually set created_at and updated_at fields?
No. GoFrame automatically writes created_at on insert and updated_at on insert/update/save. Manually setting these fields is redundant and violates project conventions.
What should I use for database operations instead of g.Map?
Always use DO objects from internal/model/do/. DO struct fields are interface{}, unset fields remain nil and are automatically ignored by the ORM.
How does soft delete work in GoFrame?
Call Delete() on the DAO; GoFrame automatically converts it to UPDATE SET deleted_at = NOW(). Queries automatically filter out soft-deleted rows without requiring manual WhereNull conditions.
Where should I implement business logic?
Implement business logic directly in the service/ directory. Do not use the logic/ directory unless explicitly requested.

Generated from the current SKILL.md. These answers refresh after source changes.