gopeach

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2023 License: MIT Imports: 13 Imported by: 0

README ΒΆ

πŸ‘ GoPeach

GoPeach is a fasthttp based framework πŸ˜ƒ made to simplify fasthttp while keeping its performance.
GoPeach also integrats a database structure to allow you to implement gorm easily.

go get -u github.com/Cypaaa/gopeach

Quickstart

package main

import (
    "github.com/Cypaaa/gopeach"
)

func main() {
    app := gopeach.New()

    app.Get("/", func(ctx *gopeach.RequestCtx) {
      ctx.Send("Hello World!")
    })

    app.Listen(":8080")
}

πŸ”’ JWT and Scrypt

GoPeach implements 4 functions to help you use JWT (EdDSA) and Scrypt.

  • JWT: GenerateJWT, VerifyJWT
  • Scrypt: Hash, CompareHash

You will find examples in the example directory.

πŸ‘¨β€πŸ’»πŸ‘©β€πŸ’» Middlewares

You can add custom or community made middlewares!
They handle a request in order they are defined.
Your first middleware will be executed before your second one which itself will execute before your handler

func main() {
    app := gopeach.New()

    // Your first middleware
    app.Middleware(func(ctx *gopeach.RequestCtx) {
        fmt.Println("This is your first middleware")

        // Pass to the next handler only if method is "GET"
        // else the request won't be handled anymore
        if ctx.MethodString() == "GET" {
            ctx.Next()
            return
        }
    })

    // Your second middleware
    app.Middleware(func(ctx *gopeach.RequestCtx) {
        fmt.Println("This is your second one")
        ctx.Next()
    })

    // Get all routes
    app.Get("/", func(ctx *gopeach.RequestCtx) {
        ctx.Send("Hello World!")
    })

    app.Listen(":8080")
}

πŸ““ Database

func main() {
    godotenv.Load()

    // Dialector
    dns := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
        os.Getenv("DB_USER"),
        os.Getenv("DB_PASSWORD"),
        os.Getenv("DB_HOST"),
        os.Getenv("DB_PORT"),
        os.Getenv("DB_NAME"),
    )
    dialector := mysql.Open(dns)
    
    // Database
    db, err := gopeach.NewDatabase(dialector)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()
    err = db.Migrate(
        models.MyModelTest{},
        // ...
    )
    if err != nil {
        log.Fatal(err)
    }
}

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	// DefaultSaltLength is the default salt length.
	DefaultSaltLength = 32
	// DefaultHashLength is the default hash length.
	DefaultHashLength = 64
)

Variables ΒΆ

This section is empty.

Functions ΒΆ

func CompareHash ΒΆ

func CompareHash(s, hash string) (bool, error)

Compare compares a string and a hash.

func GenerateJWT ΒΆ

func GenerateJWT(jwtSecretKey ed25519.PrivateKey, mc jwtv5.MapClaims) (string, error)

Generate generates a JWT token. It takes a jwtSecretKey string and a struct (interface{}) jwtSecretKey must be EdDSA private key and returns a token and an error.

func Hash ΒΆ

func Hash(s string) (string, error)

Hash hashes a string.

func VerifyJWT ΒΆ

func VerifyJWT(jwtSecretKey ed25519.PublicKey, token string, opts ...jwtv5.ParserOption) (jwtv5.MapClaims, error)

Verify verifies a JWT token. It takes a jwtSecretKey string and a token string

Types ΒΆ

type App ΒΆ

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

App stores Routes and middlewares

func New ΒΆ

func New() *App

New returns a new App

func (*App) CaseSensitive ΒΆ

func (r *App) CaseSensitive(b bool)

CaseSensitive sets if the routes should be checked with case sensitivity

func (*App) Delete ΒΆ

func (r *App) Delete(s string, h func(ctx *RequestCtx))

Delete adds DELETE Route.

func (*App) Get ΒΆ

func (r *App) Get(s string, h func(ctx *RequestCtx))

Get adds GET Route

func (*App) Handler ΒΆ

func (r *App) Handler(ctx *fasthttp.RequestCtx)

Handler handles requests

func (*App) Listen ΒΆ

func (r *App) Listen(addr string) error

Listen listens on addr

func (*App) ListenTLS ΒΆ

func (r *App) ListenTLS(addr, certFile, keyFile string) error

ListenTLS listens on addr with certFile and keyFile

func (*App) Middleware ΒΆ

func (r *App) Middleware(h func(ctx *RequestCtx))

Middleware adds middleware

func (*App) Patch ΒΆ

func (r *App) Patch(s string, h func(ctx *RequestCtx))

Patch adds PATCH Route

func (*App) Post ΒΆ

func (r *App) Post(s string, h func(ctx *RequestCtx))

Post adds POST Route

func (*App) Put ΒΆ

func (r *App) Put(s string, h func(ctx *RequestCtx))

Put adds PUT Route

type Database ΒΆ

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

Database struct

func NewDatabase ΒΆ

func NewDatabase(dialector gorm.Dialector) (*Database, error)

NewDatabase creates a new database connection

func (*Database) Close ΒΆ

func (d *Database) Close() error

Close closes the database connection

func (*Database) Conn ΒΆ

func (d *Database) Conn() *gorm.DB

Conn returns the database connection

func (*Database) Delete ΒΆ

func (d *Database) Delete(i interface{}) error

Delete deletes the model (soft delete: set deleted_at field)

func (*Database) DeleteByQuery ΒΆ

func (d *Database) DeleteByQuery(i interface{}, query interface{}, args ...interface{}) error

DeleteByQuery deletes the model by query

