---
title: User HTTP Service
slug: /examples/practices/user-http-service
keywords: [http, user, service, crud, mysql, dao, goframe, rest api, authentication, session, middleware, swagger, openapi, web service, backend, registration, login, authorization, jwt, user management, api documentation]
description: Demonstrates an HTTP RESTful API-based user management service with registration, login, and logout functionality. Features Session management, middleware authentication, OpenAPI documentation, MySQL integration, and DAO pattern. Ideal for learning GoFrame web API development and authentication systems.
hide_title: true
---

# 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

```text
.
├── 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](https://golang.org/dl/) `1.23` or higher
- [MySQL](https://www.mysql.com/) `5.7` or higher

## Prerequisites

### Install GoFrame CLI Tool

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

Or use `Makefile`:

```bash
make cli
```

### Setup MySQL Database

Run `MySQL` database using `Docker`:

```bash
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:

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

Or manually execute:

```sql
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](manifest/config/config.yaml):

```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:

```bash
make dao
```

### Run the Server

Start the `HTTP` server:

```bash
go run main.go
```

The server will start on port `8000` with the following endpoints:
- Swagger UI: http://localhost:8000/swagger
- OpenAPI Spec: http://localhost:8000/api.json

### 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:
   ```bash
   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**:
   ```bash
   curl -X POST http://localhost:8000/user/check-passport \
     -H "Content-Type: application/json" \
     -d '{"Passport": "user001"}'
   ```

3. **Sign In** - Authenticate user:
   ```bash
   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**:
   ```bash
   curl -X POST http://localhost:8000/user/is-signed-in \
     -b cookies.txt
   ```

5. **Get User Profile** (requires authentication):
   ```bash
   curl -X GET http://localhost:8000/user/profile \
     -b cookies.txt
   ```

6. **Sign Out**:
   ```bash
   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:**
```json
{
  "Passport": "string (6-16 chars, required)",
  "Password": "string (6-16 chars, required)",
  "Password2": "string (must match Password, required)",
  "Nickname": "string (optional)"
}
```

**Response:**
```json
{
  "code": 0,
  "message": "",
  "data": {}
}
```

#### SignIn
**POST** `/user/sign-in`

Authenticate user and create session.

**Request Body:**
```json
{
  "Passport": "string (required)",
  "Password": "string (required)"
}
```

**Response:**
```json
{
  "code": 0,
  "message": "",
  "data": {}
}
```

#### CheckPassport
**POST** `/user/check-passport`

Check if passport is available for registration.

**Request Body:**
```json
{
  "Passport": "string (required)"
}
```

**Response:**
```json
{
  "code": 0,
  "message": "",
  "data": {}
}
```

#### CheckNickname
**POST** `/user/check-nickname`

Check if nickname is available for registration.

**Request Body:**
```json
{
  "Nickname": "string (required)"
}
```

**Response:**
```json
{
  "code": 0,
  "message": "",
  "data": {}
}
```

#### IsSignedIn
**POST** `/user/is-signed-in`

Check if current user is signed in.

**Response:**
```json
{
  "code": 0,
  "message": "",
  "data": {
    "OK": true
  }
}
```

#### SignOut
**POST** `/user/sign-out`

Sign out current user and clear session.

**Response:**
```json
{
  "code": 0,
  "message": "",
  "data": {}
}
```

### Protected Endpoints

#### Profile
**GET** `/user/profile`

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

**Response:**
```json
{
  "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

```bash
make image
```

### Deploy to Kubernetes

```bash
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

