mir

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2019 License: Apache-2.0 Imports: 6 Imported by: 10

README

Mir

Build Status codecov GoDoc Release

Mir is used for register handler to http router(eg: Gin, Chi, Echo, Iris, Macaron, Mux, httprouter) depends on struct tag string info that defined in logic object's struct type field.

Usage (eg: gin backend)
  • Get Mir.Gin module first
go get github.com/alimy/mir/module/gin@master
  • Then happy in codding enjoy your heart...
package main

import(
	"github.com/alimy/mir"
	"github.com/gin-gonic/gin"
	"net/http"
	
	mirE "github.com/alimy/mir/module/gin"
)

type site struct {
	Chain mir.Chain     `mir:"-"`
	Group mir.Group     `mir:"v1"`
	index mir.Get       `mir:"/index/"`
	articles mir.Get    `mir:"/articles/:category/#GetArticles"`
}

// Index handler of the index field that in site struct, the struct tag indicate
// this handler will register to path "/index/" and method is http.MethodGet.
func (h *site) Index(c *gin.Context) {
	c.String(http.StatusOK, "get index data")
}

// GetArticles handler of articles indicator that contains Host/Path/Queries/Handler info.
// Path info is the second or first(if no host info) segment start with '/'(eg: /articles/:category/#GetArticles)
// Handler info is forth info start with '#' that indicate real handler method name(eg: GetArticles).if no handler info will
// use field name capital first char as default handler name(eg: if articles had no #GetArticles then the handler name will
// is Articles) 
func (h *site) GetArticles(c *gin.Context) {
	c.String(http.StatusOK, "get articles data")
}

func main() {
	//Create a new gin engine
	engine := gin.New()
	
	// Register handler to engine by mir
	mirE.Register(engine, &site{Chain: gin.HandlersChain{gin.Logger()}})
	
	// Start gin engine serve
	engine.Run()
}

Sample code use mir build web application

Documentation

Overview

Package mir provider yet another style to write http handler used register to router.

Define handler in struct type like below:

type entry struct {
	count uint32

	Chain mir.Chain     `mir:"-"`
	Group mir.Group     `mir:"v1"`
	index mir.Get       `mir:"/index/"`
	articles mir.Get    `mir:"//{subdomain}.example.com/articles/{category}/{id:[0-9]+}?filter={filter}&foo=bar&num={num:[0-9]+}#GetArticles"`
}

// Index handler of the index field that in site struct, the struct tag indicate
// this handler will register to path "/index/" and method is http.MethodGet.
func (e *entry) Index(c Index(rw http.ResponseWriter, r *http.Request) {
	e.count++
	rw.WriteHeader(200)
	rw.Write([]byte("Index"))
}

// GetArticles handler of articles indicator that contains Host/Path/Queries/Handler info.
func (e *entry) GetArticles(rw http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	result := strings.Join([]string{
		"GetArticles",
		vars["subdomain"],
		vars["category"],
		vars["id"],
		vars["filter"],
		vars["num"],
	}, ":")
	rw.WriteHeader(200)
	rw.Write([]byte(result))
}

// GetArticles handler of articles indicator that contains Host/Path/Queries/Handler info.
// Host info is the first segment start with '//'(eg:{subdomain}.domain.com)
// Path info is the second or first(if no host info) segment start with '/'(eg: /articles/{category}/{id:[0-9]+}?{filter})
// Queries info is the third info start with '?' and delimiter by '&'(eg: {filter}&{pages})
// Handler info is forth info start with '#' that indicate real handler method name(eg: GetArticles).if no handler info will
// use field name capital first char as default handler name(eg: if articles had no #GetArticles then the handler name will
// is Articles)
func (h *site) GetArticles(c gin.Context) {
	c.String(http.StatusOK, "get articles data")
}

// mirChain chain used to register to engine
func mirChain() []mux.MiddlewareFunc {
	return []mux.MiddlewareFunc{
		simpleMiddleware,
		simpleMiddleware,
	}
}

func simpleMiddleware(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Do nothing just for test
		h.ServeHTTP(w, r)
	})
}

