sgo

package module
v0.0.0-...-2b9f4e1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2021 License: MIT Imports: 16 Imported by: 0

README

SGo

SGo is a simple, light and fast Web framework written in Go.

The source is easy to learn, then you can make your own Go Web Framework!

Features

  • Pretty and fast router - based on radix tree
  • Middleware Support
  • Friendly to REST API
  • No regexp or reflect
  • QUIC Support
  • Inspired by many excellent Go Web framework

Installation

go get github.com/AmyangXYZ/sgo

Example

Simple
package main

import (
    "github.com/AmyangXYZ/sgo"
)

func main() {
    app := sgo.New()
    app.GET("/", func(ctx *sgo.Context) error {
        return ctx.Text(200, "Hello Sweetie")
    })
    app.Run(":16311")
}

Further
package main

import (
    "html/template"
    "net/http"
    "os"
    "time"

    "github.com/AmyangXYZ/sgo"
    "github.com/AmyangXYZ/sgo/middlewares"
    "github.com/dgrijalva/jwt-go"
)

var (
    tplDir     = "templates"
    listenPort = ":16311"
    secretKey  = "CuteSweetie"
    jwtSkipper = func(ctx *sgo.Context) bool {
        if ctx.Path() == "/" ||
            (ctx.Path() == "/api" && ctx.Method() == "GET") ||
            (ctx.Path() == "/login" && ctx.Method() == "POST") ||
            (len(ctx.Path()) > 8 && ctx.Path()[0:8] == "/static/") {
            return true
        }
        return false
    }
)

func main() {
    app := sgo.New()
    app.SetTemplates(tplDir, template.FuncMap{})

    app.USE(middlewares.Logger(os.Stdout, middlewares.DefaultSkipper))
    app.USE(middlewares.JWT("Header", secretKey, jwtSkipper))

    app.GET("/", home)
    app.GET("/static/*files", static)
    app.GET("/api", biu)
    app.POST("/api", hello)
    app.POST("/login", login)
    app.GET("/usr/:user", usr)

    app.Run(listenPort)

    // Or use QUIC
    // app.RunOverQUIC(listenPort, "fullchain.pem", "privkey.pem")
}

func home(ctx *sgo.Context) {
    ctx.Set("baby", "Sweetie")
    ctx.Render(200, "index")
}

func static(ctx *sgo.Context) {
    staticHandle := http.StripPrefix("/static",
        http.FileServer(http.Dir("./static")))
    staticHandle.ServeHTTP(ctx.Resp, ctx.Req)
}

func biu(ctx *sgo.Context) {
    ctx.Text(200, "biu")
}

func login(ctx *sgo.Context) {
    usr := ctx.Param("usr")
    pwd := ctx.Param("pwd")
    if usr == "Amyang" && pwd == "biu" {
        token := jwt.New(jwt.SigningMethodHS256)
        claims := token.Claims.(jwt.MapClaims)
        claims["name"] = "Amyang"
        claims["admin"] = true
        claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
        t, _ := token.SignedString([]byte(secretKey))
        ctx.JSON(200, 1, "success", map[string]string{"SG_Token": t})
        return
    }
    ctx.JSON(200, 0, "username or password error", nil)
}

func api(ctx *sgo.Context) {
    ctx.JSON(200, 1, "success", map[string]string{"version": "1.1"})
}

func hello(ctx *sgo.Context) {
    usr := ctx.Get("userInfo").(*jwt.Token)
    claims := usr.Claims.(jwt.MapClaims)
    name := claims["name"].(string)
    ctx.Text(200, "Hello "+name)
}

func usr(ctx *sgo.Context) {
    ctx.Text(200, "Welcome home, "+ctx.Param("user"))
}

example

My Blog is also powered by SGo.

License

MIT

Documentation

Index

Constants

View Source
const (
	CONNECT = http.MethodConnect
	DELETE  = http.MethodDelete
	GET     = http.MethodGet
	HEAD    = http.MethodHead
	OPTIONS = http.MethodOptions
	PATCH   = http.MethodPatch
	POST    = http.MethodPost
	PUT     = http.MethodPut
	TRACE   = http.MethodTrace
)

HTTP methods

Variables

This section is empty.

Functions

func MethodNotAllowedHandler

func MethodNotAllowedHandler(ctx *Context) error

MethodNotAllowedHandler .

func NotFoundHandler

func NotFoundHandler(ctx *Context) error

NotFoundHandler .

Types

type Context

type Context struct {
	Req  *http.Request
	Resp *responseWriter
	// contains filtered or unexported fields
}

Context provide a HTTP context for SGo.

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request, sg *SGo) *Context

NewContext .

func (*Context) Error

func (ctx *Context) Error(code int, error string)

Error .

func (*Context) FormFile

func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile gets file from request.

func (*Context) Get

func (ctx *Context) Get(key string) interface{}

Get data in context.

func (*Context) GetCookie

func (ctx *Context) GetCookie(name string) string

GetCookie .

func (*Context) Gets

func (ctx *Context) Gets() map[string]interface{}

Gets all data in context.

