plum

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2024 License: MIT Imports: 22 Imported by: 0

README

Translations: English | 简体中文

views since 2024/07/02

Plum

Plum is a Simple,General,Highly efficient,Stable,High-performance,Expandability, zero-dependency HTTP library for Go.

It's a thin wrapper around the standard library .

Why?

The Go standard library is very powerful. Fast, easy to use, and with a good API.

In particular, with the improved HTTP routing in 1.22, plum aims to maintain net/http compatibility and enhance processing power

Goals

Implement a high performance, scalable, and stable http library with a simple, generic idea in a pure standard library way. Plum is also an ideal one learning warehouse

Principles

Zero-dependency
Simple
Genneral
Stable
Expandability

Features

  • Zero-dependency, only use the standard library.
  • Structured logging interface, default implementation[log/slog].
  • routes Using new, improved http.ServeMux.
  • customizable: middlewares,logger ,binding,render and so on.

Getting Started

Installation

You need Go version 1.22 or higher.

go get -u github.com/go-plum/plum

Usage

It mainly uses middleware, logging, binding, render that is similar to gin and compatible with some or all of gin.

package main

import (
	"fmt"

	"github.com/go-plum/plum"
)

func hello(ctx *plum.Context) error {
	fmt.Println("hello", ctx.Request.URL)
	ctx.JSON(200, "hello from :"+ctx.Request.URL.String())
	return nil
}
func main() {
	p := plum.New()
	p.GET("/hello", hello)

	r := p.Group("/1")
	r.GET("/hello", hello)

    r = p.Group("/2")
	r.GET("/hello", hello)

	r = p.Group("/2").Group("/3")
	r.GET("/hello", hello)

	p.Run(":8080") // go p.Run(":8080")
}


Reference

Documentation

Index

Constants

View Source
const (
	// DefaultPrefix url prefix of pprof
	DefaultPrefix = "/debug/pprof"
)
View Source
const Release = "v0.0.0"

Variables

This section is empty.

Functions

func RoutePerf

func RoutePerf(rg *Router, prefixOptions ...string)

RoutePerf the standard HandlerFuncs from the net/http/pprof package with the provided gin.GrouterGroup. prefixOptions is a optional. If not prefixOptions, the default path prefix is used, otherwise first prefixOptions will be path prefix.

Types

type Context

type Context struct {
	Request *http.Request
	Writer  http.ResponseWriter

	Params Params

	// Keys is a key/value pair exclusively for the context of each request.
	Keys map[string]any
	// contains filtered or unexported fields
}

Context is the most important part of plum. It allows us to pass variables between middleware, manage the flow, validate the JSON of a request and render a JSON response for example.

func (*Context) Abort

func (c *Context) Abort()

Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int)

AbortWithStatus calls `Abort()` and writes the headers with the specified status code. For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).

func (*Context) AbortWithStatusJSON

func (c *Context) AbortWithStatusJSON(code int, jsonObj any)

AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body. It also sets the Content-Type as "application/json".

func (*Context) AddParam

func (c *Context) AddParam(key, value string)

AddParam adds param to context and replaces path param key with given value for e2e testing purposes

func (*Context) ContentType

func (c *Context) ContentType() string

ContentType returns the Content-Type header of the request.

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. And return the named cookie is unescaped. If multiple cookies match the given name, only one cookie will be returned.

func (*Context) Copy

func (c *Context) Copy() *Context

Copy returns a copy of the current context that can be safely used outside the request's scope. This has to be used when the context has to be passed to a goroutine.

func (*Context) Data

func (c *Context) Data(code int, contentType string, data []byte)

Data writes some data into the body stream and updates the HTTP code.

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

Deadline returns that there is no deadline (ok==false) when c.Request has no Context.

func (*Context) DefaultQuery

func (c *Context) DefaultQuery(key, defaultValue string) string

DefaultQuery returns the keyed url query value if it exists, otherwise it returns the specified defaultValue string. See: Query() and GetQuery() for further information.

func (*Context) Done

func (c *Context) Done() <-chan struct{}

Done returns nil (chan which will wait forever) when c.Request has no Context.

func (*Context) Err

func (c *Context) Err() error

Err returns nil when c.Request has no Context.

func (*Context) File

func (c *Context) File(filepath string)

File writes the specified file into the body stream in an efficient way.

func (*Context) FileFromFS

func (c *Context) FileFromFS(filepath string, fs http.FileSystem)

FileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way.

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

FormFile returns the first file for the provided form key.

func (*Context) Get

func (c *Context) Get(key string) (value any, exists bool)

Get returns the value for the given key, ie: (value, true). If the value does not exist it returns (nil, false)

func (*Context) GetHeader

func (c *Context) GetHeader(key string) string

GetHeader returns value from request headers.

func (*Context) GetPostFormMap

func (c *Context) GetPostFormMap(key string) (map[string]string, bool)

GetPostFormMap returns a map for a given form key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetQuery

func (c *Context) GetQuery(key string) (string, bool)

GetQuery is like Query(), it returns the keyed url query value

func (*Context) GetQueryArray

func (c *Context) GetQueryArray(key string) (values []string, ok bool)

GetQueryArray returns a slice of strings for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetQueryMap

func (c *Context) GetQueryMap(key string) (map[string]string, bool)

GetQueryMap returns a map for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetRawData

func (c *Context) GetRawData() ([]byte, error)

GetRawData returns stream data.

func (*Context) HTML

func (c *Context) HTML(code int, name string, obj any)

HTML renders the HTTP template specified by its file name. It also updates the HTTP code and sets the Content-Type as "text/html". See http://golang.org/doc/articles/wiki/

