helper

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2021 License: Apache-2.0 Imports: 16 Imported by: 0

README

http-helper

A simple http helper to support router and argument processing

Sample #1: handler with http.HandlerFunc

package main

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

func main() {
    r := helper.NewHelper()

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

    r.Get("/json/:msg", func(w http.ResponseWriter, r *http.Request) {
        c := helper.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 := helper.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 := helper.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 := helper.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 helper.Context

package main

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

func main() {
    r := helper.NewHelper()

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

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

    r.POST("/json", func(c *helper.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 *helper.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 *helper.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)

func WithLogger added in v0.1.2

func WithLogger(name string) negroni.Handler

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) Cookie

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

func (*Context) CookieValue added in v0.0.6

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) 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 added in v0.0.4

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

func (*Context) GetQueryParam added in v0.0.4

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) 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) 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 added in v0.2.0

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 added in v0.2.1

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

func (*Context) ReadJSON

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

func (*Context) ReadParams added in v0.0.4

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) Request

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

func (*Context) Response

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

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

type ContextHandlerFunc

type ContextHandlerFunc func(c *Context)

type HttpHelper

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

func NewHelper

func NewHelper(handlers ...negroni.Handler) *HttpHelper

func (*HttpHelper) NotFoundHandler

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

func (*HttpHelper) Run

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

func (*HttpHelper) ServeHTTP

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

func (*HttpHelper) Use

func (h *HttpHelper) Use(handler negroni.Handler)

func (*HttpHelper) UseFunc added in v0.0.2

func (h *HttpHelper) UseFunc(handlerFunc negroni.HandlerFunc)

func (*HttpHelper) UseHandler

func (h *HttpHelper) UseHandler(handler http.Handler)

func (*HttpHelper) UseHandlerFunc

func (h *HttpHelper) UseHandlerFunc(handlerFunc http.HandlerFunc)

type RouterGroup added in v0.1.0

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

func (*RouterGroup) DELETE added in v0.1.0

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

func (*RouterGroup) Delete added in v0.1.0

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

func (*RouterGroup) GET added in v0.1.0

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

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

func (*RouterGroup) Get added in v0.1.0

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

func (*RouterGroup) Group added in v0.1.0

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

func (*RouterGroup) HEAD added in v0.1.0

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

func (*RouterGroup) Head added in v0.1.0

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

func (*RouterGroup) OPTIONS added in v0.1.0

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

func (*RouterGroup) Options added in v0.1.0

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

func (*RouterGroup) PATCH added in v0.1.0

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

func (*RouterGroup) POST added in v0.1.0

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

func (*RouterGroup) PUT added in v0.1.0

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

func (*RouterGroup) Patch added in v0.1.0

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

func (*RouterGroup) Post added in v0.1.0

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

func (*RouterGroup) Put added in v0.1.0

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