td

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

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

Go to latest
Published: Apr 16, 2024 License: Apache-2.0 Imports: 12 Imported by: 4

README

malatd

简洁+易用的Golang Web框架

使用

查看详细使用说明

NAME:
   Malatd project command - A deployment tools of malatd frameware

USAGE:
   malatd [global options] command [command options] [arguments...]

VERSION:
   1.0.0

AUTHOR:
   swxctx

COMMANDS:
   gen      Generate a malatd project
   run      Compile and run go project
   doc      Generate a project README.md(malatd doc || malatd doc -r ${root_group})
   help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --help, -h     show help
   --version, -v  print the version
普通使用
package main

import (
	td "github.com/swxctx/malatd"
)

/*
	http://127.0.0.1:8080/malatd
*/
func main() {
	// new server
	srv := td.NewServer(td.NewSrvConfig())

	// api router
	srv.Get("/malatd", malatdApi)
	srv.Post("/malatd", malatdApi)
	srv.Run()
}

// malatd
func malatdApi(ctx *td.Context) {
	ctx.RenderString("malatd")
}
使用插件
package main

import (
	td "github.com/swxctx/malatd"
)

/*
	http://127.0.0.1:8080/malatd?id=123
*/
func main() {
	// new server
	srv := td.NewServer(
		td.NewSrvConfig(),
		tokenPlugin,
	)

	// api router
	srv.Get("/malatd/v1", authPlugin, malatdApi)
	srv.Run()
}

// tokenPlugin
func tokenPlugin(ctx *td.Context) {
	xlog.Infof("tokenPlugin: current tokenPlugin")
	xlog.Infof("tokenPlugin: Params-> %v", ctx.Request.URL.Query().Get("id"))
	ctx.Next()
}

// authHandle
func authPlugin(ctx *td.Context) {
	xlog.Infof("authPlugin: current authPlugin")
	xlog.Infof("authPlugin: Params-> %v", ctx.Request.URL.Query().Get("id"))
	ctx.Next()
}

// malatd
func malatdApi(ctx *td.Context) {
	xlog.Infof("malatdApi: current malatdApi")
	xlog.Infof("malatdApi: Params-> %v", ctx.Request.URL.Query().Get("id"))
	ctx.RenderString("hello malatd")
}
参数绑定
package main

import (
	"github.com/swxctx/malatd/binding"

	td "github.com/swxctx/malatd"
)

/*
	http://127.0.0.1:8080/malatd
*/
func main() {
	// new server
	srv := td.NewServer(td.NewSrvConfig())

	// api router
	srv.Get("/malatd1", malatdApi1Handle)
	srv.Post("/malatd2", malatdApi2Handle)
	srv.Run()
}

type Args struct {
	A int    `query:"a" json:"a"`
	B string `query:"b" json:"b"`
	C string `json:"c"`
}

type Result struct {
	A int    `json:"a"`
	B string `json:"b"`
	C string `json:"c"`
}

var (
	binder      = binding.JSON
	binderQuery = binding.QUERY
)

// malatdApi1Handle
func malatdApi1Handle(ctx *td.Context) {
	// bind params
	params := new(Args)
	err := binderQuery.Bind(ctx, params)
	if err != nil {
		ctx.RenderRerr(td.RerrInternalServer.SetReason(err.Error()))
		return
	}

	// api逻辑调用
	result, rerr := malatdApi1Logic(ctx, params)
	if rerr != nil {
		ctx.RenderRerr(rerr)
		return
	}
	ctx.Render(result)
}

// malatdApi1Logic
func malatdApi1Logic(ctx *td.Context, arg *Args)(*Result, *td.Rerror) {
	xlog.Infof("Args-> %v", arg)
	result := &Result{
		A: arg.A,
		B: arg.B,
		C: arg.C,
	}
	return result, nil
}

// malatdApi2Handle
func malatdApi2Handle(ctx *td.Context) {
	// bind params
	params := new(Args)
	err := binder.Bind(ctx, params)
	if err != nil {
		ctx.RenderRerr(td.RerrInternalServer.SetReason(err.Error()))
		return
	}

	err = binderQuery.Bind(ctx, params)
	if err != nil {
		ctx.RenderRerr(td.RerrInternalServer.SetReason(err.Error()))
		return
	}

	// api逻辑调用
	result, rerr := malatdApi2Logic(ctx, params)
	if rerr != nil {
		ctx.RenderRerr(rerr)
		return
	}
	ctx.Render(result)
}

func malatdApi2Logic(ctx *td.Context, arg *Args)(*Result, *td.Rerror) {
	xlog.Infof("Args-> %v", arg)
	result := &Result{
		A: arg.A,
		B: arg.B,
		C: arg.C,
	}
	return result, nil
}

Documentation

Index

Constants

