proton

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 27, 2024 License: MIT Imports: 12 Imported by: 0

README

Proton

Proton is a lightweight web framework for building HTTP servers in Go. It provides a simple and elegant way to define routes, handle middleware, and interact with databases. This tutorial will guide you through the basics of setting up and using Proton for your web applications.

Installation

To get started with Proton, you need to have Go installed on your system. You can install Proton and its dependencies using go get:

go get git.triegebauer.at/triegebauer/proton-go

This will fetch the Proton package and its dependencies and install them on your system.

Getting Started

Let's create a simple web server using Proton:

package main

import (
	"git.triegebauer.at/triegebauer/proton-go"
	"net/http"
)

func main() {
	// Create a new Proton instance
	app := proton.New()

	// Define a route
	app.GET("/", func(ctx *proton.Context) error {
		return ctx.WriteString(http.StatusOK, "Hello, Proton!")
	})

	// Start the server
	if err := app.Start(":8080"); err != nil {
		panic(err)
	}
}

Save this code in a file named main.go and run it with go run main.go. You should now have a web server running on http://localhost:8080 that responds with "Hello, Proton!" to any GET requests to the root path ("/").

Routing

Proton allows you to define routes for different HTTP methods such as GET, POST, PUT, DELETE, etc. Here's how you can define routes with different methods:

// Define routes
app.GET("/users", getUsersHandler)
app.POST("/users", createUserHandler)
app.PUT("/users/:id", updateUserHandler)
app.DELETE("/users/:id", deleteUserHandler)

In the above example, we have defined routes for retrieving, creating, updating, and deleting users.

Middleware

Middleware functions are used to perform common tasks such as logging, authentication, etc., before executing the main handler. Proton allows you to define middleware functions and apply them to specific routes or to all routes globally.

// Define a middleware
func loggingMiddleware(next proton.Handler) proton.Handler {
	return func(ctx *proton.Context) error {
		// Perform logging
		log.Println("Logging request:", ctx.request.Method, ctx.request.URL.Path)

		// Call the next handler
		return next(ctx)
	}
}

// Apply middleware to a specific route
app.GET("/users", getUsersHandler, loggingMiddleware)

// Apply middleware globally
app.UseMiddleware(loggingMiddleware)

In the above example, we have defined a logging middleware function and applied it to a specific route and globally to all routes.

Database Integration

Proton makes it easy to integrate with databases using the GORM ORM library. You can create database connections and perform migrations with just a few lines of code.

// Create a new  database instance
db := proton.NewMySQLDatabase(proton.MySQLConfig{
    DBHost:     "localhost",
    DBPort:     3306,
    DBName:     "your_database",
    DBUsername: "your_username",
    DBPassword: "your_password",
})

// Migrate database models
db.Migrate(&User{})

In the above example, we have created a MySQL database instance and performed migrations for the User model.

Static File Serving

Proton allows you to serve static files such as HTML, CSS, JavaScript, etc., from a specified directory.

// Serve static files
app.Static("/static", "./static")

In the above example, all requests to the /static path will be served from the static directory.

Conclusion

This tutorial covered the basics of setting up and using the Proton web framework for building HTTP servers in Go. Proton provides a simple and efficient way to define routes, handle middleware, integrate with databases, and serve static files. Explore the official documentation for more advanced features and best practices.

For more information, refer to the Proton GitHub repository and the GORM documentation.

Happy coding with Proton! 🚀

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	Database *Database
	// contains filtered or unexported fields
}

Context represents the context of an HTTP request.

func (*Context) Bind added in v0.1.1

func (ctx *Context) Bind(target interface{}) error

Bind binds data automatically from the HTTP request body to the provided target struct by the content type.

func (*Context) BindJSON

func (ctx *Context) BindJSON(target interface{}) error

BindJSON binds JSON data from the HTTP request body to the provided target struct by decoding it.

func (*Context) Get

func (ctx *Context) Get(key string) any

Get retrieves a value from the context given its key.

func (*Context) GetFormValue

func (ctx *Context) GetFormValue(name string) (string, error)

GetFormValue retrieves a form value from the request by name.

func (*Context) GetQueryParam

func (ctx *Context) GetQueryParam(name string) (string, error)

GetQueryParam retrieves a query parameter from the request URL by name.

func (*Context) GetRouteParam

func (ctx *Context) GetRouteParam(name string) (string, error)

GetRouteParam retrieves a parameter from the request route by name.

