mgin

package module
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: Apache-2.0 Imports: 20 Imported by: 0

README

mgin

A http framework to support router and argument processing

Sample #1: handler with http.HandlerFunc

package main

import (
    "github.com/rosbit/mgin"
    "net/http"
    "fmt"
)

func main() {
    r := mgin.NewMgin()

    r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
        c := mgin.NewHttpContext(w, r)
        c.String(http.StatusOK, "hello")
    })

    r.Get("/json/:msg", func(w http.ResponseWriter, r *http.Request) {
        c := mgin.NewHttpContext(w, r)
        msg := c.Param("msg")
        c.JSON(http.StatusOK, map[string]interface{} {
            "code": http.StatusOK,
            "msg": msg,
        })
    })

    r.Post("/json", func(w http.ResponseWriter, r *http.Request) {
        c := mgin.NewHttpContext(w, r)
        var i interface{}
        code, err := c.ReadJSON(&i)
        if err != nil {
            c.Error(code, err.Error())
            return
        }
        c.JSONPretty(http.StatusOK, i, " ")
    })

    r.Get("/jump", func(w http.ResponseWriter, r *http.Request) {
        c := mgin.NewHttpContext(w, r)
        url := c.QueryParam("u")
        if url == "" {
            c.Error(http.StatusBadRequest, "argument u expected")
            return
        }
        c.Redirect(http.StatusFound, url)
    })

    r.Post("/form/:name", func(w http.ResponseWriter, r *http.Request) {
        c := mgin.NewHttpContext(w, r)
        n := c.Param("name")
        v := c.FormValue(n)
        c.String(http.StatusOK, fmt.Sprintf("value of %s: %s\n", n, v))
    })

    r.Run()
    // or r.Run(":8080")
    // or http.ListenAndServe(":8080", r)
}

Sample #2: handler with argument mgin.Context

package main

import (
    "github.com/rosbit/http-mgin"
    "net/http"
    "fmt"
)

