+
Skip to content

ZiyanK/backend

Repository files navigation

Go Textbook API

A Go implementation of the textbook management and Gemini AI integration API using Gin framework and MongoDB.

Features

  • Textbook Management: Create and manage textbooks with detailed table of contents
  • Google Gemini AI Integration: Query AI with specific textbook sections for educational assistance
  • Role-based Authentication: JWT-based authentication with teacher and student roles
  • MongoDB Integration: Efficient document storage and retrieval
  • RESTful API: Clean and consistent API design with proper HTTP status codes

Quick Start

Prerequisites

  • Go 1.21 or higher
  • MongoDB running locally or connection string
  • Google Gemini API key

Installation

  1. Clone and setup:
cd go-api
go mod tidy
  1. Environment Setup:
cp .env.example .env
# Edit .env file with your configuration
  1. Run the server:
go run main.go

The server will start on http://localhost:8080

API Endpoints

Authentication

Register User

POST /api/v1/auth/register
Content-Type: application/json

{
  "email": "teacher@example.com",
  "full_name": "John Doe",
  "password": "password123",
  "role": "teacher"
}

Login

POST /api/v1/auth/login
Content-Type: application/json

{
  "email": "teacher@example.com",
  "password": "password123"
}

Teacher Endpoints

Create Textbook

POST /api/v1/teacher/textbooks
Authorization: Bearer <jwt_token>
Content-Type: application/json

{
  "class": 10,
  "subject": "Science",
  "medium": "English",
  "chapters": [
    {
      "chapter_number": 1,
      "title": "Chemical Reactions and Equations",
      "sections": [
        "1.1 Chemical Equation",
        "1.2 Balanced Chemical Equation"
      ]
    }
  ]
}

Get Teacher's Textbooks

GET /api/v1/teacher/textbooks
Authorization: Bearer <jwt_token>

Get Specific Textbook

GET /api/v1/teacher/textbooks/{textbook_id}
Authorization: Bearer <jwt_token>

Common Endpoints (All Users)

Get All Textbooks

GET /api/v1/common/textbooks
Authorization: Bearer <jwt_token>

Get Textbook by ID

GET /api/v1/common/textbooks/{textbook_id}
Authorization: Bearer <jwt_token>

Query Gemini with Sections

POST /api/v1/common/textbooks/query-sections
Authorization: Bearer <jwt_token>
Content-Type: application/json

{
  "textbook_id": "textbook_id_here",
  "selected_sections": [
    "1.1 Chemical Equation",
    "1.2 Balanced Chemical Equation"
  ],
  "custom_prompt": "Explain the difference between chemical equations and balanced equations for Class 10 students"
}

Project Structure

go-api/
├── main.go                     # Application entry point
├── go.mod                      # Go module definition
├── go.sum                      # Go module checksums
├── .env.example               # Environment variables template
├── sample_textbook_data.json  # Sample data for testing
├── README.md                  # This file
├── internal/                  # Private application code
│   ├── config/               # Configuration management
│   │   └── config.go
│   ├── database/             # Database connection
│   │   └── database.go
│   ├── handlers/             # HTTP request handlers
│   │   ├── auth.go
│   │   └── textbook.go
│   ├── middleware/           # HTTP middleware
│   │   └── auth.go
│   ├── models/               # Data models
│   │   ├── textbook.go
│   │   └── user.go
│   └── services/             # Business logic
│       └── gemini.go
└── pkg/                      # Public utility packages
    └── utils/
        └── auth.go

Configuration

Environment variables:

Variable Description Default
PORT Server port 8080
ENVIRONMENT Environment mode development
MONGODB_URL MongoDB connection string mongodb://localhost:27017
MONGODB_DB_NAME MongoDB database name clarity_education
SECRET_KEY JWT secret key dev_secret_key_123_change_this_in_production
ACCESS_TOKEN_EXPIRE_MINUTES JWT token expiration 30
GEMINI_API_KEY Google Gemini API key (required for AI features)

Dependencies

  • Gin: HTTP web framework
  • MongoDB Driver: Official MongoDB Go driver
  • JWT: JWT token handling
  • Bcrypt: Password hashing
  • Godotenv: Environment variable loading

Testing

Health Check

curl http://localhost:8080/health

Register a Teacher

curl -X POST http://localhost:8080/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "teacher@example.com",
    "full_name": "Test Teacher",
    "password": "password123",
    "role": "teacher"
  }'

Create a Textbook

# Use the token from registration
curl -X POST http://localhost:8080/api/v1/teacher/textbooks \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d @sample_textbook_data.json

Differences from Python Version

Architecture

  • Go Gin instead of Python FastAPI
  • Standard library JSON instead of Pydantic
  • MongoDB Driver instead of Motor (async)
  • Native HTTP client for Gemini API instead of google-generativeai library

Performance Benefits

  • Compiled binary - faster startup and execution
  • Built-in concurrency - better handling of concurrent requests
  • Lower memory footprint - more efficient resource usage
  • Static typing - compile-time error checking

API Compatibility

  • Same endpoints - identical API structure
  • Same request/response format - compatible with existing clients
  • Same authentication - JWT-based auth with same claims
  • Same database schema - uses identical MongoDB collections

Getting Gemini API Key

  1. Go to Google AI Studio
  2. Create a new API key
  3. Add it to your .env file as GEMINI_API_KEY=your_key_here

Error Handling

The API returns standard HTTP status codes:

  • 200 - Success
  • 201 - Created
  • 400 - Bad Request (validation errors)
  • 401 - Unauthorized (authentication required)
  • 403 - Forbidden (insufficient permissions)
  • 404 - Not Found
  • 409 - Conflict (duplicate resource)
  • 500 - Internal Server Error
  • 503 - Service Unavailable (external service error)

Security Features

  • JWT Authentication - Secure token-based authentication
  • Password Hashing - Bcrypt for secure password storage
  • Role-based Access - Teacher/student role separation
  • CORS Support - Configurable cross-origin resource sharing
  • Input Validation - Request validation using Gin binding

Production Deployment

  1. Set environment to production:
export ENVIRONMENT=production
  1. Use production MongoDB:
export MONGODB_URL=mongodb://your-production-mongo
  1. Build binary:
go build -o textbook-api main.go
  1. Run binary:
./textbook-api

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

This project is licensed under the MIT License.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载