shack

package module
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2022 License: MIT Imports: 18 Imported by: 0

README

Shack

Shack is a simple web framework written in Go.

Installation

go get -u github.com/ichxxx/shack

Examples

Quick start
import (
	"github.com/ichxxx/shack"
	"github.com/ichxxx/shack/middleware"
	"github.com/ichxxx/shack/rest"
)


func main() {
    r := shack.NewRouter()
    r.GET("/example", func(ctx *shack.Context) {
        rest.Resp(ctx).OK()
    }).With(middleware.Recovery())

    shack.Run(":8080", r)
    // or
    // http.ListenAndServe(":8080", r)
}
Parameters in path
func main() {
    r := shack.NewRouter()
    r.GET("/example/:id/*path", func(ctx *shack.Context) {
        id := ctx.Param("id")
        path := ctx.Param("path")
        ctx.JSON(shack.M{"id": id, "path": path})
        // or
        // rest.Resp(ctx).Data("id", id, "path", path).OK()
    })

    shack.Run(":8080", r)
}
Querystring parameters
type query struct {
    Foo int    `json:"foo"`
    Bar string `json:"bar"`
}

func main() {
    r := shack.NewRouter()
    r.GET("/example", func(ctx *shack.Context) {
        foo := ctx.QueryFlow("foo").Int()
        bar := ctx.Query("bar", "defaultBar")
        
        query := &query{}
        ctx.RawQueryFlow().Bind(query, "json")
        
        rest.Resp(ctx).Data(
            "foo", foo,
            "bar", bar,
            "query", query,
        )).OK()
    })

    shack.Run(":8080", r)
}
Json Body
type query struct {
    Foo int    `json:"foo"`
    Bar string `json:"bar"`
}

func main() {
    r := shack.NewRouter()
    r.GET("/example", func(ctx *shack.Context) {		
        query := &query{}
        ctx.BodyFlow().BindJson(query)
        
        rest.Resp(ctx).Data(
            "query", query,
        ).OK()
    })

    shack.Run(":8080", r)
}
Multipart/Urlencoded Form
type forms struct {
    Code int               `json:"code"`
    Msg  string            `json:"msg"`
    Data map[string]string `json:"data"`
}

func main() {
    r := shack.NewRouter()
    r.POST("/example", func(ctx *shack.Context) {
        data := ctx.Form("data")
        
        forms := &forms{}
        ctx.FormsFlow().Bind(forms, "json")
        
        rest.Resp(ctx).Data(
            "data", data,
            "forms", forms,
        ).OK()
    })

    shack.Run(":8080", r)
}
Router group and middleware
func main() {
    r := shack.NewRouter()
    r.Use(forAll)
    r.GET("/example", exampleHandler).With(middleware.AccessLog())
    r.Group("/api", func(r *shack.Router) {
        r.Use(onlyForApi)
        r.Handle("/article", articleHandler)
        
        r.Add(func(r *shack.Router) {
            r.Handle("/user", userHandler, http.MethodGet, http.MethodPost)
        })
    })
    
    shack.Run(":8080", r)
}
Mount router
func main() {
    r := shack.NewRouter()
    r.Mount("/api", apiRouter())
    
    shack.Run(":8080", r)
}

func apiRouter() *shack.Router {
    return shack.NewRouter()
}
Logger
func main() {
    shack.Logger("example").
        Level(shack.ErrorLevel).
        Encoding("json").
        Output("./logs").
        Enable()
    
    shack.Log.Error("some error",
        "timestamp", time.Now().Unix(),
    )
}
Config

Shack has a simple toml config parser built in.

You can use it as follows:

# test_config.toml
[test]
name = "shack"
port = 8080
foo_bar = ["1", "2"]
var TestConfig = &struct{
    // To use automatic parsing,
    // you have to combine shack.BaseConfig
    // in a struct.
    shack.BaseConfig
    Name    string
    Port    string
    FooBar  []int  `config:"foo_bar"`

}

func init() {
    // The second args `test` is the section's name in the toml file.
    shack.Config.Add(TestConfig, "test")
}

func main() {
    shack.Config.File("test_config.toml").Load()

    // After that, shack will parse the config automatically.
    // You can just use it.
    fmt.Println(TestConfig.Name)
    fmt.Println(TestConfig.Port)
    fmt.Println(TestConfig.FooBar)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	MaxMultipartMemory int64 = 8 << 20
)

Functions

func Run added in v0.1.5

func Run(addr string, router *Router, opts ...Option) error

