jeen

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2022 License: MIT Imports: 27 Imported by: 0

README

Jeen

Jeen is a package wrapper that is used as a web application base for the go language.

Package Wrappers?

Yes, because jeen works by using other available packages.

What's Different?

Jeen wrapped these packages to make usage shorter and code cleaner. In addition, several new functions have been added which will certainly make the coding process faster.

Context cancellation has been included in every request so there is no need to check the timeout anymore. You only need to make sure the parts that don't use context.

Database and session has also been included so that it can be used easily in every http request. However, you can choose database and session drivers as needed.

Credits

Author

This Package is developed by Fuad Ar-Radhi.

Documentation

Index

Constants

View Source
const (
	UNKNOWN = iota
	QUESTION
	DOLLAR
	NAMED
	AT
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Driver  *Driver
	Default *Default
}
type Cookie struct {
	// contains filtered or unexported fields
}

Cookie is response and request for http cookie

func (*Cookie) Add

func (c *Cookie) Add(cookie *http.Cookie)

AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, AddCookie does not attach more than one Cookie header field. That means all cookies, if any, are written into the same line, separated by semicolon. AddCookie only sanitizes c's name and value, and does not sanitize a Cookie header already present in the request.

func (*Cookie) All

func (c *Cookie) All() []*http.Cookie

All parses and returns the HTTP cookies sent with the request.

func (*Cookie) Get

func (c *Cookie) Get(name string) (*http.Cookie, error)

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

func (*Cookie) Set

func (c *Cookie) Set(cookie *http.Cookie)

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

type Database

type Database struct {

	// database/sql DB pool, can be used by other packages that require a *sql.DB
	DB *sql.DB

	// database/sql Conn, can be used by other packages that require
	// a single connection from *sql.DB
	Conn *sql.Conn
	// contains filtered or unexported fields
}

func (*Database) BuildQuery

func (d *Database) BuildQuery(namedQuery string, namedArgs ...Map) (string, []interface{}, error)

buildquery convert named queries to positional queries, so they can be executed directly by the database/sql without changing the working system of sanitaze sql injection

func (*Database) Close

func (d *Database) Close()

Close returns the connection to the connection pool. All operations after a Close will return with ErrConnDone. Close is safe to call concurrently with other operations and will block until all other operations finish. It may be useful to first cancel any used context and then call close directly after.

func (*Database) Query

func (d *Database) Query(query string, args ...Map) *SqlQuery

Query only store the query string and arguments without executing it. see Result, Row and Exec for more information.

type Default

type Default struct {
	WithDatabase bool
	WithTimeout  time.Duration
	WithTemplate *Template
}

type Delims

type Delims struct {
	Left  string
	Right string
}

type Driver

type Driver struct {
	Database func() (db *sql.DB, drivername string)
	Session  func() (store scs.Store)
}

type HandlerMiddlewareFunc

type HandlerMiddlewareFunc func(res *Resource) bool

type HandlerRouteFunc

type HandlerRouteFunc func(res *Resource)

type HandlerServerFunc

type HandlerServerFunc func(serv *Server)

type Html

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

func (*Html) Error

func (h *Html) Error(filename string, data Map, escape ...bool) error

Error is shortcut for Response with StatusInternalServerError = 500, use escape = false if don't need html escape (default `true`)

func (*Html) Forbidden

func (h *Html) Forbidden(filename string, data Map, escape ...bool) error

Forbidden is shortcut for Response with StatusForbidden = 403, use escape = false if don't need html escape (default `true`)

func (*Html) NotFound

func (h *Html) NotFound(filename string, data Map, escape ...bool) error

NotFound is shortcut for Response with StatusNotFound = 404, use escape = false if don't need html escape (default `true`)

func (*Html) Render

func (h *Html) Render(out io.Writer, filename string, data Map, escape ...bool) error

Render render to io.Writer without output to browser, example:

var b bytes.Buffer
err = res.Html.Output(&b, ...)
fmt.Println(b.String())

func (*Html) Response

func (h *Html) Response(statusCode int, filename string, data Map, escape ...bool) error

Response render html from filename, output to browser, use escape = false if don't need html escape (default `true`)

func (*Html) ResponseByte

func (h *Html) ResponseByte(statusCode int, text []byte) error

ResponseByte render to browser from statuscode and byte content

func (*Html) ResponseString

func (h *Html) ResponseString(statusCode int, text string) error

ResponseString response to browser from statuscode and string content

func (*Html) StatusText

func (h *Html) StatusText(statusCode int) error

StatusText response output to browser, with header and default string from statuscode

func (*Html) Success

func (h *Html) Success(filename string, data Map, escape ...bool) error

Success is shortcut for Response with StatusOK = 200, use escape = false if don't need html escape (default `true`)

func (*Html) Timeout

func (h *Html) Timeout(filename string, data Map, escape ...bool) error

Timeout is shortcut for Response with StatusGatewayTimeout = 504, use escape = false if don't need html escape (default `true`)

func (*Html) Unauthorized

func (h *Html) Unauthorized(filename string, data Map, escape ...bool) error

Unauthorized is shortcut for Response with StatusUnauthorized = 401, use escape = false if don't need html escape (default `true`)

type HtmlEngine

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

The following source code was copied from the goview package, we cannot use the package directly because goview only supports escaped html.

Source: https://github.com/foolin/goview/blob/master/view.go

engine used to render html or text output

func (*HtmlEngine) Render

func (e *HtmlEngine) Render(w io.Writer, name string, data Map, escape bool) error

render output to io.Writer, so we can use that output before render to browser

func (*HtmlEngine) Response

func (e *HtmlEngine) Response(w http.ResponseWriter, statusCode int, name string, data Map, escape bool) error

Response render output to responseWriter

type Json

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

func (*Json) Error

func (j *Json) Error(data interface{}) error

Error is shortcut for Response with StatusInternalServerError = 500,

func (*Json) Forbidden

func (j *Json) Forbidden(data interface{}) error

Forbidden is shortcut for Response with StatusForbidden = 403,

func (*Json) NotFound

func (j *Json) NotFound(data interface{}) error

NotFound is shortcut for Response with StatusNotFound = 404,

func (*Json) Response

func (j *Json) Response(statusCode int, data interface{}) error

Response response json output to browser,

func (*Json) Success

func (j *Json) Success(data interface{}) error

Success is shortcut for Response with StatusOK = 200,

func (*Json) Timeout

func (j *Json) Timeout(data interface{}) error

Timeout is shortcut for Response with StatusGatewayTimeout = 504,

func (*Json) Unauthorized

func (j *Json) Unauthorized(data interface{}) error

Unauthorized is shortcut for Response with StatusUnauthorized = 401,

type Map

type Map map[string]interface{}

type Options

type Options func(s *Server)

func WithDatabase

func WithDatabase(usedb bool) Options

func WithTemplate

func WithTemplate(template *Template) Options

func WithTimeout

func WithTimeout(timeout time.Duration) Options

type Request

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

func (*Request) Instance

func (r *Request) Instance() *http.Request

return instance of *http.Request

func (*Request) IsTLS

func (r *Request) IsTLS() bool

func (*Request) IsWebSocket

func (r *Request) IsWebSocket() bool

func (*Request) QueryParam

func (r *Request) QueryParam(name string) string

func (*Request) QueryString

func (r *Request) QueryString() string

func (*Request) RemoteAddr

func (r *Request) RemoteAddr() string

func (*Request) RequestURI

func (r *Request) RequestURI() string

func (*Request) Scheme

func (r *Request) Scheme() string

func (*Request) URLParam

func (r *Request) URLParam(key string) string

type Resource

type Resource struct {

	// request
	Request *Request

	// writer
	Writer *Writer

	// cookie
	Cookie *Cookie

	// request context
	Context context.Context

	// database sql.DB
	Database *Database

	// session SCS
	Session *Session

	// html response with goview
	Html *Html

	// json response
	Json *Json
	// contains filtered or unexported fields
}

All resource needed for development

func (*Resource) Get

func (r *Resource) Get(key interface{}) interface{}

Get get value from context

func (*Resource) Redirect

func (r *Resource) Redirect(code int, url string) error

Redirect redirects the request to a provided URL with status code.

func (*Resource) Set

func (r *Resource) Set(key, val interface{})

Set set value to request context, see Get to get it

type Router

type Router interface {
	chi.Router
}

type Server

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

func InitServer

func InitServer(cfg *Config) *Server

func (*Server) Close

func (s *Server) Close()