func main() {
    r := mgin.NewMgin()

    r.GET("/hello", func(c *mgin.Context) {
        c.String(http.StatusOK, "hello")
    })

    r.GET("/json/:msg", func(c *mgin.Context) {
        msg := c.Param("msg")
        c.JSON(http.StatusOK, map[string]interface{} {
            "code": http.StatusOK,
            "msg": msg,
        })
    })

    r.POST("/json", func(c *mgin.Context) {
        var i interface{}
        code, err := c.ReadJSON(&i)
        if err != nil {
            c.Error(code, err.Error())
            return
        }
        c.JSONPretty(http.StatusOK, i, " ")
    })

    r.GET("/jump", func(c *mgin.Context) {
        url := c.QueryParam("u")
        if url == "" {
            c.Error(http.StatusBadRequest, "argument u expected")
            return
        }
        c.Redirect(http.StatusFound, url)
    })

    r.POST("/form/:name", func(c *mgin.Context) {
        n := c.Param("name")
        v := c.FormValue(n)
        c.String(http.StatusOK, fmt.Sprintf("value of %s: %s\n", n, v))
    })

    r.Run()
    // or r.Run(":8080")
    // or http.ListenAndServe(":8080", r)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NotFoundHandler

func NotFoundHandler(c *Context) (err error)

Types

type Context

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

func NewHttpContext

func NewHttpContext(w http.ResponseWriter, r *http.Request) *Context

func (*Context) AddHeader

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

func (*Context) Attachment

func (c *Context) Attachment(file, name string) error

func (*Context) Blob

func (c *Context) Blob(code int, contentType string, b []byte) (err error)

func (*Context) Context added in v0.1.2

func (c *Context) Context() context.Context

func (*Context) Cookie

func (c *Context) Cookie(name string) (*http.Cookie, error)

func (*Context) CookieValue

func (c *Context) CookieValue(n string) string

func (*Context) Cookies

func (c *Context) Cookies() []*http.Cookie

func (*Context) Error

func (c *Context) Error(code int, msg string) (err error)

func (*Context) ErrorString added in v0.2.2

func (c *Context) ErrorString(err error) (errStr string)

func (*Context) File

func (c *Context) File(file string) (err error)

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

func (*Context) FormParams

func (c *Context) FormParams() (url.Values, error)

func (*Context) FormValue

func (c *Context) FormValue(name string) string

func (*Context) GetQueryArray

func (c *Context) GetQueryArray(name string) ([]string, bool)

func (*Context) GetQueryParam

func (c *Context) GetQueryParam(name string) (string, bool)

func (*Context) Header

func (c *Context) Header(name string) string

func (*Context) Inline

func (c *Context) Inline(file, name string) error

func (*Context) IsWebsocket added in v0.1.2

func (c *Context) IsWebsocket() bool

func (*Context) JSON

func (c *Context) JSON(code int, i interface{}) error

func (*Context) JSONBlob

func (c *Context) JSONBlob(code int, b []byte) (err error)

func (*Context) JSONPretty

func (c *Context) JSONPretty(code int, i interface{}, indent string) (err error)

func (*Context) Json added in v0.2.2

func (c *Context) Json(code int, i interface{}) (errStr string)

func (*Context) JsonBlob added in v0.2.2

func (c *Context) JsonBlob(code int, s string) (errStr string)

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

func (*Context) Param

func (c *Context) Param(name string) string

func (*Context) QueryParam

func (c *Context) QueryParam(name string) string

func (*Context) QueryParams

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

func (*Context) QueryString

func (c *Context) QueryString() string

func (*Context) ReadAndValidate

func (c *Context) ReadAndValidate(vals interface{}) (status int, err error)

read values from path, query string, form, header or cookie, store them in a struct specified by vals, then values are validated by using "github.com/go-playground/validator/v10". param name is specified by field tag. e.g.

var vals struct {
   V1 int    `path:"v1" validate:"gt=0"`     // read path param "v1", the value must be greater than 0
   V2 bool   `query:"v2"`                    // read query param "v2=xxx"
   V3 string `form:"v3" validate:"required"` // read form param "v3=xxx",
   V4 int    `header:"Content-Length"`       // read header "Content-Length"
   V5 []byte `cookie:"v5"`                   // read cookie "v4"
}
if status, err := c.ReadAndValidate(&vals); err != nil {
   c.Error(status, err.Error())
   return
}

func (*Context) ReadAndValidateJSON

func (c *Context) ReadAndValidateJSON(res interface{}, dumper ...io.Writer) (code int, err error)

func (*Context) ReadBody added in v0.2.2

func (c *Context) ReadBody() (body string, errStr string)

func (*Context) ReadJSON

func (c *Context) ReadJSON(res interface{}, dumper ...io.Writer) (code int, err error)

func (*Context) ReadJSONBody added in v0.2.2

func (c *Context) ReadJSONBody() (body interface{}, errStr string)

func (*Context) ReadParams

func (c *Context) ReadParams(vals interface{}) (status int, err error)

read values from path, query string, form, header or cookie, store them in a struct specified by vals. param name is specified by field tag. e.g.

var vals struct {
   V1 int    `path:"v1" optional`       // read path param "v1" optionally, any integer type (u)int8/16/32/64 is acceptable
   V2 bool   `query:"v2" ignore-error`  // read query param "v2=xxx", ignore error occurring
   V3 string `form:"v3"`                // read form param "v3=xxx", type string can be replace with []byte
   V4 int    `header:"Content-Length"`  // read header "Content-Length"
   V5 []byte `cookie:"v5" optional`     // read cookie "v4" opiontally
}
if status, err := c.ReadParams(&vals); err != nil {
   c.Error(status, err.Error())
   return
}

func (*Context) Redirect

func (c *Context) Redirect(code int, url string) error

func (*Context) RemoteAddr added in v0.1.7

func (c *Context) RemoteAddr() string

func (*Context) Request

func (c *Context) Request() *http.Request

func (*Context) Response

func (c *Context) Response() http.ResponseWriter

func (*Context) ResponseJSONEncoder added in v0.2.3

func (c *Context) ResponseJSONEncoder() *json.Encoder

func (*Context) SSEvent added in v0.1.2

func (c *Context) SSEvent(name string, message interface{})

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

func (*Context) SetHeader

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

func (*Context) Stream

func (c *Context) Stream(code int, contentType string, r io.Reader) (err error)

func (*Context) String

func (c *Context) String(code int, s string) error

func (*Context) StringBlob added in v0.2.2

func (c *Context) StringBlob(code int, ct string, s string) (errStr string)

func (*Context) Write added in v0.2.3

func (c *Context) Write(b []byte) (int, error)

func (*Context) WriteChunk added in v0.2.3

func (c *Context) WriteChunk(s string) (bytesWriten int, errStr string)

func (*Context) WriteHeader added in v0.2.3

func (c *Context) WriteHeader(statusCode int, contentType ...string)

type ContextHandlerFunc

type ContextHandlerFunc func(c *Context)

type Handler

type Handler = negroni.Handler
type negroni.Handler interface {
	ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
}

func CreateBodyDumpingHandler added in v0.2.0

func CreateBodyDumpingHandler(dumper io.Writer, prompt ...string) Handler

func WithLogger

func WithLogger(name string) Handler

func Wrap added in v0.1.1

func Wrap(handler http.Handler) Handler

func WrapFunc added in v0.1.1

func WrapFunc(handlerFunc http.HandlerFunc) Handler

func WrapMiddleFunc added in v0.1.1

func WrapMiddleFunc(handlerFunc HandlerFunc) Handler

type HandlerFunc

type HandlerFunc = negroni.HandlerFunc

type HandlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)