func Shutdown added in v0.4.1

func Shutdown(addrs ...string)

Types

type Context

type Context struct {
	Request    Request
	Response   Response
	PathParams map[string]string

	Err error

	Bucket map[string]interface{}
	// contains filtered or unexported fields
}

func (*Context) Abort

func (c *Context) Abort()

Abort prevents pending handlers from being called.

func (*Context) Error added in v0.2.1

func (c *Context) Error(err error)

Error sets the first non-nil error of the context.

func (*Context) Get

func (c *Context) Get(key string) (value interface{}, ok bool)

Get returns the value for the given key in the context bucket.

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.

func (*Context) Set

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

Set stores a key/value pair in the context bucket.

type Handler added in v0.4.1

type Handler func(*Context)

type Map added in v0.4.1

type Map map[string]interface{}

Map is a shortcut for map[string]interface{}

type Option added in v0.4.1

type Option struct {
	ShutdownFunc func()
}

type Request added in v0.4.1

type Request struct {
	*http.Request
	// contains filtered or unexported fields
}

func (*Request) BindJSON added in v0.4.1

func (r *Request) BindJSON(dst interface{}) error

func (*Request) BindQuery added in v0.4.1

func (r *Request) BindQuery(dst interface{}, tag ...string) error

func (*Request) Body added in v0.4.1

func (r *Request) Body() []byte

Body returns the request body.

func (*Request) File added in v0.4.1

func (r *Request) File(key string) []*multipart.FileHeader

func (*Request) Forms added in v0.4.1

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

func (*Request) Header added in v0.4.1

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

func (*Request) JSON added in v0.4.1

func (r *Request) JSON(key string) interface{}

func (*Request) Method added in v0.4.1

func (r *Request) Method() string

func (*Request) Path added in v0.4.1

func (r *Request) Path() string

func (*Request) Query added in v0.4.1

func (r *Request) Query(key string, defaultValue ...string) string

func (*Request) RawQuery added in v0.4.1

func (r *Request) RawQuery() string

func (*Request) URI added in v0.4.1

func (r *Request) URI() string

type Response added in v0.4.1

type Response struct {
	http.ResponseWriter
	StatusCode int
	// contains filtered or unexported fields
}

func (*Response) Flush added in v0.4.1

func (r *Response) Flush() error

func (*Response) Header added in v0.4.1

func (r *Response) Header(key, value string)

func (*Response) JSON added in v0.4.1

func (r *Response) JSON(data interface{}) error

func (*Response) Status added in v0.4.1

func (r *Response) Status(code int)

Status sets the http status of response.

func (*Response) String added in v0.4.1

func (r *Response) String(s string) error

func (*Response) Write added in v0.4.1

func (r *Response) Write(data []byte) error

type Router

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

func NewRouter

func NewRouter() *Router

func (*Router) Add added in v0.2.0

func (r *Router) Add(routeFunc func(r *Router)) *Router

Add is a shortcut of Group("/", fn).

func (*Router) DELETE

func (r *Router) DELETE(pattern string, handler Handler) *trie

func (*Router) GET

func (r *Router) GET(pattern string, handler Handler) *trie

func (*Router) Group

func (r *Router) Group(pattern string, routeFunc func(r *Router)) *Router

Group adds a sub-Router to the group along a `pattern` string.

func (*Router) HEAD

func (r *Router) HEAD(pattern string, handler Handler) *trie

func (*Router) Handle

func (r *Router) Handle(pattern string, handler Handler) *trie

func (*Router) MethodNotAllowed

func (r *Router) MethodNotAllowed(handler Handler)

MethodNotAllowed defines a handler to respond whenever a method is not allowed.

func (*Router) Mount

func (r *Router) Mount(pattern string, router *Router)

Mount attaches another router along a `pattern` string.

func (*Router) NotFound

func (r *Router) NotFound(handler Handler)

NotFound defines a handler to respond whenever a route could not be found.

func (*Router) OPTIONS

func (r *Router) OPTIONS(pattern string, handler Handler) *trie

func (*Router) PATCH

func (r *Router) PATCH(pattern string, handler Handler) *trie

func (*Router) POST

func (r *Router) POST(pattern string, handler Handler) *trie

func (*Router) PUT

func (r *Router) PUT(pattern string, handler Handler) *trie

func (*Router) ServeHTTP

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

func (*Router) Use

func (r *Router) Use(middlewares ...Handler)

Use appends one or more middlewares onto the router.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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