View Source
const (
	// 公用错误码
	CodeUnknownError = -1
	CodeWriteFailed  = 104

	CodeInvalidParameter    = 299
	CodeBadPacket           = 400
	CodeUnauthorized        = 401
	CodeNotFound            = 404
	CodeInternalServerError = 500
	CodeBadGateway          = 502
)

Variables

Functions

func BytesToString

func BytesToString(b []byte) string

BytesToString []byte to string

func CodeMessage

func CodeMessage(rerrCode int) string

CodeMessage

func StringToBytes

func StringToBytes(s string) []byte

StringToBytes

func ToUriPath

func ToUriPath(name string) string

ToUriPath maps struct(func) name to URI path.

Types

type Context

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

Context

func (*Context) ContentType

func (c *Context) ContentType() string

ContentType

func (*Context) ContentTypeSet

func (c *Context) ContentTypeSet(value string)

ContentType

func (*Context) GetRemoteIP

func (c *Context) GetRemoteIP() string

GetRemoteIP

func (*Context) Head

func (c *Context) Head(key string) string

Head

func (*Context) HeadSet

func (c *Context) HeadSet(key, value string)

HeadSet

func (*Context) Method

func (c *Context) Method() string

Method

func (*Context) Next

func (c *Context) Next()

Next

func (*Context) Query

func (c *Context) Query(key string) string

Query

func (*Context) QueryValues

func (c *Context) QueryValues() url.Values

QueryValues

func (*Context) Redirect

func (c *Context) Redirect(targetUrl string, code int)

Redirect request redirect

func (*Context) RemoteAddr

func (c *Context) RemoteAddr() string

RemoteAddr

func (*Context) Render

func (c *Context) Render(obj interface{}) (int, error)

Render response json

func (*Context) RenderRerr

func (c *Context) RenderRerr(rerr *Rerror) (int, error)

RenderRerr response rerror

func (*Context) RenderString

func (c *Context) RenderString(resp string) (int, error)

Render response json

func (*Context) RequestURI

func (c *Context) RequestURI() string

RequestURI

func (*Context) Stream

func (c *Context) Stream(step func(w io.Writer) bool) error

Stream 方法用于发送流式响应

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent

type Plugin

type Plugin func(ctx *Context)

Plugin

type Plugins

type Plugins []Plugin

Plugins

type Rerror

type Rerror struct {
	// Code 错误状态码
	Code int `json:"code"`
	// Message 错误信息
	Message string `json:"message"`
	// Reason 错误原因
	Reason string `json:"reason"`
}

Rerror 发生错误时返回的错误信息 response error

func NewRerror

func NewRerror(code int, message, reason string) *Rerror

NewRerror

func (*Rerror) MarshalRerror

func (r *Rerror) MarshalRerror() ([]byte, error)

MarshalRerror 错误信息编码

func (*Rerror) SetCode

func (r *Rerror) SetCode(message string) *Rerror

SetCode

func (*Rerror) SetMessage

func (r *Rerror) SetMessage(message string) *Rerror

SetMessage

func (*Rerror) SetReason

func (r *Rerror) SetReason(reason string) *Rerror

SetReason

func (*Rerror) String

func (r *Rerror) String() string

String prints error info.

func (*Rerror) UnmarshalRerror

func (r *Rerror) UnmarshalRerror(data []byte) error

UnmarshalRerror 解析错误信息

type Router

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

Router

func (*Router) AddPlugin

func (r *Router) AddPlugin(plugins ...Plugin)

AddPlugin

func (*Router) Get

func (r *Router) Get(relativePath string, plugins ...Plugin)

Get

func (*Router) Group

func (r *Router) Group(relativePath string, plugins ...Plugin) *Router

注册组路由

func (*Router) Options

func (r *Router) Options(relativePath string, plugins ...Plugin)

Options

func (*Router) Post

func (r *Router) Post(relativePath string, plugins ...Plugin)

Post

type Server

type Server struct {
	// 路由组
	Router
	// contains filtered or unexported fields
}

Server

func NewServer

func NewServer(srvCfg *SrvConfig, plugins ...Plugin) *Server

NewServer

func (*Server) Run

func (srv *Server) Run() error

ListenAndServe fast http listen

type SrvConfig

type SrvConfig struct {
	// 监听地址[host:port]
	Address string `yaml:"address"`
}

SrvConfig

func NewSrvConfig

func NewSrvConfig() *SrvConfig

NewSrvConfig

Directories

Path Synopsis
cmd
create/tpl
Package main generated by go-bindata.
Package main generated by go-bindata.
run
run/fsnotify
Package fsnotify implements file system notification.
Package fsnotify implements file system notification.
Package httprouter is a trie based high performance HTTP request router.
Package httprouter is a trie based high performance HTTP request router.

Jump to

Keyboard shortcuts

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