func (*Context) Init

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

Init the context gotten from sync pool.

func (*Context) JSON

func (ctx *Context) JSON(code, flag int, msg string, data interface{}) error

JSON response JSON data. {flag: 1, msg: "success", data: ...}

func (*Context) JSONP

func (ctx *Context) JSONP(code int, callback string, data interface{}) error

JSONP return JSONP data.

func (*Context) Method

func (ctx *Context) Method() string

Method .

func (*Context) Next

func (ctx *Context) Next()

Next execute next middleware or router.

func (*Context) Param

func (ctx *Context) Param(key string) string

Param returns specific params

func (*Context) Params

func (ctx *Context) Params() url.Values

Params returns all params

func (*Context) Path

func (ctx *Context) Path() string

Path returns URL Path string.

func (*Context) Redirect

func (ctx *Context) Redirect(code int, url string)

Redirect redirects the request

func (*Context) Referer

func (ctx *Context) Referer() string

Referer returns request referer.

func (*Context) Render

func (ctx *Context) Render(code int, tplname string) error

Render sgo.templates with stored data.

func (*Context) SaveFile

func (ctx *Context) SaveFile(name, saveDir string) (string, error)

SaveFile saves the form file and returns the filename.

func (*Context) Set

func (ctx *Context) Set(key string, val interface{})

Set var in context.

func (*Context) SetCookie

func (ctx *Context) SetCookie(name, value string)

SetCookie is used for jwt.

func (*Context) Status

func (ctx *Context) Status() int

Status Code.

func (*Context) Text

func (ctx *Context) Text(code int, body string) error

Text response text data.

func (*Context) UserAgent

func (ctx *Context) UserAgent() string

UserAgent returns http request UserAgent

func (*Context) Write

func (ctx *Context) Write(data []byte) (n int, err error)

Write Response.

type HandlerFunc

type HandlerFunc func(*Context) error

HandlerFunc context handler func

type SGo

type SGo struct {
	// Router is based on a radix/trie tree.
	Tree *Trie

	// Pool is for context.
	Pool *sync.Pool

	NotFoundHandler         HandlerFunc
	MethodNotAllowedHandler HandlerFunc

	// Built-in templates render.
	Templates *Templates

	Middlewares []HandlerFunc
}

SGo is Suuuuuuuuper Sweetie!

func New

func New() *SGo

New SGo App.

func (*SGo) Any

func (sg *SGo) Any(path string, handler HandlerFunc)

Any register any method handler

func (*SGo) CONNECT

func (sg *SGo) CONNECT(path string, handler HandlerFunc)

CONNECT register CONNECT request handler

func (*SGo) DELETE

func (sg *SGo) DELETE(path string, handler HandlerFunc)

DELETE register DELETE request handler

func (*SGo) GET

func (sg *SGo) GET(path string, handler HandlerFunc)

GET register GET request handler

func (*SGo) HEAD

func (sg *SGo) HEAD(path string, handler HandlerFunc)

HEAD register HEAD request handler

func (*SGo) Handle

func (sg *SGo) Handle(method, path string, handler HandlerFunc)

Handle register custom METHOD request HandlerFunc

func (*SGo) OPTIONS

func (sg *SGo) OPTIONS(path string, handler HandlerFunc)

OPTIONS register OPTIONS request handler

func (*SGo) PATCH

func (sg *SGo) PATCH(path string, handler HandlerFunc)

PATCH register PATCH request HandlerFunc

func (*SGo) POST

func (sg *SGo) POST(path string, handler HandlerFunc)

POST register POST request handler

func (*SGo) PUT

func (sg *SGo) PUT(path string, handler HandlerFunc)

PUT register PUT request handler

func (*SGo) Run

func (sg *SGo) Run(addr string) error

Run at the given addr

func (*SGo) RunOverTLS

func (sg *SGo) RunOverTLS(addr, certFile, keyFile string) error

RunOverTLS .

func (*SGo) ServeHTTP

func (sg *SGo) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*SGo) SetTemplates

func (sg *SGo) SetTemplates(tplDir string, funcMap template.FuncMap)

SetTemplates set the templates dir and funcMap.

func (*SGo) TRACE

func (sg *SGo) TRACE(path string, handler HandlerFunc)

TRACE register TRACE request handler

func (*SGo) USE

func (sg *SGo) USE(middlewares ...HandlerFunc)

USE middlewares for SGo

type Templates

type Templates struct {
	Dir    string
	Suffix string

	FuncMap template.FuncMap
	// contains filtered or unexported fields
}

Templates is a templates manager.

func NewTemplates

func NewTemplates(tplDir string, funcMap template.FuncMap) *Templates

NewTemplates .

func (*Templates) Render

func (tpl *Templates) Render(w io.Writer, tplname string, data interface{}) error

Render Templates.

type Trie

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

Trie node.

func (*Trie) Insert

func (t *Trie) Insert(method, path string, handler HandlerFunc)

Insert a node into the tree.

func (*Trie) Search

func (t *Trie) Search(components []string, params url.Values) *Trie

Search the tree.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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