func (*Database) Destroy ΒΆ

func (d *Database) Destroy(i interface{}) error

Destroy destroys the model (hard delete: delete entry from database)

func (*Database) Find ΒΆ

func (d *Database) Find(i interface{}) error

Find finds the models

func (*Database) FindByQuery ΒΆ

func (d *Database) FindByQuery(i interface{}, query interface{}, args ...interface{}) error

FindByQuery finds the model by query

func (*Database) FindCond ΒΆ

func (d *Database) FindCond(i, c interface{}) error

FindCond finds the models by custom condition from the same structure

func (*Database) First ΒΆ

func (d *Database) First(i, c interface{}) error

First finds the first model by custom cudition from the same structure (findOne)

func (*Database) FirstByQuery ΒΆ

func (d *Database) FirstByQuery(i interface{}, query interface{}, args ...interface{}) error

FirstByQuery finds the first model by query (findOne)

func (*Database) Init ΒΆ

func (d *Database) Init() error

Init initializes the database connection

func (*Database) Migrate ΒΆ

func (d *Database) Migrate(i ...interface{}) error

Migrate migrates the database

func (*Database) Save ΒΆ

func (d *Database) Save(i interface{}) error

Save saves the model

type HTTPResponse ΒΆ

type HTTPResponse struct {
	Timestamp int64
	Status    int
	Error     string
	Message   string
	Path      string
}

Error represents an http error.

func NewHTTPResponse ΒΆ

func NewHTTPResponse() *HTTPResponse

NewError returns a new Error.

func (*HTTPResponse) Accepted ΒΆ

func (e *HTTPResponse) Accepted(message, path string) *HTTPResponse

Accepted returns a new HTTPResponse with status 202.

func (*HTTPResponse) BadRequest ΒΆ

func (e *HTTPResponse) BadRequest(message, path string) *HTTPResponse

BadRequest returns a new HTTPResponse with status 400.

func (*HTTPResponse) Conflict ΒΆ

func (e *HTTPResponse) Conflict(message, path string) *HTTPResponse

Conflict returns a new HTTPResponse with status 409.

func (*HTTPResponse) Created ΒΆ

func (e *HTTPResponse) Created(message, path string) *HTTPResponse

Created returns a new HTTPResponse with status 201.

func (*HTTPResponse) Forbidden ΒΆ

func (e *HTTPResponse) Forbidden(message, path string) *HTTPResponse

Forbidden returns a new HTTPResponse with status 403.

func (*HTTPResponse) InternalServerError ΒΆ

func (e *HTTPResponse) InternalServerError(message, path string) *HTTPResponse

InternalServerError returns a new HTTPResponse with status 500.

func (*HTTPResponse) NotFound ΒΆ

func (e *HTTPResponse) NotFound(message, path string) *HTTPResponse

NotFound returns a new HTTPResponse with status 404.

func (*HTTPResponse) ToJson ΒΆ

func (e *HTTPResponse) ToJson() string

ToJson returns the HTTPResponse as a JSON string.

func (*HTTPResponse) Unauthorized ΒΆ

func (e *HTTPResponse) Unauthorized(message, path string) *HTTPResponse

Unauthorized returns a new HTTPResponse with status 401.

type RequestCtx ΒΆ

type RequestCtx struct {
	*fasthttp.RequestCtx
	Params   map[string]string
	JsonBody map[string]interface{}
	Nexts    []func(ctx *RequestCtx)
	// contains filtered or unexported fields
}

RequestCtx is an extension of fasthttp.RequestCtx

func NewRequestCtx ΒΆ

func NewRequestCtx(ctx *fasthttp.RequestCtx, h []func(ctx *RequestCtx)) *RequestCtx

NewRequestCtx returns a new RequestCtx

func (*RequestCtx) Cookie ΒΆ

func (ctx *RequestCtx) Cookie(name string) string

Cookie returns cookie value by name

func (*RequestCtx) Header ΒΆ

func (ctx *RequestCtx) Header(key string) string

GetHeader returns the request header with key

func (*RequestCtx) MethodString ΒΆ

func (ctx *RequestCtx) MethodString() string

Method returns the request method

func (*RequestCtx) Next ΒΆ

func (ctx *RequestCtx) Next()

Next calls the next handler

func (*RequestCtx) PathString ΒΆ

func (ctx *RequestCtx) PathString() string

Path returns the request path

func (*RequestCtx) Send ΒΆ

func (ctx *RequestCtx) Send(s string)

Send is and alias for WriteString

func (*RequestCtx) SetContentType ΒΆ

func (ctx *RequestCtx) SetContentType(contentType string)

SetContentType sets the response content type

func (*RequestCtx) SetCookie ΒΆ

func (ctx *RequestCtx) SetCookie(cookie *fasthttp.Cookie)

SetCookie sets cookie.

func (*RequestCtx) SetHeader ΒΆ

func (ctx *RequestCtx) SetHeader(key, value string)

SetHeader sets the response header with key, value pair

func (*RequestCtx) SetStatusCode ΒΆ

func (ctx *RequestCtx) SetStatusCode(statusCode int)

SetStatusCode sets the response status code

type Route ΒΆ

type Route struct {
	Path         string
	ParamIndexes map[string]uint // map[string]uint{"id": 0, "name": 1, ...}
	Handler      func(ctx *RequestCtx)
}

Route stores path, param indexes and handler.

func NewRoute ΒΆ

func NewRoute(path string, h func(ctx *RequestCtx)) Route

NewRoute takes a path string and an handler function and returns new Route.

Directories ΒΆ

Path Synopsis
example

Jump to

Keyboard shortcuts

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