opm

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2023 License: MIT Imports: 22 Imported by: 0

README

opm

Go web framework

[Guide]

Installation
go get github.com/boyfinal/opm
Example
package main

import (
  "net/http"
  "github.com/boyfinal/opm"
  "github.com/boyfinal/opm/middleware"
)

func main() {
  // Echo instance
  or := opm.NewRouter()

  // Middleware
  or.Use(middleware.Logger())
  or.Use(middleware.Recover())

  // Routes
  or.GET("/", opm.HandlerFunc(func(c opm.Context) error {
		return c.String(http.StatusOK, "Hello, World!")
	})

  srv := &opm.Server{
		Addr:         "localhost:8888",
		WriteTimeout: time.Second * 60,
		ReadTimeout:  time.Second * 60,
		IdleTimeout:  time.Second * 60,
		Handler:      or,
	}

  // Start server
  srv.Run()
}

Documentation

Index

Constants

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + ";" + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)
View Source
const (
	DefaultHost  = "localhost"
	DefaultPort  = 8080
	WriteTimeout = 45 * time.Second
	ReadTimeout  = 45 * time.Second
)

Variables

View Source
var (
	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXRequestID          = "X-Request-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"

	ErrUnsupportedMediaType        = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrNotFound                    = NewHTTPError(http.StatusNotFound)
	ErrUnauthorized                = NewHTTPError(http.StatusUnauthorized)
	ErrForbidden                   = NewHTTPError(http.StatusForbidden)
	ErrMethodNotAllowed            = NewHTTPError(http.StatusMethodNotAllowed)
	ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
	ErrTooManyRequests             = NewHTTPError(http.StatusTooManyRequests)
	ErrBadRequest                  = NewHTTPError(http.StatusBadRequest)
	ErrBadGateway                  = NewHTTPError(http.StatusBadGateway)
	ErrInternalServerError         = NewHTTPError(http.StatusInternalServerError)
	ErrRequestTimeout              = NewHTTPError(http.StatusRequestTimeout)
	ErrServiceUnavailable          = NewHTTPError(http.StatusServiceUnavailable)
	ErrValidatorNotRegistered      = errors.New("validator not registered")
	ErrRendererNotRegistered       = errors.New("renderer not registered")
	ErrInvalidRedirectCode         = errors.New("invalid redirect status code")
	ErrCookieNotFound              = errors.New("cookie not found")
	ErrInvalidCertOrKeyType        = errors.New("invalid cert or key type, must be string or []byte")
	ErrInvalidListenerNetwork      = errors.New("invalid listener network")
)

Functions

func Contains

func Contains(arr interface{}, in interface{}) bool

Contains determines whether an array includes a certain value among its entries

func GenerateRandBytes

func GenerateRandBytes(n int) ([]byte, error)

GenerateRandBytes returns generated random bytes

func InArrayString added in v0.0.2

func InArrayString(arr []string, in string) bool

InArrayString determines whether an array string includes a certain value among its entries

func NumFormat

func NumFormat(v interface{}) string

NumFormat is a function that takes in a variable of type interface{} and returns a string representation of that variable.

func StrConcat added in v0.0.2

func StrConcat(ss ...string) string

StrConcat concat multiple string

func Xor added in v0.0.2

func Xor(a, b []byte) []byte

Xor []byte

Types

type Context