func (*Context) Set

func (ctx *Context) Set(key string, value any)

Set sets a key-value pair in the context.

func (*Context) WriteJSON

func (ctx *Context) WriteJSON(statusCode int, j JSON) error

WriteJSON writes JSON data to the response writer with the specified status code.

func (*Context) WriteString

func (ctx *Context) WriteString(statusCode int, s string) error

WriteString writes a string to the response writer with the specified status code.

type DBModel

type DBModel struct {
	ID        uint           `json:"id" gorm:"primarykey"`
	CreatedAt time.Time      `json:"-"`
	UpdatedAt time.Time      `json:"-"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

DBModel defines common fields for database models.

type DBType

type DBType string

DBType represents types of supported databases.

const (
	// SQLite represents the SQLite database type.
	SQLite DBType = "sqlite"
	// MySQL represents the MySQL database type.
	MySQL DBType = "mysql"
	// PostgreSQL represents the PostgreSQL database type.
	PostgreSQL DBType = "postgresql"
)

type Database

type Database struct {
	ORM *gorm.DB
}

Database represents a database connection.

func NewMySQLDatabase

func NewMySQLDatabase(cfg MySQLConfig) *Database

NewMySQLDatabase creates a new MySQL database instance based on the provided configuration.

func NewPostgreSQLDatabase

func NewPostgreSQLDatabase(cfg PostgreSQLConfig) *Database

NewPostgreSQLDatabase creates a new PostgreSQL database instance based on the provided configuration.

func NewSQLiteDatabase

func NewSQLiteDatabase(cfg SQLiteConfig) *Database

NewSQLiteDatabase creates a new SQLite database instance based on the provided configuration.

func (*Database) Migrate

func (db *Database) Migrate(model interface{})

Migrate performs database migrations for the provided model.

type Handler

type Handler func(ctx *Context) error

Handler represents a handler function for HTTP requests.

type JSON

type JSON map[string]any

JSON represents a JSON object.

type Middleware

type Middleware func(next Handler) Handler

Middleware represents a middleware function for handling HTTP requests.

type MySQLConfig

type MySQLConfig struct {
	DBHost     string
	DBPort     int
	DBName     string
	DBUsername string
	DBPassword string
}

MySQLConfig represents configuration parameters for MySQL database.

type PostgreSQLConfig

type PostgreSQLConfig struct {
	DBHost     string
	DBPort     int
	DBName     string
	DBUsername string
	DBPassword string
}

PostgreSQLConfig represents configuration parameters for PostgreSQL database.

type Proton

type Proton struct {
	// contains filtered or unexported fields
}

Proton represents an HTTP server.

func New

func New() *Proton

New creates a new instance of Proton.

func NewWithDatabase

func NewWithDatabase(db *Database) *Proton

NewWithDatabase creates a new instance of Proton with a specified database.

func (*Proton) DELETE

func (p *Proton) DELETE(path string, handler Handler, middlewares ...Middleware)

DELETE registers a DELETE route with the router.

func (*Proton) GET

func (p *Proton) GET(path string, handler Handler, middlewares ...Middleware)

GET registers a GET route with the router.

func (*Proton) HEAD

func (p *Proton) HEAD(path string, handler Handler, middlewares ...Middleware)

HEAD registers a HEAD route with the router.

func (*Proton) OPTIONS

func (p *Proton) OPTIONS(path string, handler Handler, middlewares ...Middleware)

OPTIONS registers an OPTIONS route with the router.

func (*Proton) PATCH

func (p *Proton) PATCH(path string, handler Handler, middlewares ...Middleware)

PATCH registers a PATCH route with the router.

func (*Proton) POST

func (p *Proton) POST(path string, handler Handler, middlewares ...Middleware)

POST registers a POST route with the router.

func (*Proton) PUT

func (p *Proton) PUT(path string, handler Handler, middlewares ...Middleware)

PUT registers a PUT route with the router.

func (*Proton) Start

func (p *Proton) Start(address string) error

Start starts the HTTP server.

func (*Proton) Static

func (p *Proton) Static(path string, dirPath string)

Static serves static files from a directory.

func (*Proton) UseMiddleware

func (p *Proton) UseMiddleware(middlewares ...Middleware)

UseMiddleware adds middlewares to the Proton instance.

type SQLiteConfig

type SQLiteConfig struct {
	DBFile string
}

SQLiteConfig represents configuration parameters for SQLite database.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL