soon

package module
v0.0.0-...-58bf0a8 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2020 License: MIT Imports: 23 Imported by: 0

README

Soon Web Framework

Build Status codecov Go Report Card GoDoc License

Soon is a web framework written in Go (Golang). It features an expressjs-like API.

Installation

To install Soon, you need to install Go and set your Go workspace first.

The first need Go installed (version 1.11+ is required), then you can use the below Go command to install Soon.

$ go get -u github.com/soongo/soon

Quick Start

package main

import (
	"github.com/soongo/soon"
)

// an example middleware
func logger(c *soon.Context) {
	// do something before
	c.Next()
	// do something after
}

func main() {
	// soon.SetMode(soon.DebugMode) // enable soon framework debug mode

	// Create an app with default router
	app := soon.New()

	app.Use(logger) // use middleware

	app.GET("/", func(c *soon.Context) {
		c.Send("Hello World")
	})

	app.GET("/:foo", func(c *soon.Context) {
		c.Send(c.Params().Get("foo"))
	})

	// an example error handler
	app.Use(func(v interface{}, c *soon.Context) {
		msg := "Internal Server Error"
		switch err := v.(type) {
		case error:
			msg = err.Error()
		case string:
			msg = err
		}
		c.Status(500)
		c.Send(msg)
	})

	app.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Documentation

Index

Constants

View Source
const (
	// DebugMode indicates soon mode is debug.
	DebugMode = "debug"

	// ReleaseMode indicates soon mode is release.
	ReleaseMode = "release"

	// TestMode indicates soon mode is test.
	TestMode = "test"
)
View Source
const BodyBytesKey = "_soongo/soon/bodybyteskey"

BodyBytesKey indicates a default body bytes key.

View Source
const EnvSoonMode = "SOON_MODE"

EnvSoonMode indicates environment name for soon mode.

View Source
const (
	// HTTPMethodAll means any http method.
	HTTPMethodAll = "ALL"
)
View Source
const Version = "v0.1.0-dev"

Version is the current version of Soon framework.

Variables

View Source
var DefaultErrorWriter io.Writer = os.Stderr

DefaultErrorWriter is the default io.Writer used by Soon to debug errors

View Source
var DefaultWriter io.Writer = os.Stdout

DefaultWriter is the default io.Writer used by Soon for debug output. To support coloring in Windows use:

import "github.com/mattn/go-colorable"
soon.DefaultWriter = colorable.NewColorableStdout()

Functions

func DisableBindValidation

func DisableBindValidation()

DisableBindValidation closes the default validator.

func EnableJsonDecoderDisallowUnknownFields

func EnableJsonDecoderDisallowUnknownFields()

EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to call the DisallowUnknownFields method on the JSON Decoder instance.

func EnableJsonDecoderUseNumber

func EnableJsonDecoderUseNumber()

EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to call the UseNumber method on the JSON Decoder instance.

func IsDebugging

func IsDebugging() bool

IsDebugging returns true if the framework is running in debug mode. Use SetMode(soon.DebugMode) to enable debug mode.

func Mode

func Mode() string

Mode returns currently soon mode.

func SetMode

func SetMode(value string)

SetMode sets soon mode according to input string.

Types

type App

type App struct {
	*Router
}

App represents an application with Soon framework.

func New

func New(options ...*RouterOption) *App

New creates a Soon application.

func (*App) Run

func (app *App) Run(addr ...string) error

Run attaches the router to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, app)

type Context

type Context struct {
	Request *Request

	Writer ResponseWriter

	// Locals contains local variables scoped to the request,
	// and therefore available during that request / response cycle (if any).
	//
	// This property is useful for exposing request-level information such as
	// the request path name, authenticated user, user settings, and so on.
	Locals map[string]interface{}
	// contains filtered or unexported fields
}

Context is the most important part of soon. 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 NewContext

func NewContext(r *http.Request, w http.ResponseWriter) *Context

NewContext returns an instance of Context object

func (*Context) Append

func (c *Context) Append(key string, value interface{})

Append the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value. The value parameter can be a string or a string slice. Note: calling c.Set() after c.Append() will reset the previously-set header value.

func (*Context) Attachment

func (c *Context) Attachment(filename ...string)

Attachment sets the HTTP response Content-Disposition header field to “attachment”. If a filename is given, then it sets the Content-Type based on the extension name via c.Type(), and sets the Content-Disposition “filename=” parameter.

func (*Context) BindBodyWith

func (c *Context) BindBodyWith(obj interface{}, bb binding.BindingBody) (err error)

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

NOTE: This method reads the body before binding. So you should use BindWith for better performance if you need to call only once.

func (*Context) BindHeader

func (c *Context) BindHeader(obj interface{}) error

BindHeader is a shortcut for c.BindWith(obj, binding.Header).

func (*Context) BindJSON

func (c *Context) BindJSON(obj interface{}) error

BindJSON is a shortcut for c.BindWith(obj, binding.JSON).

func (*Context) BindQuery

func (c *Context) BindQuery(obj interface{}) error

BindQuery is a shortcut for c.BindWith(obj, binding.Query).

func (*Context) BindUri

func (c *Context) BindUri(obj interface{}) error

BindUri binds the passed struct pointer using binding.Uri.

func (*Context) BindWith

func (c *Context) BindWith(obj interface{}, b binding.Binding) error

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

func (*Context) ClearCookie

func (c *Context) ClearCookie(cookie *http.Cookie)

ClearCookie clears the specified cookie.

func (*Context) Cookie

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

Cookie sets cookie.

func (*Context) Download

func (c *Context) Download(filePath string, options ...renderer.FileOptions)

Download transfers the file at path as an “attachment”. Typically, browsers will prompt the user for download. By default, the Content-Disposition header “filename=” parameter is path (this typically appears in the browser dialog). Override this default with the options.Name parameter.

This method uses c.SendFile() to transfer the file. The optional options argument passes through to the underlying c.SendFile() call, and takes the exact same parameters.

func (*Context) End

func (c *Context) End()

End signals to the server that all of the response headers and body have been sent; other operations after it will be ignored.

Use to quickly end the response without any data. If you need to respond with data, instead use methods such as c.Send() and c.Json().

func (*Context) Format

func (c *Context) Format(m map[string]Handle)

Format responds to the Acceptable formats using an `map` of mime-type callbacks.

This method uses `req.accepted`, an array of acceptable types ordered by their quality values. When "Accept" is not present the first after sorted callback is invoked, otherwise the first match is used. When no match is performed the server responds with 406 "Not Acceptable".

Content-Type is set for you, however you may alter this within the callback using `c.Type()` or `c.Set("Content-Type", ...)`.

By default Soon passes an `error` with a `.status` of 406 to `Next(err)` if a match is not made. If you provide a `.default` callback it will be invoked instead.

func (*Context) Get

func (c *Context) Get(field string) string

Get the first value of response header associated with the given key. If there are no values associated with the key, Get returns "". It is case insensitive

func (*Context) GetLocal

func (c *Context) GetLocal(key string) (value interface{}, exists bool)

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

func (*Context) HeadersSent

func (c *Context) HeadersSent() bool

HeadersSent indicates if the response header was already sent.

func (*Context) Html

func (c *Context) Html(s string)

Html sends a html response.

func (*Context) Json

func (c *Context) Json(v interface{})

Json sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string.

func (*Context) Jsonp

func (c *Context) Jsonp(v interface{})

Jsonp sends a JSON response with JSONP support. This method is identical to c.Json(), except that it opts-in to JSONP callback support.

func (c *Context) Links(links map[string]string)

Links sets Link header field with the given `links`.

func (*Context) Location

func (c *Context) Location(url string)

Location sets the location header to `url`. The given `url` can also be "back", which redirects to the _Referrer_ or _Referer_ headers or "/".

func (*Context) MustBindHeader

func (c *Context) MustBindHeader(obj interface{})

MustBindHeader is a shortcut for c.MustBindWith(obj, binding.Header).

func (*Context) MustBindJSON

func (c *Context) MustBindJSON(obj interface{})

MustBindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).

func (*Context) MustBindQuery

func (c *Context) MustBindQuery(obj interface{})

MustBindQuery is a shortcut for c.MustBindWith(obj, binding.Query).

func (*Context) MustBindUri

func (c *Context) MustBindUri(obj interface{})

MustBindUri binds the passed struct pointer using binding.Uri. It will panic with HTTP 400 if any error occurs. See the binding package.

func (*Context) MustBindWith

func (c *Context) MustBindWith(obj interface{}, b binding.Binding)

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

func (*Context) MustGetLocal

func (c *Context) MustGetLocal(key string) interface{}

MustGetLocal returns the value for the given key if it exists, otherwise it panics.

func (*Context) Next

func (c *Context) Next(v ...interface{})

Next calls the next handler

func (*Context) Redirect

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

Redirect to the given `location` with `status`.

func (*Context) Render

func (c *Context) Render(r renderer.Renderer)

Render uses the specified renderer to deal with http response body.

func (*Context) ResetLocals

func (c *Context) ResetLocals(m map[string]interface{})

ResetLocals is used to reset and store new key/value pairs in locals for this context.

func (*Context) Send

func (c *Context) Send(s string)

Send is alias for String method

func (*Context) SendFile

func (c *Context) SendFile(filePath string, options ...renderer.FileOptions)

SendFile transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension. Unless the root option is set in the options object, path must be an absolute path to the file.

func (*Context) SendStatus

func (c *Context) SendStatus(code int)

SendStatus sets the response HTTP status code to statusCode and send its string representation as the response body.

func (*Context) Set

func (c *Context) Set(value ...interface{})

Set the response header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive;

To set multiple fields at once, pass a string map as the parameter.

func (*Context) SetLocal

func (c *Context) SetLocal(k string, v interface{})

SetLocal is used to store a new key/value pair in locals for this context. It also lazy initializes c.Locals if it was not used previously.

func (*Context) SetLocals

func (c *Context) SetLocals(m map[string]interface{})

SetLocals is used to store multi new key/value pairs in locals for this context. It also lazy initializes c.locals if it was not used previously.

func (*Context) Status

func (c *Context) Status(code int)

Status sets the HTTP status for the response.

func (*Context) String

func (c *Context) String(s string)

String sends a plain text response.

func (*Context) Type

func (c *Context) Type(s string)

Type sets the Content-Type HTTP header to the MIME type as determined by LookupMimeType() for the specified type. If type contains the “/” character, then it sets the Content-Type to type.

func (*Context) Vary

func (c *Context) Vary(fields ...string)

Vary adds `field` to Vary. If already present in the Vary set, then this call is simply ignored.

type ErrorHandle

type ErrorHandle func(interface{}, *Context)

ErrorHandle handles the error generated in route handler, and dispatch error and context objects into the error handler.

type Handle

type Handle func(*Context)

Handle is the handler function of router, router use it to handle matched http request, and dispatch a context object into the handler.

func DevLog

func DevLog() Handle

DevLog is a built-in middleware function in Soon. It just print simple log for development. For production environment, you can use `https://github.com/sirupsen/logrus`

func Static

func Static(root string, options ...renderer.FileOptions) Handle

Static is a built-in middleware function in Soon. It serves static files.

The root argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining req.url with the provided root directory. When a file is not found, instead of sending a 404 response, it instead calls next() to move on to the next middleware, allowing for stacking and fall-backs.

type HttpError

type HttpError internal.HttpError

type Params

type Params map[interface{}]string

Params contains all matched url params

func (Params) Get

func (p Params) Get(k interface{}) string

Get one param by key

func (Params) MarshalJSON

func (p Params) MarshalJSON() ([]byte, error)

MarshalJSON transforms the Params object to json

func (Params) Set

func (p Params) Set(k interface{}, v string)

Set one param with key

type Request

type Request struct {
	*http.Request

	// Params contains all matched url params of the request
	Params Params

	// BaseUrl is the URL path on which a router instance was mounted.
	//
	// Even if you use a path pattern to load the router,
	// the baseUrl property returns the matched string, not the pattern(s).
	BaseUrl string

	Hostname string
	Protocol string
	Path     string
	Query    url.Values
	Secure   bool
	Xhr      bool
	// contains filtered or unexported fields
}

Request is a wrapper for http.Request.

func NewRequest

func NewRequest(req *http.Request) *Request

NewRequest returns an instance of Request object

func (*Request) Accepts

func (r *Request) Accepts(types ...string) []string

Accepts checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. The method returns the best match, or if none of the specified content types is acceptable, returns nil (in which case, the application should respond with 406 "Not Acceptable").

The types value may be multiple MIME types string (such as “application/json”, "text/html"), extension names (such as “json”, "text"). The method returns the best match (if any).

func (*Request) AcceptsCharsets

func (r *Request) AcceptsCharsets(charsets ...string) []string

AcceptsCharsets reports accepted charsets or best fit based on `charsets`.

func (*Request) AcceptsEncodings

func (r *Request) AcceptsEncodings(encodings ...string) []string

AcceptsEncodings reports accepted encodings or best fit based on `encodings`.

func (*Request) AcceptsLanguages

func (r *Request) AcceptsLanguages(languages ...string) []string

AcceptsLanguages reports accepted languages or best fit based on `languages`.

func (*Request) ContentType

func (r *Request) ContentType() string

ContentType returns the Content-Type HTTP header of request

func (*Request) Fresh

func (r *Request) Fresh() bool

Fresh checks if the request is fresh, aka Last-Modified and/or the ETag still match.

func (*Request) Get

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

Get returns the specified HTTP request header field (case-insensitive match).

func (*Request) Is

func (r *Request) Is(types ...string) string

Is checks if the incoming request contains the "Content-Type" header field, and it contains the give mime `type`.

func (*Request) Range

func (r *Request) Range(size int64, combine bool) (util.Ranges, error)

Range parses `Range` header field, capping to the given `size`.

The "combine" argument can be set to `true` and overlapping & adjacent ranges * will be combined into a single range.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher

	// Returns the HTTP response status code of the current request.
	Status() int

	// Returns the number of bytes already written into the response http body.
	// See Written()
	Size() int

	// Writes the string into the response body.
	WriteString(string) (int, error)

	// Returns true if the response header was already written.
	HeaderWritten() bool

	// Returns true if the response body was already written.
	Written() bool

	// Forces to write the http header (status code + headers).
	// Http header changes After this will not be sent with response.
	WriteHeaderNow()
}

ResponseWriter interface

type Router

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

Router is a http.Handler which can be used to dispatch requests to different handler functions.

func NewRouter

func NewRouter(options ...*RouterOption) *Router

NewRouter returns a new initialized Router with default configuration. Sensitive and Strict is false by default.

func (*Router) ALL

func (r *Router) ALL(route string, handle Handle)

ALL means any http method, so this is a shortcut for router.Handle(http.MethodAny, route, handle)

func (*Router) DELETE

func (r *Router) DELETE(route string, handle Handle)

DELETE is a shortcut for router.Handle(http.MethodDelete, route, handle)

func (*Router) GET

func (r *Router) GET(route string, handle Handle)

GET is a shortcut for router.Handle(http.MethodGet, route, handle)

func (*Router) HEAD

func (r *Router) HEAD(route string, handle Handle)

HEAD is a shortcut for router.Handle(http.MethodHead, route, handle)

func (*Router) Handle

func (r *Router) Handle(method, route string, handle Handle)

Handle registers the handler for the http request which matched the method and route, and dispatch a context object into the handler.

func (*Router) OPTIONS

func (r *Router) OPTIONS(route string, handle Handle)

OPTIONS is a shortcut for router.Handle(http.MethodOptions, route, handle)

func (*Router) PATCH

func (r *Router) PATCH(route string, handle Handle)

PATCH is a shortcut for router.Handle(http.MethodPatch, route, handle)

func (*Router) POST

func (r *Router) POST(route string, handle Handle)

POST is a shortcut for router.Handle(http.MethodPost, route, handle)

func (*Router) PUT

func (r *Router) PUT(route string, handle Handle)

PUT is a shortcut for router.Handle(http.MethodPut, route, handle)

func (*Router) Param

func (r *Router) Param(name string, handle paramHandle)

Param registers a handler on router, and the handler will be triggered only by route parameters defined on router routes.

The handler will be called only once in a request-response cycle, even if the parameter is matched in multiple routes

func (*Router) Route

func (r *Router) Route(route string) *routerProxy

Route returns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use router.route() to avoid duplicate route naming and thus typing errors.

func (*Router) ServeHTTP

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

ServeHTTP writes reply headers and data to the ResponseWriter and then return. Router implements the interface http.Handler.

func (*Router) Use

func (r *Router) Use(params ...interface{})

Use the given middleware, or error handler, or mount another router, with optional path, defaulting to "/".

type RouterOption

type RouterOption struct {
	// When true the regexp will be case sensitive. (default: false)
	Sensitive bool

	// Preserve the req.params values from the parent router.
	// If the parent and the child have conflicting param names, the child’s value take precedence.
	MergeParams bool

	// When true the regexp won't allow an optional trailing delimiter to match. (default: false)
	Strict bool
}

RouterOption contains options for router, such as `Sensitive` and `Strict`

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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