type Context interface {
	// Request returns `*http.Request`
	Request() *http.Request

	// SetRequest sets `*http.Request`
	SetRequest(*http.Request)

	// Response returns `http.ResponseWriter`
	Response() http.ResponseWriter

	// SetResponse sets `http.ResponseWriter`
	SetResponse(http.ResponseWriter)

	// Logger returns the Looger instance
	Logger() Logger

	// SetLogger set the logger
	SetLogger(l Logger)

	// SetValue saves data in body response
	SetValue(string, interface{})

	// GetValue data in body response
	GetValue(string) interface{}

	// GetValues data in body response
	GetValues() map[string]interface{}

	// Param returns path parameter by name.
	Param(name string) string

	// ParamNames sets path parameter names.
	SetParamNames(names ...string)

	// ParamNames returns path parameter names.
	ParamNames() []string

	// ParamNames sets path parameter values.
	SetParamValues(values ...string)

	// ParamNames returns path parameter values.
	ParamValues() []string

	// QueryParam returns the query param for the provided.
	QueryParam(name string) string

	// QueryParams returns the query parameters as `url.Values`.
	QueryParams() url.Values

	// QueryString returns the URL query string.
	QueryString() string

	// FormValue returns the form field value for the provided name.
	FormValue(name string) string

	// FormFile returns the multipart form file for the provided name.
	FormFile(name string) (*multipart.FileHeader, error)

	// HTML sends a blod response with  content type and status code
	Blob(code int, contentType string, b []byte) (err error)

	// Decode reads the next JSON-encoded value from request
	Decode(interface{}) error

	// Stream sends a streaming response with status code and content type.
	Stream(code int, contentType string, r io.Reader) error

	// HTML sends a HTTP response with status code
	HTML(code int, html string) (err error)

	// HTMLBlob sends a HTTP blod response with status code
	HTMLBlob(code int, b []byte) (err error)

	// Render renders a template with data and sends a text/html response with
	// status code.
	Render(code int, filename string) error

	// JSON sends a JSON response with status code
	JSON(code int, data interface{}) error

	// JSON sends a JSON response with status code
	String(code int, data string) error

	// Redirect Redirects the request to provider URL with status code
	Redirect(code int, url string) error

	// File sends a file response
	File(file string) error

	// NoContent sends a response with no body anh a status code
	NoContent(code int) error

	// Get retrieves data from the body response.
	Get(key string) interface{}

	// Set saves data in the body response.
	Set(key string, val interface{})

	// Get data in the body response.
	Body() map[string]interface{}

	Reset(w http.ResponseWriter, r *http.Request)

	// Cookie returns the named cookie provided in the request.
	Cookie(name string) (*http.Cookie, error)

	// SetCookie adds a `Set-Cookie` header in HTTP response.
	SetCookie(cookie *http.Cookie)

	// Cookies returns the HTTP cookies sent with the request.
	Cookies() []*http.Cookie

	// Renderer sets service provide response HTML.
	SetRenderer(Renderer)

	// Renderer returns service provide response HTML.
	Renderer() Renderer

	// SetRoute sets `*Route`
	SetRoute(*Route)

	// Route returns `*Route`
	Route() *Route

	// Domain returns site domain
	Domain() string

	// RealIP return real ip
	RealIP() string
}

type Core added in v0.0.3

type Core struct {
	sync.Mutex

	Logger   Logger
	Renderer Renderer

	NotFoundHandler         Handler
	SystemErrorHandler      Handler
	MethodNotAllowedHandler Handler
	// contains filtered or unexported fields
}

func Make added in v0.0.3

func Make() *Core

New returns a Server.

func (*Core) Any added in v0.0.3

func (core *Core) Any(path string, h Handler, m ...MiddlewareFunc) []*Route

func (*Core) CONNECT added in v0.0.3

func (core *Core) CONNECT(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Core) DELETE added in v0.0.3

func (core *Core) DELETE(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Core) DefaultHTTPErrorHandler added in v0.0.3

func (core *Core) DefaultHTTPErrorHandler(err error, c Context)

func (*Core) File added in v0.0.3

func (core *Core) File(path, file string)

func (*Core) GET added in v0.0.3

func (core *Core) GET(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Core) Group added in v0.0.3

func (core *Core) Group(prefix string, m ...MiddlewareFunc) *Group

func (*Core) HEAD added in v0.0.3

func (core *Core) HEAD(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Core) Match added in v0.0.3

func (core *Core) Match(req *http.Request, match *RouteMatch) bool

func (*Core) Middleware added in v0.0.3

func (core *Core) Middleware(m ...MiddlewareFunc) *Group

func (*Core) Name added in v0.0.3

func (core *Core) Name(name string) *Route

func (*Core) NewContext added in v0.0.3

func (core *Core) NewContext(w http.ResponseWriter, req *http.Request) Context

NewContext returns a Context instance.

func (*Core) NewRoute added in v0.0.3

func (core *Core) NewRoute() *Route

NewRoute create new a Route

func (*Core) OPTIONS added in v0.0.3

func (core *Core) OPTIONS(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Core) PATCH added in v0.0.3

func (core *Core) PATCH(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Core) POST added in v0.0.3

func (core *Core) POST(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Core) PUT added in v0.0.3

