marmoset

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2021 License: MIT Imports: 14 Imported by: 17

README

marmoset

Go codecov Go Report Card Maintainability GoDoc

less than "web framework", just make your code a bit DRY.

func main() {
	router := marmoset.NewRouter()
	router.GET("/hello", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello!"))
	})
	http.ListenAndServe(":8080", router)
}

Features

  • Path parameters
  • Static directory
  • Request filters
    • Request-Context accessor, if you want
func main() {

	router := marmoset.NewRouter()

	router.GET("/foo", your.FooHttpHandlerFunc)
	router.POST("/bar", your.BarHttpHandlerFunc)

	// Path parameters available with regex like declaration
	router.GET("/users/(?P<name>[a-zA-Z0-9]+)/hello", func(w http.ResponseWriter, r *http.Request) {
		marmoset.Render(w).HTML("hello", map[string]string{
			// Path parameters can be accessed by req.FromValue()
			"message": fmt.Printf("Hello, %s!", r.FormValue("name")),
		})
	})

	// Set static file path
	router.Static("/public", "/your/assets/path")

	// Last added filter will be called first.
	server := marmoset.NewFilter(router).
		Add(&your.Filter{}).
		Add(&your.AnotherFilter{}).
		Add(&marmoset.ContextFilter{}). // if you want
		Server()

	http.ListenAndServe(":8080", server)
}

Documentation

Overview

Package marmoset ,reinventing the wheel

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func LoadViews

func LoadViews(p string) *template.Template

LoadViews ...

func RenderJSON

func RenderJSON(w http.ResponseWriter, status int, data interface{}) error

RenderJSON ...

func UseTemplate added in v0.5.0

func UseTemplate(tpl *template.Template)

Types

type ContextFilter

type ContextFilter struct {
	Filter
}

ContextFilter ... Only this `ContextFilter` can access `shared` itself. Add this filter for the last of your filter chain.

func (*ContextFilter) ServeHTTP

func (f *ContextFilter) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Filter

type Filter struct {
	http.Handler
	Next http.Handler
}

Filter ... Remember "Last added, First called"

Example
// Define routings.
router := NewRouter()
router.GET("/test", SampleController)

// Add Filters.
// If you want to use `Context`, `ContextFilter` must be added for the last.
// Remember "Last added, First called"
router.Apply(new(AuthFilter))

// Use `http.ListenAndServe` in real case, instead of httptest.
server := httptest.NewServer(router)

req, _ := http.NewRequest("GET", server.URL+"/test", nil)
req.Header.Add("X-User", `{"id":10,"name":"otiai10"}`)
res, _ := http.DefaultClient.Do(req)
fmt.Println("StatusCode:", res.StatusCode)

req, _ = http.NewRequest("GET", server.URL+"/test", nil)
req.Header.Add("X-User", `{"id":20,"name":"otiai20"}`)
res, _ = http.DefaultClient.Do(req)
fmt.Println("StatusCode:", res.StatusCode)
Output:

StatusCode: 200
StatusCode: 403

func (*Filter) SetNext

func (f *Filter) SetNext(next http.Handler)

SetNext ...

type Filterable

type Filterable interface {
	ServeHTTP(http.ResponseWriter, *http.Request)
	SetNext(http.Handler)
}

Filterable represents struct which can be a filter

type HTTPMethod

type HTTPMethod string

HTTPMethod ...

const (
	// MethodGet ...
	MethodGet HTTPMethod = http.MethodGet
	// MethodPost ...
	MethodPost HTTPMethod = http.MethodPost
	// MethodAny represents any method type
	MethodAny HTTPMethod = "*"
)

type P

type P map[string]interface{}

P is just a short hand of `map[string]interface{}` I don't want to write `map[string]interface{}` so repeatedly... :(

type Renderer

type Renderer struct {
	Pretty     bool
	EscapeHTML bool
	// contains filtered or unexported fields
}

Renderer ...

func Render

func Render(w http.ResponseWriter, pretty ...bool) Renderer

Render ...

func (Renderer) HTML

func (r Renderer) HTML(name string, data interface{}) error

HTML ...

func (Renderer) JSON

func (r Renderer) JSON(status int, data interface{}) error

JSON ...

type RequestContextMap

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

RequestContextMap ...

func Context

func Context() *RequestContextMap

Context to hide `shared`

func (*RequestContextMap) Flush

func (rctxmap *RequestContextMap) Flush(req *http.Request)

Flush ...

func (*RequestContextMap) Get

func (rctxmap *RequestContextMap) Get(req *http.Request) context.Context

Get ...

func (*RequestContextMap) Set

func (rctxmap *RequestContextMap) Set(req *http.Request, ctx context.Context)

Set ...

type Resolver

type Resolver interface {
	FindHandler(*http.Request) (http.HandlerFunc, bool)
}

Resolver only resolves

type Router

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

Router ...

Example (WithPathParams)
router := NewRouter()
var userID, filename string
router.GET("/users/(?P<user_id>[a-zA-Z0-9]+)", func(w http.ResponseWriter, r *http.Request) {
	userID = r.FormValue("user_id")
	w.WriteHeader(http.StatusOK)
})
router.GET("/uploads/(?P<filename>.+)", func(w http.ResponseWriter, r *http.Request) {
	filename = r.FormValue("filename")
	w.WriteHeader(http.StatusOK)
})
server := httptest.NewServer(router)
http.Get(server.URL + "/users/otiai10")
http.Get(server.URL + "/uploads/some_image.png")
fmt.Println("USER ID:", userID)
fmt.Println("FILENAME:", filename)
Output:

USER ID: otiai10
FILENAME: some_image.png

func NewRouter

func NewRouter() *Router

NewRouter ...

func (*Router) Apply

func (router *Router) Apply(filters ...Filterable) error

Apply applies Filters

func (*Router) FindHandler

func (router *Router) FindHandler(req *http.Request) (http.HandlerFunc, bool)

FindHandler ...

func (*Router) GET

func (router *Router) GET(path string, handler http.HandlerFunc) *Router

GET ...

func (*Router) Handle

func (router *Router) Handle(path string, handler http.Handler) *Router

Handle ...

func (*Router) NotFound added in v0.6.0

func (router *Router) NotFound(fun http.HandlerFunc)

func (*Router) POST

func (router *Router) POST(path string, handler http.HandlerFunc) *Router

POST ...

func (*Router) ServeHTTP

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

func (*Router) Static

func (router *Router) Static(p, dir string) *Router

Static ...

func (*Router) StaticRelative

func (router *Router) StaticRelative(p string, relativeDir string) *Router

StaticRelative ...

func (*Router) Subrouter

func (router *Router) Subrouter(child *Router) *Router

Subrouter ...

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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