type MiniGin

type MiniGin struct {
	RouterGroup
	// contains filtered or unexported fields
}

func NewMgin

func NewMgin(handlers ...Handler) *MiniGin

func (*MiniGin) NotFoundHandler

func (hr *MiniGin) NotFoundHandler(h http.Handler)

func (*MiniGin) Run

func (h *MiniGin) Run(addr ...string)

func (*MiniGin) ServeHTTP

func (h *MiniGin) ServeHTTP(w http.ResponseWriter, r *http.Request)

type RouterGroup

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

func (*RouterGroup) DELETE

func (g *RouterGroup) DELETE(path string, h func(c *Context))

func (*RouterGroup) Delete

func (g *RouterGroup) Delete(path string, h http.HandlerFunc)

func (*RouterGroup) GET

func (g *RouterGroup) GET(pattern string, h func(c *Context))

------ context -----

func (*RouterGroup) Get

func (g *RouterGroup) Get(pattern string, h http.HandlerFunc)

func (*RouterGroup) Group

func (g *RouterGroup) Group(relPath string) *RouterGroup

func (*RouterGroup) HEAD

func (g *RouterGroup) HEAD(path string, h func(c *Context))

func (*RouterGroup) Head

func (g *RouterGroup) Head(path string, h http.HandlerFunc)

func (*RouterGroup) OPTIONS

func (g *RouterGroup) OPTIONS(path string, h func(c *Context))

func (*RouterGroup) Options

func (g *RouterGroup) Options(path string, h http.HandlerFunc)

func (*RouterGroup) PATCH

func (g *RouterGroup) PATCH(path string, h func(c *Context))

func (*RouterGroup) POST

func (g *RouterGroup) POST(path string, h func(c *Context))

func (*RouterGroup) PUT

func (g *RouterGroup) PUT(path string, h func(c *Context))

func (*RouterGroup) Patch

func (g *RouterGroup) Patch(path string, h http.HandlerFunc)

func (*RouterGroup) Post

func (g *RouterGroup) Post(path string, h http.HandlerFunc)

func (*RouterGroup) Put

func (g *RouterGroup) Put(path string, h http.HandlerFunc)

----- HandlerFunc ----

Jump to

Keyboard shortcuts

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