pipeflow

package module
v0.0.0-...-2472918 Latest Latest
Warning

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

Go to latest
Published: Feb 29, 2020 License: MIT Imports: 7 Imported by: 0

README

Pipeflow

Pipeflow is a middleware container which is used in my own blog system.

Quick Look

package main

import (
    "fmt"
    "github.com/go-redis/redis"
    "net/http"
    "pipeflow"
    "reflect"
)

func main() {
	fb := pipeflow.NewBuilder()

	fb.Run(func(ctx pipeflow.HTTPContext) {
		fmt.Println("request URL: " + ctx.Request.RequestURI)
	})

	fb.UseCors([]string{"http://localhost:18080"}, nil, nil, nil)

	fb.Use(func(ctx pipeflow.HTTPContext, next func()) {
		fmt.Println("first")
		next()
		fmt.Println("first post action")
	})

	fb.Use(func(ctx pipeflow.HTTPContext, next func()) {
		fmt.Println("second")
		next()
		fmt.Println("second post action")
	})

	fb.Use(func(ctx pipeflow.HTTPContext, next func()) {
		if token := ctx.Request.Header.Get("token"); token != "" {
			next()
		} else {
			ctx.ResponseWriter.WriteHeader(http.StatusNonAuthoritativeInfo)
			_, _ = ctx.ResponseWriter.Write([]byte("NonAuthoritativeInfo"))
		}
	})

	redisClient := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379", Password: "password", DB: 0})
	if _, err := redisClient.Ping().Result(); nil != err {
		panic(err)
	}

	// fb.SetResource("redis", redisClient)
	// fb.SetResourceWithType(reflect.TypeOf(redisClient), redisClient)
	fb.SetResourceAlsoWithType("redis", redisClient)

	fb.Map("/hey", func(ctx pipeflow.HTTPContext) {
		var client, _ = ctx.GetResource("redis").(*redis.Client)
		var count, _ = client.Get("count").Int()
		client.Set("count", count+1, -1)
		_, _ = ctx.ResponseWriter.Write([]byte("hello"))
	}, pipeflow.HTTPPost, pipeflow.HTTPGet)

	fb.GET("/hello", func(ctx pipeflow.HTTPContext) {
		var client1, _ = ctx.GetResource("redis").(*redis.Client)
		var client2 = ctx.GetResourceByType(reflect.TypeOf((*redis.Client)(nil))).(*redis.Client)
		var count, _ = client1.Get("count").Int()
		client2.Set("count", count+1, -1)
		_, _ = ctx.ResponseWriter.Write([]byte("hello"))
	})

	fb.GET("/{foo}/hello?id&name", func(ctx pipeflow.HTTPContext) {
		_, _ = fmt.Fprintln(ctx.ResponseWriter, "foo = "+ctx.Vars["foo"]+", id = "+ctx.Request.Form.Get("id")+", name = "+ctx.Request.Form.Get("name"))
	})

	_ = http.ListenAndServe(":8888", fb.Build())
}

Request: http://localhost:8888/bar/hello?id=1&name=nomyfan

Response: foo = bar, id = 1, name = nomyfan

Console output:

request URL: /bar/hello?id=1&name=nomyfan
first
second
second post action
first post action

Documentation

Index

Constants

View Source
const (
	// HTTPGet GET
	HTTPGet = iota
	// HTTPHead HEAD
	HTTPHead
	// HTTPPost POST
	HTTPPost
	// HTTPPut PUT
	HTTPPut
	// HTTPDelete DELETE
	HTTPDelete
	// HTTPOptions OPTIONS
	HTTPOptions
	// HTTPTrace TRACE
	HTTPTrace
)

Variables

This section is empty.

Functions

func NotFoundMiddleware

func NotFoundMiddleware(ctx HTTPContext)

NotFoundMiddleware handles not found case

Types

type Cors

type Cors struct {
	AllowedOrigins map[string]bool
	AllowedMethods []string
	AllowedHeaders []string
	ExposedHeaders []string
}

Cors is used to handle CORS

func (*Cors) Handle

func (cors *Cors) Handle(ctx HTTPContext)

handle implements middleware

type Flow

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

Flow is main service register center

func (*Flow) GetResource

func (flow *Flow) GetResource(key string) interface{}