Close server and all resource

func (*Server) Connect

func (s *Server) Connect(pattern string, handler HandlerRouteFunc, opts ...Options) *Server

Connect adds the route `pattern` that matches a CONNECT http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) Delete

func (s *Server) Delete(pattern string, handler HandlerRouteFunc, opts ...Options) *Server

Delete adds the route `pattern` that matches a DELETE http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) Get

func (s *Server) Get(pattern string, handler HandlerRouteFunc, opts ...Options) *Server

Get adds the route `pattern` that matches a GET http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) Group

func (s *Server) Group(handler HandlerServerFunc, opts ...Options) *Server

Group creates a new inline-Mux with a fresh middleware stack. It's useful for a group of handlers along the same routing path that use an additional set of middlewares. See _examples/.

func (*Server) Handle

func (s *Server) Handle(pattern string, handler HandlerServerFunc, opts ...Options) *Server

Handle adds the route `pattern` that matches any http method to execute the `handler` jeen.HandlerServerFunc.

func (*Server) HandleFunc

func (s *Server) HandleFunc(pattern string, handler HandlerRouteFunc, opts ...Options) *Server

HandleFunc adds the route `pattern` that matches any http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) Handler added in v0.1.2

func (s *Server) Handler() http.Handler

Handler expose http.Handler

func (*Server) Head

func (s *Server) Head(pattern string, handler HandlerRouteFunc, opts ...Options) *Server

Head adds the route `pattern` that matches a HEAD http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(addr string)

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.

func (*Server) Method

func (s *Server) Method(method string, pattern string, handler HandlerServerFunc, opts ...Options) *Server

Method adds the route `pattern` that matches `method` http method to execute the `handler` jeen.HandlerServerFunc.

func (*Server) MethodFunc

func (s *Server) MethodFunc(method string, pattern string, handler HandlerRouteFunc, opts ...Options) *Server

MethodFunc adds the route `pattern` that matches `method` http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) MethodNotAllowed

func (s *Server) MethodNotAllowed(handler HandlerRouteFunc, opts ...Options) *Server

MethodNotAllowed sets a custom jeen.HandlerRouteFunc for routing paths where the method is unresolved. The default handler returns a 405 with an empty body.

func (*Server) Mount

func (s *Server) Mount(pattern string, handler HandlerServerFunc, opts ...Options) *Server

Mount attaches another http.Handler or jeen.Server as a subrouter along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Mount. See _examples/.

Note that Mount() simply sets a wildcard along the `pattern` that will continue routing at the `handler`, which in most cases is another jeen.Server. As a result, if you define two Mount() routes on the exact same pattern the mount will panic.

func (*Server) NotFound

func (s *Server) NotFound(handler HandlerRouteFunc, opts ...Options) *Server

NotFound sets a custom jeen.HandlerRouteFunc for routing paths that could not be found. The default 404 handler is `http.NotFound`.

func (*Server) Options

func (s *Server) Options(pattern string, handler HandlerRouteFunc, opts ...Options) *Server

Options adds the route `pattern` that matches a OPTIONS http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) Patch

func (s *Server) Patch(pattern string, handler HandlerRouteFunc, opts ...Options) *Server

Patch adds the route `pattern` that matches a PATCH http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) Post

func (s *Server) Post(pattern string, handler HandlerRouteFunc, opts ...Options) *Server

Post adds the route `pattern` that matches a POST http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) Put

func (s *Server) Put(pattern string, handler HandlerRouteFunc, opts ...Options) *Server

Put adds the route `pattern` that matches a PUT http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) Route

func (s *Server) Route(pattern string, handler HandlerServerFunc, opts ...Options) *Server

Route creates a new Mux with a fresh middleware stack and mounts it along the `pattern` as a subrouter. Effectively, this is a short-hand call to Mount. See _examples/.

func (*Server) Timeout

func (s *Server) Timeout(handler HandlerRouteFunc, opts ...Options) *Server

Timeout sets a custom jeen.HandlerRouteFunc for routing paths that have exceeded timeout. The default is json response.

func (*Server) Trace

func (s *Server) Trace(pattern string, handler HandlerRouteFunc, opts ...Options) *Server

Trace adds the route `pattern` that matches a TRACE http method to execute the `handler` jeen.HandlerRouteFunc.

