Skip to content

Ely0rda/SnippetBox-Web-Application

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SnippetBox Web Application

Go Version License

A secure web application for creating, storing, and sharing text snippets with authentication.

Table of Contents

Overview

SnippetBox is a full-featured web application that allows users to create, view, and manage text snippets. Each snippet has a custom expiry time, ensuring that content remains relevant and the database stays clean. The application implements secure user authentication, CSRF protection, and follows best practices for web development with Go.

Tech Stack

  • Backend: Go 1.19
  • Database: MySQL
  • Web Framework: Custom HTTP routing with Pat and Alice middleware chaining
  • Frontend: HTML, CSS, JavaScript
  • Security: HTTPS with TLS, CSRF protection, secure sessions
  • Authentication: Bcrypt for password hashing
  • Session Management: golangcollege/sessions

Architecture

SnippetBox follows a clean, well-structured monolithic architecture with clear separation of concerns:

  • cmd/web: Application entrypoint, handlers, middleware, and web-specific code
  • pkg/models: Data models and database interactions
  • pkg/forms: Form validation logic
  • ui/html: HTML templates with Go's templating engine
  • ui/static: Static assets (CSS, JS, images)

The application uses dependency injection for better testability and follows the MVC pattern.

Key Features

  1. User Authentication System: Secure signup, login, and logout functionality with password hashing.
  2. CRUD Operations for Snippets: Create, read, and automatic deletion of snippets after expiry time.
  3. Security Features: HTTPS, CSRF protection, secure headers, SQL injection prevention, and session management.
  4. Form Validation: Server-side validation with friendly error messages.
  5. Template Caching: Efficient template rendering with a cache system.

Installation

  1. Clone the repository:

    git clone https://github.com/Ely0rda/SnippetBox-Web-Application.git
    cd SnippetBox-Web-Application
  2. Set up the MySQL database:

    # Log into MySQL
    mysql -u root -p
    
    # Create database and user
    CREATE DATABASE snippetbox CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    CREATE USER 'web'@'localhost' IDENTIFIED BY 'sparkle';
    GRANT ALL PRIVILEGES ON snippetbox.* TO 'web'@'localhost';
    
    # Create snippets table
    USE snippetbox;
    CREATE TABLE snippets (
        id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
        title VARCHAR(100) NOT NULL,
        content TEXT NOT NULL,
        created DATETIME NOT NULL,
        expires DATETIME NOT NULL
    );
    
    # Create index
    CREATE INDEX idx_snippets_created ON snippets(created);
    
    # Create users table
    CREATE TABLE users (
        id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(255) NOT NULL,
        email VARCHAR(255) NOT NULL,
        hashed_password CHAR(60) NOT NULL,
        created DATETIME NOT NULL,
        CONSTRAINT users_uc_email UNIQUE (email)
    );
  3. Generate TLS certificate:

    mkdir tls
    cd tls
    
    # Generate private key and self-signed certificate
    go run /usr/local/go/src/crypto/tls/generate_cert.go --rsa-bits=2048 --host=localhost

Usage

  1. Start the application:

    go run ./cmd/web
  2. Open your browser and navigate to https://localhost:4000

  3. You can customize the application by modifying the flags:

    # Change the port and DSN
    go run ./cmd/web -addr=":8080" -dsn="web:password@/snippetbox?parseTime=true"

Testing

The project includes unit tests for core functionality:

# Run all tests
go test -v ./...

# Run specific tests
go test -v ./cmd/web

Example of testing the human date formatting function:

func TestHumanDate(t *testing.T) {
    tests := []struct {
        name string
        tm   time.Time
        want string
    }{
        {
            name: "UTC",
            tm:   time.Date(2020, 12, 17, 10, 0, 0, 0, time.UTC),
            want: "17 Dec 2020 at 10:00",
        },
        // Additional test cases...
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            hd := humanDate(tt.tm)
            if hd != tt.want {
                t.Errorf("want %q; got %q", tt.want, hd)
            }
        })
    }
}

Skills Demonstrated

  • Go Web Development: Building a complete web application with Go's standard library and minimal third-party packages
  • Security Implementation: HTTPS, secure cookies, password hashing, CSRF protection, and other security best practices
  • Database Management: SQL queries, transaction management, and connection pooling with Go's database/sql package
  • Authentication System: Complete user authentication workflow with signup, login, and session management
  • Clean Architecture: Well-structured codebase with clear separation of concerns and dependency injection
  • Error Handling: Comprehensive error handling and user-friendly error messages
  • Testing: Unit testing critical application components

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contact

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published