func (core *Core) PUT(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Core) Path added in v0.0.3

func (core *Core) Path(path string) *Route

func (*Core) Prefix added in v0.0.3

func (core *Core) Prefix(prefix string) *Group

func (*Core) Run added in v0.0.3

func (core *Core) Run(addr string)

func (*Core) RunServer added in v0.0.3

func (core *Core) RunServer(s *Server)

func (*Core) ServeHTTP added in v0.0.3

func (core *Core) ServeHTTP(w http.ResponseWriter, rq *http.Request)

func (*Core) SetLog added in v0.0.3

func (core *Core) SetLog(logger Logger) *Core

func (*Core) Static added in v0.0.3

func (core *Core) Static(path, root string) *Route

func (*Core) TRACE added in v0.0.3

func (core *Core) TRACE(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Core) Use added in v0.0.3

func (core *Core) Use(m ...MiddlewareFunc)

Use adds middleware

type Group

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

func (*Group) Add

func (g *Group) Add(method, path string, h Handler, m ...MiddlewareFunc) *Route

func (*Group) Any

func (g *Group) Any(path string, h Handler, m ...MiddlewareFunc) []*Route

func (*Group) CONNECT

func (g *Group) CONNECT(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Group) DELETE

func (g *Group) DELETE(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Group) File added in v0.0.2

func (g *Group) File(path, file string)

func (*Group) GET

func (g *Group) GET(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Group) Group

func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group

func (*Group) HEAD

func (g *Group) HEAD(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Group) PATCH

func (g *Group) PATCH(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Group) POST

func (g *Group) POST(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Group) PUT

func (g *Group) PUT(path string, h Handler, m ...MiddlewareFunc) *Route

func (*Group) Path

func (g *Group) Path(path string) *Route

func (*Group) Prefix

func (g *Group) Prefix(prefix string) *Group

func (*Group) Routes added in v0.0.2

func (g *Group) Routes(f func(*Group) *Group) *Group

func (*Group) TRACE

func (g *Group) TRACE(path string, h Handler, m ...MiddlewareFunc) *Route

type HTTPError

type HTTPError struct {
	Code    int         `json:"-"`
	Message interface{} `json:"message"`
}

HTTPError an error that occurred while handing a request

func NewHTTPError

func NewHTTPError(code int, message ...interface{}) *HTTPError

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Handler

type Handler func(Context) error

Handler a responds to an HTTP request

type Logger

type Logger interface {
	Debugf(format string, args ...interface{})
	Info(i ...interface{})
	Infof(format string, args ...interface{})
	Warn(i ...interface{})
	Warnf(format string, args ...interface{})
	Error(i ...interface{})
	Errorf(format string, args ...interface{})
	Fatal(i ...interface{})
	Fatalf(format string, args ...interface{})
	Panic(i ...interface{})
	Panicf(format string, args ...interface{})
}

type Map

type Map map[string]interface{}

type MiddlewareFunc

type MiddlewareFunc func(Handler) Handler

MiddlewareFunc defines a function to process middleware

type Renderer

type Renderer interface {
	Render(io.Writer, string, interface{}) error
}

type Route

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

func (*Route) GetName

func (r *Route) GetName() string

Method gets name `*Route`

func (*Route) GetPath

func (r *Route) GetPath() string

func (*Route) Handler

func (r *Route) Handler(handler Handler) *Route

func (*Route) HandlerFunc

func (r *Route) HandlerFunc(f func(Context) error) *Route

func (*Route) Method

func (r *Route) Method(method string) *Route

Method sets type method `*Route`

func (*Route) Name

func (r *Route) Name(name string) *Route

func (*Route) Path

func (r *Route) Path(path string) *Route

func (*Route) Use

func (r *Route) Use(m ...MiddlewareFunc) *Route

type RouteList added in v0.0.3

type RouteList []*Route

type RouteMatch

type RouteMatch struct {
	Route    *Route
	Handler  Handler
	PNames   []string
	PValues  []string
	MatchErr error
}

type RouteNames added in v0.0.3

type RouteNames map[string]*Route

type Server

type Server struct {
	Name         string
	Host         string
	Port         int
	Addr         string
	Handler      http.Handler
	WriteTimeout time.Duration
	ReadTimeout  time.Duration
}

func (*Server) Run

func (s *Server) Run()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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