### Install Project Dependencies with npm Source: https://github.com/fischlvor/go_blog/blob/master/web-blog/README.md Installs all necessary dependencies for the project using npm. This is a prerequisite for running development or build commands. ```sh npm install ``` -------------------------------- ### Configure and Run goBlog Backend Source: https://github.com/fischlvor/go_blog/blob/master/README.en.md Steps to configure and run the goBlog backend service written in Go. This includes dependency installation, database configuration, and starting the server. ```bash cd server # Install dependencies go mod tidy # Configure database cp configs/config.yaml.example configs/config.yaml # Modify database connection information in config file # Run the project go run main.go ``` -------------------------------- ### Run Development Server with Hot-Reloading Source: https://github.com/fischlvor/go_blog/blob/master/web-blog/README.md Starts the development server which includes hot-reloading. This command is used for active development, allowing changes to be reflected in the browser without a full page refresh. ```sh npm run dev ``` -------------------------------- ### Compile Project for Production Source: https://github.com/fischlvor/go_blog/blob/master/web-blog/README.md Compiles and minifies the project for production deployment. This command generates optimized build files. ```sh npm run build ``` -------------------------------- ### Configure and Run goBlog Frontend Source: https://github.com/fischlvor/go_blog/blob/master/README.en.md Instructions for setting up and running the goBlog frontend application using npm. This covers dependency installation, development server, and production build. ```bash cd web # Install dependencies npm install # Run in development mode npm run dev # Build production version npm run build ``` -------------------------------- ### Docker Compose Production Setup for Go Blog Source: https://context7.com/fischlvor/go_blog/llms.txt Defines the production services for the Go Blog project, including database, cache, search engine, backend APIs, frontends, and Nginx. It manages container orchestration, networking, and volume persistence. ```yaml version: '3.8' services: # Database mysql: image: mysql:8.0 container_name: blog-mysql environment: MYSQL_ROOT_PASSWORD: your_root_password MYSQL_DATABASE: blog_db volumes: - mysql_data:/var/lib/mysql - ./server-blog/sql:/docker-entrypoint-initdb.d ports: - "3306:3306" networks: - blog-network # Cache redis: image: redis:6.2-alpine container_name: blog-redis command: redis-server --appendonly yes volumes: - redis_data:/data ports: - "6379:6379" networks: - blog-network # Search Engine elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:8.17.0 container_name: blog-elasticsearch environment: - discovery.type=single-node - xpack.security.enabled=false - "ES_JAVA_OPTS=-Xms512m -Xmx512m" volumes: - es_data:/usr/share/elasticsearch/data ports: - "9200:9200" networks: - blog-network # SSO Authentication Service server-auth: build: ./server-auth-service container_name: blog-server-auth environment: - GIN_MODE=release volumes: - ./server-auth-service/configs:/app/configs - ./server-auth-service/keys:/app/keys - ./server-auth-service/logs:/app/logs depends_on: - mysql - redis ports: - "8000:8000" networks: - blog-network # Blog Backend Service server-blog: build: ./server-blog container_name: blog-server environment: - GIN_MODE=release volumes: - ./server-blog/configs:/app/configs - ./server-blog/keys:/app/keys - ./server-blog/log:/app/log - ./server-blog/uploads:/app/uploads depends_on: - mysql - redis - elasticsearch ports: - "8080:8080" networks: - blog-network # SSO Frontend web-auth: build: ./web-auth-service container_name: blog-web-auth ports: - "3000:80" networks: - blog-network # Blog Frontend web-blog: build: ./web-blog container_name: blog-web ports: - "5173:80" networks: - blog-network # Nginx Reverse Proxy nginx: build: ./nginx container_name: blog-nginx ports: - "80:80" - "443:443" volumes: - ./nginx/go_blog.conf:/etc/nginx/conf.d/default.conf - ./nginx/ssl:/etc/nginx/ssl depends_on: - server-auth - server-blog - web-auth - web-blog networks: - blog-network volumes: mysql_data: redis_data: es_data: networks: blog-network: driver: bridge ``` -------------------------------- ### Get Article Comments API Request Source: https://context7.com/fischlvor/go_blog/llms.txt Retrieves comments for a specific article with nested replies, supporting pagination. Requires 'article_id' as a query parameter and an 'Authorization' header. Returns a JSON object containing a list of comments, each with their replies. ```bash curl -X GET "http://localhost:8080/api/comment/list?article_id=article-uuid-here&page=1&page_size=20" \ -H "Authorization: Bearer access-token-here" ``` -------------------------------- ### Get Chat Sessions List API Request Source: https://context7.com/fischlvor/go_blog/llms.txt Retrieves a paginated list of chat sessions. Requires an 'Authorization' header with a bearer token. Returns a JSON object containing session data including IDs, titles, model used, message counts, and timestamps. ```bash curl -X GET "http://localhost:8080/api/ai-chat/sessions?page=1&pageSize=10" \ -H "Authorization: Bearer access-token-here" ``` -------------------------------- ### GET /api/oauth/authorize - OAuth Silent Login Flow Source: https://context7.com/fischlvor/go_blog/llms.txt Initiates the OAuth authorization flow, attempting a silent login if an active SSO session cookie is present. Redirects to the callback URI with an authorization code if successful. ```APIDOC ## GET /api/oauth/authorize ### Description Initiates the OAuth authorization flow. Attempts silent login if an active SSO session cookie is present. Redirects to the callback URI with an authorization code if successful. ### Method GET ### Endpoint /api/oauth/authorize ### Parameters #### Query Parameters - **app_id** (string) - Required - The unique identifier of the application. - **redirect_uri** (string) - Required - The URI to redirect to after authorization. - **state** (string) - Optional - A value used to maintain state between the request and callback. #### Request Headers - **Cookie** (string) - Optional - Contains the SSO session cookie for silent authentication. ### Request Example ```bash curl -X GET "http://localhost:8000/api/oauth/authorize?app_id=blog&redirect_uri=http://localhost:5173/callback&state=base64-state" \ -H "Cookie: sso_session=session-cookie-here" ``` ### Response #### Success Response (302 Found) - **Location** (header) - The URI to redirect to, including the authorization code and state. #### Response Example ```http HTTP/1.1 302 Found Location: http://localhost:5173/callback?code=auth-code-uuid&state=base64-state ``` ``` -------------------------------- ### Get Messages in Session API Request Source: https://context7.com/fischlvor/go_blog/llms.txt Retrieves messages within a specific chat session, with pagination. Requires 'session_id' as a query parameter and an 'Authorization' header. Returns a JSON object with message details like ID, role, content, and timestamps. ```bash curl -X GET "http://localhost:8080/api/ai-chat/messages?session_id=123&page=1&pageSize=20" \ -H "Authorization: Bearer access-token-here" ``` -------------------------------- ### Clone goBlog Project Source: https://github.com/fischlvor/go_blog/blob/master/README.en.md Instructions to clone the goBlog project repository using Git. This is the first step in setting up the project locally. ```bash git clone https://gitee.com/your-repo/go_blog.git cd go_blog ``` -------------------------------- ### Build goBlog Backend for Production Source: https://github.com/fischlvor/go_blog/blob/master/README.en.md Command to compile the goBlog backend Go application into an executable for production deployment. ```bash cd server && go build -o main . ``` -------------------------------- ### Register User API (Bash) Source: https://context7.com/fischlvor/go_blog/llms.txt Registers a new user account in the SSO system. Requires email, password, nickname, app_id, captcha_id, and captcha. Returns a success message upon successful registration. ```bash curl -X POST http://localhost:8000/api/auth/register \ -H "Content-Type: application/json" \ -d '{ "email": "user@example.com", "password": "SecurePass123!", "nickname": "John Doe", "app_id": "blog", "captcha_id": "captcha-uuid-here", "captcha": "123456" }' ``` -------------------------------- ### Deploy Single Service Script (Bash) Source: https://context7.com/fischlvor/go_blog/llms.txt This bash function deploys a single service. It builds a Docker image for the specified service, saves the image, and then streams it to a remote host. On the remote host, it loads the Docker image and updates the service using docker-compose. Dependencies include Docker, ssh, gzip, and a defined REMOTE_HOST and REMOTE_PATH environment variables. ```bash deploy_single() { local service=$1 echo "=== Deploying single service: $service ===" docker build -t goblog-$service:latest ./$service docker save goblog-$service:latest | gzip | \ ssh $REMOTE_HOST "cd $REMOTE_PATH && docker load && \ docker-compose -f docker-compose.prod.yml up -d $service" } case "${1:-all}" in ... single) if [ -z "$2" ]; then echo "Usage: $0 single " exit 1 fi deploy_single "$2" ;; ... esac ``` -------------------------------- ### Device Management API Source: https://context7.com/fischlvor/go_blog/llms.txt Provides endpoints for managing user devices, including listing devices, kicking specific devices, and logging out all devices. ```APIDOC ## Device Management API ### Description Manage user login devices with automatic device limit enforcement. This API allows users to view their active devices, revoke access for specific devices, or perform a global logout to invalidate all active sessions. ### Method GET, POST ### Endpoint /api/device/*, /api/auth/logout/all ### Endpoints Documentation #### List User Devices ##### Method GET ##### Endpoint `/api/device/list` ##### Query Parameters - **page** (integer) - Optional - The page number for pagination. Defaults to 1. - **page_size** (integer) - Optional - The number of items per page. Defaults to 10. ##### Request Example ```bash curl -X GET "http://localhost:8000/api/device/list?page=1&page_size=10" \ -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ##### Success Response (200) - **code** (integer) - The status code, typically 200. - **data** (object) - Contains the list of devices. - **list** (array) - An array of device objects. - **id** (integer) - The unique identifier for the device entry. - **device_id** (string) - A unique identifier for the device fingerprint. - **device_name** (string) - A user-friendly name for the device. - **device_type** (string) - The type of device (e.g., 'browser', 'mobile'). - **app_name** (string) - The name of the application the device is associated with. - **last_active_at** (string) - ISO 8601 timestamp of the last activity. - **is_current** (boolean) - Indicates if this is the currently active device. - **total** (integer) - The total number of devices associated with the user. ##### Response Example ```json { "code": 200, "data": { "list": [ { "id": 1, "device_id": "device-fingerprint-uuid", "device_name": "Chrome on Windows", "device_type": "browser", "app_name": "goBlog", "last_active_at": "2025-12-25T10:30:00Z", "is_current": true }, { "id": 2, "device_id": "another-device-uuid", "device_name": "Safari on iPhone", "device_type": "mobile", "app_name": "goBlog", "last_active_at": "2025-12-24T15:20:00Z", "is_current": false } ], "total": 2 } } ``` #### Kick Specific Device Offline ##### Method POST ##### Endpoint `/api/device/kick` ##### Request Body - **device_id** (string) - Required - The unique identifier of the device to kick. ##### Request Example ```bash curl -X POST http://localhost:8000/api/device/kick \ -H "Authorization: Bearer access-token-here" \ -H "Content-Type: application/json" \ -d '{ "device_id": "device-fingerprint-uuid" }' ``` #### Global Logout (Kick All Devices) ##### Method POST ##### Endpoint `/api/auth/logout/all` ##### Request Example ```bash curl -X POST http://localhost:8000/api/auth/logout/all \ -H "Authorization: Bearer access-token-here" ``` ``` -------------------------------- ### Create AI Chat Session (API) Source: https://context7.com/fischlvor/go_blog/llms.txt Initiates a new AI chat session with a specified title and model. This API call requires an authorization token and returns the session details upon successful creation. ```bash # Create new chat session curl -X POST http://localhost:8080/api/ai-chat/session \ -H "Authorization: Bearer access-token-here" \ -H "Content-Type: application/json" \ -d '{ "title": "Go Programming Questions", "model": "deepseek-chat" }' ``` -------------------------------- ### Nginx Configuration with Rate Limiting for Go Blog Source: https://context7.com/fischlvor/go_blog/llms.txt Configures the Nginx reverse proxy for the Go Blog project, including SSL termination, rate limiting for different zones (global, API, login), and SSE support for AI streaming. ```nginx # nginx/go_blog.conf # Rate limiting zones limit_req_zone $binary_remote_addr zone=global:10m rate=10000r/s; limit_req_zone $binary_remote_addr zone=api:10m rate=1000r/s; limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m; ``` -------------------------------- ### Article Like/Unlike with Redis Cache (Go) Source: https://context7.com/fischlvor/go_blog/llms.txt Implements article liking and unliking functionality on the server-side using Go. It utilizes Redis for caching like status and counts, and a database for persistent storage. The function handles checking existing likes, adding new likes, removing likes, and updating like counts. ```go // internal/service/article_service.go func (s *ArticleService) ArticleLike(req request.ArticleLike) error { cacheKey := fmt.Sprintf("article:like:%s:%s", req.ArticleID, req.UserUUID) // Check if already liked using Redis exists, err := global.Redis.Exists(context.Background(), cacheKey).Result() if err != nil { return err } if exists == 1 { // Unlike: remove from cache and database global.Redis.Del(context.Background(), cacheKey) global.DB.Where("article_id = ? AND user_uuid = ?", req.ArticleID, req.UserUUID).Delete(&database.ArticleLike{}) // Decrement like count in cache global.Redis.Decr(context.Background(), fmt.Sprintf("article:likes:%s", req.ArticleID)) } else { // Like: add to cache and database global.Redis.Set(context.Background(), cacheKey, "1", 0) like := database.ArticleLike{ ArticleID: req.ArticleID, UserUUID: req.UserUUID, CreatedAt: time.Now(), } global.DB.Create(&like) // Increment like count in cache global.Redis.Incr(context.Background(), fmt.Sprintf("article:likes:%s", req.ArticleID)) } return nil } ``` -------------------------------- ### Login User API (Bash) Source: https://context7.com/fischlvor/go_blog/llms.txt Authenticates a user via password and obtains an OAuth authorization code for SSO. Requires email, password, app_id, state, device details, captcha_id, and captcha. Returns an authorization code and redirect URI. ```bash curl -X POST http://localhost:8000/api/auth/login \ -H "Content-Type: application/json" \ -d '{ "email": "user@example.com", "password": "SecurePass123!", "app_id": "blog", "state": "base64-encoded-state-parameter", "device_id": "device-fingerprint-uuid", "device_name": "Chrome on Windows", "device_type": "browser", "captcha_id": "captcha-uuid-here", "captcha": "123456" }' ``` -------------------------------- ### Automated Deployment Script Source: https://context7.com/fischlvor/go_blog/llms.txt A bash script for automating the build, image saving/uploading, and remote deployment of Dockerized services. It requires Docker and SSH access to the remote server and assumes a specific project structure. ```bash #!/bin/bash # deploy.sh - Automated deployment script set -e # Configuration REMOTE_HOST="user@your-server.com" REMOTE_PATH="/opt/goblog" SERVICES=("server-blog" "server-auth" "web-blog" "web-auth" "nginx") # Build all Docker images build_images() { echo "=== Building Docker images ===" for service in "${SERVICES[@]}"; do echo "Building $service..." docker build -t goblog-$service:latest ./$service done } # Save and upload images upload_images() { echo "=== Uploading images to server ===" for service in "${SERVICES[@]}"; do echo "Saving $service image..." docker save goblog-$service:latest | gzip > /tmp/$service.tar.gz echo "Uploading $service image..." scp /tmp/$service.tar.gz $REMOTE_HOST:$REMOTE_PATH/images/ rm /tmp/$service.tar.gz done # Upload docker-compose files scp docker-compose*.yml $REMOTE_HOST:$REMOTE_PATH/ } # Deploy on remote server deploy() { echo "=== Deploying on remote server ===" ssh $REMOTE_HOST << 'ENDSSH' cd /opt/goblog # Load images for image in images/*.tar.gz; do echo "Loading $image..." docker load < $image done # Stop old containers docker-compose -f docker-compose.prod.yml down # Start new containers docker-compose -f docker-compose.base.yml up -d docker-compose -f docker-compose.prod.yml up -d # Clean up old images docker image prune -f echo "Deployment complete!" ENDSSH } ``` -------------------------------- ### Device Management Operations (Shell) Source: https://context7.com/fischlvor/go_blog/llms.txt Provides `curl` commands for managing user devices, including listing devices, kicking a specific device offline, and performing a global logout to disconnect all user devices. ```bash # Get user devices list curl -X GET "http://localhost:8000/api/device/list?page=1&page_size=10" \ -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." # Response { "code": 200, "data": { "list": [ { "id": 1, "device_id": "device-fingerprint-uuid", "device_name": "Chrome on Windows", "device_type": "browser", "app_name": "goBlog", "last_active_at": "2025-12-25T10:30:00Z", "is_current": true }, { "id": 2, "device_id": "another-device-uuid", "device_name": "Safari on iPhone", "device_type": "mobile", "app_name": "goBlog", "last_active_at": "2025-12-24T15:20:00Z", "is_current": false } ], "total": 2 } } # Kick specific device offline curl -X POST http://localhost:8000/api/device/kick \ -H "Authorization: Bearer access-token-here" \ -H "Content-Type: application/json" \ -d '{ "device_id": "device-fingerprint-uuid" }' # Global logout - kick all devices offline curl -X POST http://localhost:8000/api/auth/logout/all \ -H "Authorization: Bearer access-token-here" ``` -------------------------------- ### Token Exchange and Refresh (Shell) Source: https://context7.com/fischlvor/go_blog/llms.txt Demonstrates how to exchange an authorization code for JWT tokens or refresh an expired access token using `curl` requests. It shows the POST requests and expected JSON responses. ```bash # Exchange authorization code for tokens curl -X POST http://localhost:8000/api/auth/token \ -H "Content-Type: application/json" \ -d '{ "grant_type": "authorization_code", "code": "auth-code-uuid-here", "client_id": "blog", "client_secret": "your-app-secret", "redirect_uri": "http://localhost:5173/callback" }' # Response - JWT tokens with RSA signature { "code": 200, "data": { "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...", "refresh_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 7200 } } # Refresh expired access token curl -X POST http://localhost:8000/api/auth/token \ -H "Content-Type: application/json" \ -d '{ "grant_type": "refresh_token", "refresh_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...", "client_id": "blog", "client_secret": "your-app-secret" }' ``` -------------------------------- ### Nginx Configuration: Blog Frontend and API Proxy Source: https://context7.com/fischlvor/go_blog/llms.txt Configures Nginx to serve the blog frontend, redirect HTTP to HTTPS, and proxy API requests to the backend. It includes rate limiting for global and API requests, caching for static assets, and CORS headers for the API. ```nginx server { listen 80; server_name www.example.com; # Redirect HTTP to HTTPS return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name www.example.com; # SSL configuration ssl_certificate /etc/nginx/ssl/cert.pem; ssl_certificate_key /etc/nginx/ssl/key.pem; ssl_protocols TLSv1.2 TLSv1.3; # Global rate limiting limit_req zone=global burst=5000 nodelay; # Frontend static files location / { root /usr/share/nginx/html; try_files $uri $uri/ /index.html; # Cache static assets location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf)$ { expires 1y; add_header Cache-Control "public, immutable"; } } # API proxy to blog backend location /api/ { limit_req zone=api burst=100 nodelay; proxy_pass http://server-blog:8080/api/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # CORS headers add_header Access-Control-Allow-Origin * always; add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always; add_header Access-Control-Allow-Headers "Authorization, Content-Type" always; if ($request_method = OPTIONS) { return 204; } } # AI Chat streaming endpoint - disable buffering for SSE location /api/ai-chat/message/stream { proxy_pass http://server-blog:8080/api/ai-chat/message/stream; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; # SSE specific settings proxy_http_version 1.1; proxy_set_header Connection ""; proxy_buffering off; proxy_cache off; proxy_read_timeout 300s; chunked_transfer_encoding on; # Disable all buffering proxy_request_buffering off; proxy_buffering off; } } ``` -------------------------------- ### Create Comment API Request (Bash) Source: https://context7.com/fischlvor/go_blog/llms.txt Creates a new comment on an article. Supports top-level comments (parent_id: null) and replies to existing comments. Requires 'article_id', 'content', and optionally 'parent_id' and 'reply_to_uuid'. Authentication is handled via 'Authorization' header, and content type is JSON. ```bash # Create top-level comment curl -X POST http://localhost:8080/api/comment/create \ -H "Authorization: Bearer access-token-here" \ -H "Content-Type: application/json" \ -d '{ "article_id": "article-uuid-here", "content": "Great article! Very helpful explanation of Go interfaces.", "parent_id": null }' # Reply to comment curl -X POST http://localhost:8080/api/comment/create \ -H "Authorization: Bearer access-token-here" \ -H "Content-Type: application/json" \ -d '{ "article_id": "article-uuid-here", "content": "Thanks! I\'m glad it was helpful.", "parent_id": 789, "reply_to_uuid": "commenter-uuid-here" }' ``` -------------------------------- ### POST /api/auth/login - User Login with Password Source: https://context7.com/fischlvor/go_blog/llms.txt Authenticates a user using their email and password. Upon successful authentication, it returns an OAuth authorization code for the SSO flow. ```APIDOC ## POST /api/auth/login ### Description Authenticate user and obtain OAuth authorization code for SSO flow. ### Method POST ### Endpoint /api/auth/login ### Parameters #### Request Body - **email** (string) - Required - The email address of the user. - **password** (string) - Required - The user's password. - **app_id** (string) - Required - The unique identifier of the application. - **state** (string) - Optional - A value used to maintain state between the request and callback. - **device_id** (string) - Optional - A unique identifier for the user's device. - **device_name** (string) - Optional - A human-readable name for the device. - **device_type** (string) - Optional - The type of device (e.g., 'browser'). - **captcha_id** (string) - Required - The identifier for the CAPTCHA challenge. - **captcha** (string) - Required - The user's input for the CAPTCHA challenge. ### Request Example ```json { "email": "user@example.com", "password": "SecurePass123!", "app_id": "blog", "state": "base64-encoded-state-parameter", "device_id": "device-fingerprint-uuid", "device_name": "Chrome on Windows", "device_type": "browser", "captcha_id": "captcha-uuid-here", "captcha": "123456" } ``` ### Response #### Success Response (200) - **code** (integer) - Success status code. - **message** (string) - A success message. - **data** (object) - Contains authorization code and redirect information. - **code** (string) - The obtained OAuth authorization code. - **redirect_uri** (string) - The URI to redirect the user to. - **return_url** (string) - The intended return URL after successful login. #### Response Example ```json { "code": 200, "message": "success", "data": { "code": "auth-code-uuid-here", "redirect_uri": "http://localhost:5173/callback", "return_url": "http://localhost:5173/home" } } ``` ``` -------------------------------- ### Comment System API Source: https://context7.com/fischlvor/go_blog/llms.txt APIs for managing comments and replies on articles. ```APIDOC ## POST /api/comment/create ### Description Creates a new comment or a reply to an existing comment on an article. Supports nested replies. ### Method POST ### Endpoint `/api/comment/create` ### Parameters #### Request Body - **article_id** (string) - Required - The ID of the article the comment is associated with. - **content** (string) - Required - The content of the comment. - **parent_id** (integer) - Optional - The ID of the parent comment if this is a reply. Null for top-level comments. - **reply_to_uuid** (string) - Optional - The UUID of the user being replied to (used for nested replies). ### Request Example ```json { "article_id": "article-uuid-here", "content": "Great article! Very helpful explanation of Go interfaces.", "parent_id": null } ``` ### Response #### Success Response (200) - **code** (integer) - The status code of the response. - **msg** (string) - A message indicating success. - **data** (object) - The data payload. - **id** (integer) - The unique identifier of the created comment. - **created_at** (string) - The timestamp when the comment was created. #### Response Example ```json { "code": 200, "msg": "评论成功", "data": { "id": 789, "created_at": "2025-12-25T12:00:00Z" } } ``` ## GET /api/comment/list ### Description Retrieves a list of comments for a specific article with nested replies. Supports pagination. ### Method GET ### Endpoint `/api/comment/list` ### Parameters #### Query Parameters - **article_id** (string) - Required - The ID of the article to retrieve comments for. - **page** (integer) - Optional - The page number to retrieve. - **page_size** (integer) - Optional - The number of comments per page. ### Request Example ```bash curl -X GET "http://localhost:8080/api/comment/list?article_id=article-uuid-here&page=1&page_size=20" \ -H "Authorization: Bearer access-token-here" ``` ### Response #### Success Response (200) - **code** (integer) - The status code of the response. - **data** (object) - The data payload. - **list** (array) - A list of comment objects, potentially with nested replies. - **id** (integer) - The unique identifier of the comment. - **user** (object) - Information about the user who posted the comment. - **uuid** (string) - The user's UUID. - **nickname** (string) - The user's nickname. - **avatar** (string) - The URL of the user's avatar. - **content** (string) - The content of the comment. - **likes** (integer) - The number of likes the comment has received. - **created_at** (string) - The timestamp when the comment was created. - **replies** (array) - An array of reply objects (nested comments). - **id** (integer) - The unique identifier of the reply. - **user** (object) - Information about the user who posted the reply. - **reply_to** (object) - Information about the user being replied to. - **uuid** (string) - The UUID of the user being replied to. - **nickname** (string) - The nickname of the user being replied to. - **content** (string) - The content of the reply. - **likes** (integer) - The number of likes the reply has received. - **created_at** (string) - The timestamp when the reply was created. - **total** (integer) - The total number of comments available. #### Response Example ```json { "code": 200, "data": { "list": [ { "id": 789, "user": { "uuid": "user-uuid-here", "nickname": "John Doe", "avatar": "https://cdn.example.com/avatars/john.jpg" }, "content": "Great article! Very helpful explanation of Go interfaces.", "likes": 5, "created_at": "2025-12-25T12:00:00Z", "replies": [ { "id": 790, "user": { "uuid": "author-uuid", "nickname": "Article Author", "avatar": "https://cdn.example.com/avatars/author.jpg" }, "reply_to": { "uuid": "user-uuid-here", "nickname": "John Doe" }, "content": "Thanks! I'm glad it was helpful.", "likes": 2, "created_at": "2025-12-25T12:05:00Z" } ] } ], "total": 1 } } ``` ``` -------------------------------- ### AI Chat Session API Source: https://context7.com/fischlvor/go_blog/llms.txt APIs for managing AI chat sessions, including creating new sessions and sending messages. ```APIDOC ## POST /api/ai-chat/session ### Description Initializes a new AI chat session, allowing users to select a model for their conversation. ### Method POST ### Endpoint /api/ai-chat/session ### Parameters #### Request Body - **title** (string) - Required - The title for the new chat session. - **model** (string) - Required - The AI model to be used for the session. #### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Content-Type** (string) - Required - application/json ### Request Example ```json { "title": "Go Programming Questions", "model": "deepseek-chat" } ``` ### Response #### Success Response (200) - **code** (integer) - The status code of the response. - **data** (object) - Contains details of the created chat session. - **id** (integer) - The unique identifier for the chat session. - **title** (string) - The title of the chat session. - **model** (string) - The AI model used in the session. - **created_at** (string) - The timestamp when the session was created. ### Response Example ```json { "code": 200, "data": { "id": 123, "title": "Go Programming Questions", "model": "deepseek-chat", "created_at": "2025-12-25T10:30:00Z" } } ``` ``` ```APIDOC ## POST /api/ai-chat/message/stream ### Description Sends a message to an active AI chat session and receives a streaming response using Server-Sent Events (SSE). ### Method POST ### Endpoint /api/ai-chat/message/stream ### Parameters #### Request Body - **session_id** (integer) - Required - The ID of the chat session to send the message to. - **content** (string) - Required - The message content to send to the AI. #### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Content-Type** (string) - Required - application/json ### Request Example ```json { "session_id": 123, "content": "Explain Go interfaces and how they differ from other languages" } ``` ### Response #### Success Response (200) - The response is streamed using Server-Sent Events (SSE). - Each event contains a `chunk` field with a part of the AI's response. - A final `done` event indicates the completion of the response. ### Response Example (SSE Stream) ``` data: {"chunk": "Go interfaces are"} data: {"chunk": " a powerful feature"} data: {"chunk": " that provides"} data: {"chunk": " implicit implementation"} data: {"done": true, "message_id": 456} ``` ``` -------------------------------- ### Blog Article API Source: https://context7.com/fischlvor/go_blog/llms.txt API endpoints for managing blog articles, including creation and potentially other CRUD operations. ```APIDOC ## POST /api/articles ### Description Publish a new blog article. This endpoint accepts article content in Markdown format along with associated metadata. It handles the storage and retrieval of blog posts. ### Method POST ### Endpoint /api/articles ### Parameters #### Request Body - **title** (string) - Required - The title of the blog article. - **content_markdown** (string) - Required - The main content of the article in Markdown format. - **author_uuid** (string) - Required - The unique identifier of the author. - **tags** (array of strings) - Optional - A list of tags associated with the article. - **is_published** (boolean) - Optional - Whether the article should be published immediately. Defaults to false. ### Request Example ```json { "title": "My First Go Blog Post", "content_markdown": "# Hello World!\n\nThis is my first blog post written in Markdown.", "author_uuid": "user-uuid-123", "tags": ["golang", "blogging"], "is_published": true } ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier of the newly created article. - **title** (string) - The title of the article. - **created_at** (string) - ISO 8601 timestamp of when the article was created. - **updated_at** (string) - ISO 8601 timestamp of when the article was last updated. #### Response Example ```json { "id": "article-uuid-456", "title": "My First Go Blog Post", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Check Article Like Status (API) Source: https://context7.com/fischlvor/go_blog/llms.txt Checks if a user has liked a specific article via an API endpoint. It requires the article ID and an authorization token. The API returns a JSON response indicating the like status. ```bash curl -X GET "http://localhost:8080/api/article/isLike?article_id=article-uuid-here" \ -H "Authorization: Bearer access-token-here" ``` -------------------------------- ### Check if user liked article Source: https://context7.com/fischlvor/go_blog/llms.txt Retrieves whether a specific user has liked a given article. This endpoint is useful for displaying like status on article pages. ```APIDOC ## GET /api/article/isLike ### Description Checks if a user has liked a specific article. ### Method GET ### Endpoint /api/article/isLike ### Parameters #### Query Parameters - **article_id** (string) - Required - The unique identifier of the article. #### Headers - **Authorization** (string) - Required - Bearer token for authentication. ### Response #### Success Response (200) - **code** (integer) - The status code of the response. - **data** (boolean) - Indicates whether the user has liked the article. ### Response Example ```json { "code": 200, "data": true } ``` ``` -------------------------------- ### AI Chat Sessions API Source: https://context7.com/fischlvor/go_blog/llms.txt Retrieve a list of AI chat sessions with pagination support. ```APIDOC ## GET /api/ai-chat/sessions ### Description Retrieves a list of AI chat sessions. Supports pagination. ### Method GET ### Endpoint `/api/ai-chat/sessions` ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. - **pageSize** (integer) - Optional - The number of sessions per page. ### Request Example ```bash curl -X GET "http://localhost:8080/api/ai-chat/sessions?page=1&pageSize=10" \ -H "Authorization: Bearer access-token-here" ``` ### Response #### Success Response (200) - **code** (integer) - The status code of the response. - **data** (object) - The data payload. - **list** (array) - A list of chat session objects. - **id** (integer) - The unique identifier of the session. - **title** (string) - The title of the chat session. - **model** (string) - The AI model used for the session. - **message_count** (integer) - The number of messages in the session. - **created_at** (string) - The timestamp when the session was created. - **updated_at** (string) - The timestamp when the session was last updated. - **total** (integer) - The total number of sessions available. #### Response Example ```json { "code": 200, "data": { "list": [ { "id": 123, "title": "Go Programming Questions", "model": "deepseek-chat", "message_count": 12, "created_at": "2025-12-25T10:30:00Z", "updated_at": "2025-12-25T11:45:00Z" } ], "total": 1 } } ``` ``` -------------------------------- ### Token Exchange and Frontend Callback (TypeScript) Source: https://context7.com/fischlvor/go_blog/llms.txt Handles the frontend callback after user login, exchanges the authorization code for access and refresh tokens, and stores them in local storage. It uses the Vue Router to navigate to the home page upon successful token retrieval. ```typescript import { useRoute, useRouter } from 'vue-router' const route = useRoute() const router = useRouter() const code = route.query.code as string const redirectUri = route.query.redirect_uri as string // Exchange authorization code for access token const exchangeToken = async () => { try { const response = await fetch('http://localhost:8000/api/auth/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ grant_type: 'authorization_code', code: code, client_id: 'blog', client_secret: 'your-app-secret', redirect_uri: redirectUri }) }) const result = await response.json() if (result.code === 200) { localStorage.setItem('access_token', result.data.access_token) localStorage.setItem('refresh_token', result.data.refresh_token) router.push('/home') } } catch (error) { console.error('Token exchange failed:', error) } } ``` -------------------------------- ### POST /api/auth/register - User Registration Source: https://context7.com/fischlvor/go_blog/llms.txt Registers a new user account in the SSO system. Upon successful registration, the user is automatically authorized for the specified application. ```APIDOC ## POST /api/auth/register ### Description Register a new user account in the SSO system with automatic application authorization. ### Method POST ### Endpoint /api/auth/register ### Parameters #### Request Body - **email** (string) - Required - The email address of the user. - **password** (string) - Required - The password for the new user account. - **nickname** (string) - Required - The display name of the user. - **app_id** (string) - Required - The unique identifier of the application requesting registration. - **captcha_id** (string) - Required - The identifier for the CAPTCHA challenge. - **captcha** (string) - Required - The user's input for the CAPTCHA challenge. ### Request Example ```json { "email": "user@example.com", "password": "SecurePass123!", "nickname": "John Doe", "app_id": "blog", "captcha_id": "captcha-uuid-here", "captcha": "123456" } ``` ### Response #### Success Response (200) - **code** (integer) - Success status code. - **message** (string) - A message indicating successful registration. - **data** (null) - No data returned on successful registration. #### Response Example ```json { "code": 200, "message": "注册成功,请登录", "data": null } ``` ``` -------------------------------- ### JWT Verification Middleware (Go) Source: https://context7.com/fischlvor/go_blog/llms.txt A Go middleware function for Gin that verifies JWTs from the Authorization header. It extracts claims, sets user and app information in the context, and aborts the request with a 401 error if the token is invalid. ```go // JWT verification in blog service (Go) // server-blog/internal/middleware/jwt.go import ( "server/pkg/jwt" "github.com/gin-gonic/gin" ) func JWTAuth() gin.HandlerFunc { return func(c *gin.Context) { token := c.GetHeader("Authorization") token = strings.TrimPrefix(token, "Bearer ") // Verify JWT using SSO public key (RSA) claims, err := jwt.ParseToken(token) if err != nil { c.JSON(401, gin.H{"error": "Invalid token"}) c.Abort() return } c.Set("user_uuid", claims.UserUUID) c.Set("app_id", claims.AppID) c.Next() } } ```