droplet

package module
v0.7.3 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2022 License: MIT Imports: 4 Imported by: 3

README

droplet

Decouple the service access layer so that the business only cares about input and output.

Background

When you write a http web server, you see above code everywhere. Such as gin:

func consumerCreate(c *gin.Context) {
	// read header
    requestId, _ := c.Get("X-Request-Id")
    param, exist := c.Get("requestBody")
    
    u4 := uuid.NewV4()
    
    if !exist || len(param.([]byte)) < 1 {
        err := errno.New(errno.InvalidParam)
        logger.WithField(conf.RequestId, requestId).Error(err.ErrorDetail())
        
        // write response
        c.AbortWithStatusJSON(http.StatusBadRequest, err.Response())
        return
    }
    
    if err := service.ConsumerCreate(param, u4.String()); err != nil {
    	// handler error
        handleServiceError(c, requestId, err)
        return
    }
    
    // write response
    c.JSON(http.StatusOK, errno.Succeed())
}

Wow, All of those codes is not related with business logic, right? So is here anyway could let us just care what application need and what application should return? That is why droplet was born.

Let We have a look at the code after used droplet:

type JsonInput struct {
    ID    string   `auto_read:"id,path" json:"id"`
    User  string   `auto_read:"user,header" json:"user"`
    IPs   []string `json:"ips"`
    Count int      `json:"count"`
    Body  []byte   `auto_read:"@body"`
}

func JsonInputDo(ctx droplet.Context) (interface{}, error) {
    input := ctx.Input().(*JsonInput)
    return input, nil
}

Here are things droplet help you to do:

  • Automatically read parameter from request by you input's tag
  • Check returns result and error, check error and convert it to a pre-define data structure
  • Write result to response

Droplet is not only that, please keep reading to find more.

Concept

Droplet is designed to work between the service access layer and the application layer, and is an intermediate layer framework. It provides a pipeline mechanism based on the reified Struct, and provides a lot of convenient middleware based on this.

Intall

go get github.com/api7/droplet

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Option = GlobalOpt{
		HeaderKeyRequestID: "X-Request-ID",
		ResponseNewFunc: func() HttpResponse {
			return &data.Response{}
		},
		Codec: []codec.Interface{
			&codec.Json{},
			&codec.MultipartForm{},
			&codec.Empty{},
		},
	}
)

Functions

func NewContext

func NewContext() *emptyContext

Types

type BasePipe

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

func NewPipe

func NewPipe() *BasePipe

func (*BasePipe) Add

func (p *BasePipe) Add(mw Middleware) *BasePipe

func (*BasePipe) AddIf

func (p *BasePipe) AddIf(mw Middleware, predicate bool) *BasePipe

func (*BasePipe) AddRange

func (p *BasePipe) AddRange(mws []Middleware) *BasePipe

func (*BasePipe) Run

func (p *BasePipe) Run(handler Handler, opts ...SetRunOpt) (interface{}, error)

func (*BasePipe) SetOrchestrator

func (p *BasePipe) SetOrchestrator(o Orchestrator) *BasePipe

type Context

type Context interface {
	Context() context.Context
	SetContext(context.Context)
	Get(key string) interface{}
	GetString(key string) string
	Set(key string, value interface{})
	SetInput(interface{})
	Input() interface{}
	SetOutput(interface{})
	Output() interface{}
	SetPath(path string)
	Path() string

	// Rewritten indicates whether the request path has been rewritten.
	Rewritten() bool
	// SetRewrite sets the rewrite flag.
	SetRewrite(rewritten bool)
}

type GlobalOpt

type GlobalOpt struct {
	HeaderKeyRequestID string
	ResponseNewFunc    func() HttpResponse
	Orchestrator       Orchestrator
	Codec              []codec.Interface
}

type Handler

type Handler func(ctx Context) (interface{}, error)

type HttpFileResponse

type HttpFileResponse interface {
	Get() (name, contentType string, content []byte)
}

type HttpResponse

type HttpResponse interface {
	Set(code int, msg string, data interface{})
	SetReqID(reqId string)
}

type Middleware

type Middleware interface {
	SetNext(next Middleware)
	Handle(ctx Context) error
}

func NewHandlerMiddleware

func NewHandlerMiddleware(handler Handler) Middleware

type MockMiddleware

type MockMiddleware struct {
	mock.Mock
}

MockMiddleware is an autogenerated mock type for the Middleware type

func (*MockMiddleware) Handle

func (_m *MockMiddleware) Handle(ctx Context) error

Handle provides a mock function with given fields: ctx

func (*MockMiddleware) Priority

func (_m *MockMiddleware) Priority() int

Priority provides a mock function with given fields:

func (*MockMiddleware) SetNext

func (_m *MockMiddleware) SetNext(next Middleware)

SetNext provides a mock function with given fields: next

type Orchestrator

type Orchestrator func(mws []Middleware) []Middleware

type RunOpt

type RunOpt struct {
	InitContext Context
}

type SetRunOpt

type SetRunOpt func(opt *RunOpt)

func InitContext

func InitContext(ctx Context) SetRunOpt

type SpecCodeHttpResponse

type SpecCodeHttpResponse interface {
	GetStatusCode() int
	HttpResponse
}

Directories

Path Synopsis
gin Module
gorestful Module

Jump to

Keyboard shortcuts

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