func (*Context) Header

func (c *Context) Header(key, value string)

Header is an intelligent shortcut for c.Writer.Header().Set(key, value). It writes a header in the response. If value == "", this method removes the header `c.Writer.Header().Del(key)`

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) IsWebsocket

func (c *Context) IsWebsocket() bool

IsWebsocket returns true if the request headers indicate that a websocket handshake is being initiated by the client.

func (*Context) JSON

func (c *Context) JSON(code int, obj any)

JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".

func (*Context) JSONP

func (c *Context) JSONP(code int, obj any)

JSONP serializes the given struct as JSON into the response body. It adds padding to response body to request data from a server residing in a different domain than the client. It also sets the Content-Type as "application/javascript".

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm is the parsed multipart form, including file uploads.

func (*Context) MustBindWith

func (c *Context) MustBindWith(obj any, b binding.Binding) error

MustBindWith binds the passed struct pointer using the specified binding engine. It will abort the request with HTTP 400 if any error occurs. See the binding package.

func (*Context) Next

func (c *Context) Next()

Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler. See example in GitHub.

func (*Context) Param

func (c *Context) Param(key string) string

Param returns the value of the URL param. It is a shortcut for c.Params.ByName(key)

func (*Context) PostFormMap

func (c *Context) PostFormMap(key string) (dicts map[string]string)

PostFormMap returns a map for a given form key.

func (*Context) Query

func (c *Context) Query(key string) (value string)

Query returns the keyed url query value if it exists, otherwise it returns an empty string `("")`. It is shortcut for `c.Request.URL.Query().Get(key)`

func (*Context) QueryArray

func (c *Context) QueryArray(key string) (values []string)

QueryArray returns a slice of strings for a given query key. The length of the slice depends on the number of params with the given key.

func (*Context) QueryMap

func (c *Context) QueryMap(key string) (dicts map[string]string)

QueryMap returns a map for a given query key.

func (*Context) Redirect

func (c *Context) Redirect(code int, location string)

Redirect returns an HTTP redirect to the specific location.

func (*Context) RemoteIP

func (c *Context) RemoteIP() string

RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port).

func (*Context) Render

func (c *Context) Render(code int, r render.Render)

Render writes the response headers and calls render.Render to render data.

func (*Context) SaveUploadedFile

func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error

SaveUploadedFile uploads the form file to specific dst.

func (*Context) Set

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

Set is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.

func (*Context) SetCookie

func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Context) SetSameSite

func (c *Context) SetSameSite(samesite http.SameSite)

SetSameSite with cookie

func (*Context) ShouldBindBodyWith

func (c *Context) ShouldBindBodyWith(bodyKey string, obj any, bb binding.BindingBody) (err error)

ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request body into the context, and reuse when it is called again.

NOTE: This method reads the body before binding. bodyKey Keep non-repetition

func (*Context) ShouldBindWith

func (c *Context) ShouldBindWith(obj any, b binding.Binding) error

ShouldBindWith binds the passed struct pointer using the specified binding engine. See the binding package.

func (*Context) Status

func (c *Context) Status(code int)

Status sets the HTTP response code.

func (*Context) String

func (c *Context) String(code int, format string, values ...any)

String writes the given string into the response body.

func (*Context) Value

func (c *Context) Value(key any) any

Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.

type HandlerFunc

type HandlerFunc func(*Context)

func Recover

func Recover(handler HandlerFunc) HandlerFunc

Recover will recover from panics.

type Logger

type Logger interface {
	Debug(msg string, args ...any)
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
}

Logger interface exposes methods in different log levels, following the convention of slog.Logger.

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (Params) ByName

func (ps Params) ByName(name string) (va string)

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (Params) Get

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name and a boolean true. If no matching Param is found, an empty string is returned and a boolean false .

type Plum

type Plum struct {
	Router

	RemoteIPHeaders []string
	// contains filtered or unexported fields
}

func New

func New(opt ...ServerOption) *Plum

func (*Plum) Run

func (p *Plum) Run(addr string, server ...*http.Server) error

func (*Plum) RunServer

func (p *Plum) RunServer(lis net.Listener, server *http.Server) error

func (*Plum) RunTLS

func (p *Plum) RunTLS(addr, certFile, keyFile string, server ...*http.Server) error

func (*Plum) ServeHTTP

func (p *Plum) ServeHTTP(res http.ResponseWriter, req *http.Request)

ServeHTTP should write reply headers and data to the ResponseWriter and then return.

func (*Plum) Shutdown

func (p *Plum) Shutdown(ctx context.Context) error

Shutdown the http server without interrupting active connections.

type Router

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

func (*Router) GET

func (r *Router) GET(route string, handler HandlerFunc)

func (*Router) Group

func (r *Router) Group(relativePath string, m ...Middleware) *Router

func (*Router) Handle

func (r *Router) Handle(method, route string, handler HandlerFunc)

func (*Router) POST

func (r *Router) POST(route string, handler HandlerFunc)

func (*Router) Use

func (r *Router) Use(m ...Middleware)

type RouterHandler

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

func (*RouterHandler) ServeHTTP

func (r *RouterHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)

type ServerOption

type ServerOption interface {
	// contains filtered or unexported methods
}

A ServerOption sets options such as credentials, codec and keepalive parameters, etc.

func HTMLRender

func HTMLRender(d render.HTMLRender) ServerOption

HTMLRender this is newFuncServerOption example.

func ReadHeaderTimeout

func ReadHeaderTimeout(d time.Duration) ServerOption

ReadHeaderTimeout this is newFuncServerOption example.

func WithLogger

func WithLogger(log Logger) ServerOption

WithLogger setting logger .

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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