sgo

package module
v1.2.0 Latest Latest
Warning

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

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

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")
    })
    app.Run(":16311")
}

Further

For vue2 projects, add module.exports = {assetsDir: 'static', css: { extract: false }} to vue.config.js, then npm run build && tar caf dist.tar.xz dist and copy dist.tar.xz and run ./deployFrontend.sh.

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/AmyangXYZ/sgo"
	"github.com/gorilla/websocket"
)

const (
	addr = ":8888"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func main() {
	app := sgo.New()
	app.SetTemplates("./templates", nil)
	app.GET("/", index)
	app.GET("/static/*files", static)

	app.GET("/api/boottime", getBootTime)
	app.GET("/ws/comm", wsComm)
	app.POST("/api/link/:name", postHandler)
	app.OPTIONS("/api/link/:name", sgo.PreflightHandler)

	if err := app.Run(addr); err != nil {
		log.Fatal("Listen error", err)
	}
}

// Index page handler.
func index(ctx *sgo.Context) error {
	return ctx.Render(200, "index")
}

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

func getBootTime(ctx *sgo.Context) error {
	return ctx.Text(200, fmt.Sprintf("%d", 20))
}

func wsComm(ctx *sgo.Context) error {
	ws, err := upgrader.Upgrade(ctx.Resp, ctx.Req, nil)
	breakSig := make(chan bool)
	if err != nil {
		return err
	}
	fmt.Println("ws/comm connected")
	defer func() {
		ws.Close()
		fmt.Println("ws/comm client closed")
	}()
	go func() {
		for {
			_, _, err := ws.ReadMessage()
			if err != nil {
				breakSig <- true
			}
		}
	}()
	for {
		select {
		// case l := <-LogsComm:
		// 	ws.WriteJSON(l)
		case <-breakSig:
			return errors.New("stop ws")
		}
	}
}

func postHandler(ctx *sgo.Context) error {
	// param request
	fmt.Println(ctx.Params)
	// json body request
	body, err := ioutil.ReadAll(ctx.Req.Body)
	if err != nil {
		return err
	}
	fmt.Println(string(body))
	var data map[string]interface{}
	json.Unmarshal(body, &data)

	return ctx.Text(200, "xx")
}

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

View Source
var PreflightHandler = func(ctx *Context) error { return ctx.Text(200, "") }

PreflightHandler is a dummy handler that handles preflight request when CORS

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