Then register entry such use mux router:

import (
	"github.com/alimy/mir"
	"github.com/gorilla/mux"
	"net/http"
	"log"

	mirE "github.com/alimy/mir/module/mux"
)

func main() {
	// Create a new mux router instance
	r := mux.NewRouter()

	// Register handler to engine by mir
	mirE.Register(r, &entry{Chain: mirChain()})

	// Bind to a port and pass our router in
	log.Fatal(http.ListenAndServe(":8000", r))
}

Index

Constants

View Source
const (
	MethodGet     = http.MethodGet
	MethodHead    = http.MethodHead
	MethodPost    = http.MethodPost
	MethodPut     = http.MethodPut
	MethodPatch   = http.MethodPatch
	MethodDelete  = http.MethodDelete
	MethodConnect = http.MethodConnect
	MethodOptions = http.MethodOptions
	MethodTrace   = http.MethodTrace

	// MethodAny indicate all method above used engine register routes
	MethodAny = "ANY"
)

Common HTTP methods.

View Source
const (
	// DefaultTag indicate default mir's struct tag name
	DefaultTag = "mir"
)

Variables

This section is empty.

Functions

func Register

func Register(e Engine, entries ...interface{}) error

Register use entries's info to register handler to give engine.

func RegisterDefault added in v0.2.0

func RegisterDefault(entries ...interface{}) error

RegisterDefault use entries's info to register handler to default engine. You must call SetDefault(...) setup a default engine first or return error.

func SetDefault added in v0.2.0

func SetDefault(e Engine)

SetDefault set default engine for register handler.

func SetTag added in v0.4.0

func SetTag(name string)

SetTag set custom mir's struct tag name(eg: mir)

Types

type Any

type Any interface{}

Any indicator a Any method handler used placeholder register info in struct tag. This is mean register handler that all http.Method* include(GET, PUT, POST, DELETE, HEAD, PATCH, OPTIONS)

type Chain added in v0.3.0

type Chain interface{}

Chain indicator a Handler slice used register Middleware to router by group

type Connect

type Connect interface{}

Connect indicator a CONNECT method handler used placeholder register info in struct tag

type Delete

type Delete interface{}

Delete indicator a DELETE method handler used placeholder register info in struct tag

type Engine

type Engine interface {
	Register([]*TagMir) error
}

Engine register mir tag info's handler to engine. Other http engine router can implement this interface then use mir to register handler engine(eg: gin,echo,mux,httprouter)

type Get

type Get interface{}

Get indicator a GET method handler used placeholder register info in struct tag

type Group

type Group string

Group indicator a default group for handler to register to server engine

type Head interface{}

Head indicator a HEAD method handler used placeholder register info in struct tag

type Options

type Options interface{}

Options indicator a OPTIONS method handler used placeholder register info in struct tag

type Patch

type Patch interface{}

Patch indicator a PATCH method handler used placeholder register info in struct tag

type Post

type Post interface{}

Post indicator a POST method handler used placeholder register info in struct tag

type Put

type Put interface{}

Put indicator a PUT method handler used placeholder register info in struct tag

type TagField

type TagField struct {
	ChainFunc interface{} // ChainFunc indicate field inline chain function
	Handler   interface{} // Handler indicate handler method
	// contains filtered or unexported fields
}

TagField indicate mir tag info used to register route info to engine

type TagMir added in v0.2.0

type TagMir struct {
	Group  string
	Chain  Chain
	Fields []*TagField
}

TagMir contains TagFields by group

func TagMirFrom added in v0.2.0

func TagMirFrom(entries ...interface{}) ([]*TagMir, error)

TagMirFrom build TagMir items from entries slice

type Trace

type Trace interface{}

Trace indicator a TRACE method handler used placeholder register info in struct tag

Directories

Path Synopsis
engine
chi Module
echo Module
fiber Module
gin Module
hertz Module
httprouter Module
iris Module
macaron Module
mux Module
mirc module
module
chi Module
echo Module
example Module
gin Module
httprouter Module
iris Module
macaron Module
mux Module

Jump to

Keyboard shortcuts

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