func (*Server) Use

func (s *Server) Use(handler HandlerMiddlewareFunc, opts ...Options)

Use appends a middleware handler to the Mux middleware stack.

The middleware stack for any Mux will execute before searching for a matching route to a specific handler, which provides opportunity to respond early, change the course of the request execution, or set request-scoped values for the next http.Handler.

func (*Server) With

func (s *Server) With(handler HandlerMiddlewareFunc, opts ...Options)

With adds inline middlewares for an endpoint handler.

type Session

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

SCS Session wrapper credit: github.com/alexedwards/scs/v2

func (*Session) Clear

func (s *Session) Clear() error

Clear removes all data for the current session. The session token and lifetime are unaffected. If there is no data in the current session this is a no-op.

func (*Session) Deadline

func (s *Session) Deadline() time.Time

Deadline returns the 'absolute' expiry time for the session. Please note that if you are using an idle timeout, it is possible that a session will expire due to non-use before the returned deadline.

func (*Session) Destroy

func (s *Session) Destroy() error

Destroy deletes the session data from the session store and sets the session status to Destroyed. Any further operations in the same request cycle will result in a new session being created.

func (*Session) Exists

func (s *Session) Exists(key string) bool

Exists returns true if the given key is present in the session data.

func (*Session) Get

func (s *Session) Get(key string, pop ...bool) *sessionValue

Get returns the value for a given key from the session data. The return value has the type interface{} so will usually need to be type asserted before you can use it.

func (*Session) Iterate

func (s *Session) Iterate(fn func(session *Session) error) error

Iterate retrieves all active (i.e. not expired) sessions from the store and executes the provided function fn for each session. If the session store being used does not support iteration then Iterate will panic.

func (*Session) Keys

func (s *Session) Keys() []string

Keys returns a slice of all key names present in the session data, sorted alphabetically. If the data contains no data then an empty slice will be returned.

func (*Session) MergeSession

func (s *Session) MergeSession(token string) error

MergeSession is used to merge in data from a different session in case strict session tokens are lost across an oauth or similar redirect flows. Use Clear() if no values of the new session are to be used.

func (*Session) RememberMe

func (s *Session) RememberMe(val bool)

RememberMe controls whether the session cookie is persistent (i.e whether it is retained after a user closes their browser). RememberMe only has an effect if you have set SessionManager.Cookie.Persist = false (the default is true) and you are using the standard LoadAndSave() middleware.

func (*Session) Remove

func (s *Session) Remove(key string)

Remove deletes the given key and corresponding value from the session data. The session data status will be set to Modified. If the key is not present this operation is a no-op.

func (*Session) RenewToken

func (s *Session) RenewToken() error

RenewToken updates the session data to have a new session token while retaining the current session data. The session lifetime is also reset and the session data status will be set to Modified.

The old session token and accompanying data are deleted from the session store.

To mitigate the risk of session fixation attacks, it's important that you call RenewToken before making any changes to privilege levels (e.g. login and logout operations). See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change for additional information.

func (*Session) Set

func (s *Session) Set(key string, value interface{})

Set adds a key and corresponding value to the session data. Any existing value for the key will be replaced. The session data status will be set to Modified.

func (*Session) SetMap

func (s *Session) SetMap(m Map)

SetMap adds a key and corresponding value to the session data from a Map. Any existing value for the key will be replaced. The session data status will be set to Modified.

func (*Session) Status

func (s *Session) Status() scs.Status

Status returns the current status of the session data.

func (*Session) Token

func (s *Session) Token() string

Token returns the session token. Please note that this will return the empty string "" if it is called before the session has been committed to the store.

type SqlQuery

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

func (*SqlQuery) Exec

func (q *SqlQuery) Exec() (sql.Result, error)

Exec execute query

func (*SqlQuery) Result

func (q *SqlQuery) Result(dest interface{}) error

Result return all rows from the query

func (*SqlQuery) Row

func (q *SqlQuery) Row(dest interface{}) error

Row return only one row from the query

type Template

type Template struct {
	Root         string
	Master       string
	Partials     []string
	Funcs        Map
	DisableCache bool
	Delims       *Delims
}

type Writer added in v0.1.1

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

func (*Writer) Instance added in v0.1.1

func (w *Writer) Instance() http.ResponseWriter

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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