GetResource gets global singleton resource preset

func (*Flow) GetResourceByType

func (flow *Flow) GetResourceByType(key reflect.Type) interface{}

GetResourceByType gets global singleton resource preset by type

func (*Flow) ServeHTTP

func (flow *Flow) ServeHTTP(writer http.ResponseWriter, res *http.Request)

type FlowBuilder

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

func NewBuilder

func NewBuilder() *FlowBuilder

func (*FlowBuilder) Build

func (fb *FlowBuilder) Build() *Flow

Build returns a flow instance

func (*FlowBuilder) DELETE

func (fb *FlowBuilder) DELETE(path string, handler func(ctx HTTPContext))

func (*FlowBuilder) GET

func (fb *FlowBuilder) GET(path string, handler func(ctx HTTPContext))

func (*FlowBuilder) HEAD

func (fb *FlowBuilder) HEAD(path string, handler func(ctx HTTPContext))

func (*FlowBuilder) Map

func (fb *FlowBuilder) Map(path string, handler func(ctx HTTPContext), methods ...HTTPMethod)

Map is used to add request handler

func (*FlowBuilder) OPTIONS

func (fb *FlowBuilder) OPTIONS(path string, handler func(ctx HTTPContext))

func (*FlowBuilder) POST

func (fb *FlowBuilder) POST(path string, handler func(ctx HTTPContext))

func (*FlowBuilder) PUT

func (fb *FlowBuilder) PUT(path string, handler func(ctx HTTPContext))

func (*FlowBuilder) Run

func (fb *FlowBuilder) Run(middleware func(ctx HTTPContext))

Run runnable typed middleware will always invoke next

func (*FlowBuilder) RunPost

func (fb *FlowBuilder) RunPost(middleware func(ctx HTTPContext))

RunPost add middleware must be invoked after HTTP request dispatcher

func (*FlowBuilder) SetHTTPDispatcher

func (fb *FlowBuilder) SetHTTPDispatcher(hd HTTPRequestDispatcher)

SetHTTPDispatcher replaces default HTTP request handler. It can be nil.

func (*FlowBuilder) SetNotFound

func (fb *FlowBuilder) SetNotFound(nf func(ctx HTTPContext))

SetNotFound replaces the default not found middleware

func (*FlowBuilder) SetResource

func (fb *FlowBuilder) SetResource(key string, value interface{})

SetResource sets global singleton resource

func (*FlowBuilder) SetResourceAlsoWithType

func (fb *FlowBuilder) SetResourceAlsoWithType(key string, value interface{})

SetResourceAlsoWithType calls SetResource and SetResourceWithType

func (*FlowBuilder) SetResourceWithType

func (fb *FlowBuilder) SetResourceWithType(key reflect.Type, value interface{})

SetResourceWithType sets global singleton resource using it's type as key

func (*FlowBuilder) TRACE

func (fb *FlowBuilder) TRACE(path string, handler func(ctx HTTPContext))

func (*FlowBuilder) Use

func (fb *FlowBuilder) Use(middleware func(ctx HTTPContext, next func()))

Use registers middleware

func (*FlowBuilder) UseCors

func (fb *FlowBuilder) UseCors(origins []string, methods []string, headers []string, expose []string)

UseCors registers CORS middleware

func (*FlowBuilder) UsePost

func (fb *FlowBuilder) UsePost(middleware func(ctx HTTPContext, next func()))

UsePost add middleware to invoke after HTTP request dispatcher

type HTTPContext

type HTTPContext struct {
	Request        *http.Request
	ResponseWriter http.ResponseWriter
	Vars           map[string]string

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

HTTPContext is the request context wrapper

func (HTTPContext) GetResource

func (ctx HTTPContext) GetResource(key string) interface{}

GetResource gets global singleton resource preset

func (HTTPContext) GetResourceByType

func (ctx HTTPContext) GetResourceByType(key reflect.Type) interface{}

GetResourceByType gets global singleton resource preset by type

type HTTPMethod

type HTTPMethod int

HTTPMethod is enum of http methods

type HTTPRequestDispatcher

type HTTPRequestDispatcher interface {
	Map(path string, handler func(ctx HTTPContext), methods ...HTTPMethod)
	Handle(ctx HTTPContext)
}

Jump to

Keyboard shortcuts

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