slimgo

package module
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2019 License: GPL-3.0 Imports: 24 Imported by: 0

README

SlimGo Web Framework

slimgo logo

又一个 go web 框架,wheel。

起步

安装
go get github.com/gitwillsky/slimgo
使用
package main

import (
	"fmt"
	"net/http"

	"github.com/gitwillsky/slimgo"
)

func main() {
	s := slimgo.New()

	// 全局过滤器 global filter
	// 全局过滤器在route之前执行
    s.AddServerFilter(func(ctx *server.Context) (interface{}, error) {
        now := time.Now()
		r, e := ctx.Next()

		// 这里可以定义router handler的结果处理,比如自定义json解析逻辑, 模板渲染逻辑,自定义错误处理等

		// ctx.getRegURLPath() 方法获得注册路由时的URL原始字符串,global filter 由系统定义为 "/*"
        log.Debugf("Handler %s in %f seconds", ctx.GetRegURLPath(), time.Since(now).Seconds())
        return r, e
    })

	// 注册单个handler
	s.GET("/hello", func(ctx *server.Context) (interface{}, error) {
		return "hello world", nil
	})

	//  根(组)路由支持
	s.Root("/system", func(ctx *server.Context) (interface{}, error){
		log.Infof("进入根路由")
		// 这里适合进行路由权限校验等逻辑
		// 这里如果返回结果或者错误,那么下面的handler将不会执行
		return nil, nil
	}).
		GET("/files/*filepath", system.StaticFileHandler).

		POST("/token", system.TokenHandler).

		// 也可以单独为后面的handler做其他的权限校验
		// 这里如果不调用ClearFilters() 那么根上定义的filter也将应用到后面的handler
		ClearFilters().
		AddFilter(filter.AuthFilter).

		POST("/files", system.UploadFileHandler).

		GET("/my", system.GetMyInfoHandler).

		PATCH("/my", system.PatchMyInfoHandler).

		PUT("/mypass", system.UpdatePasswordHandler)

    // 启动web服务
    if err = s.Start(":8080"); err != nil {
        log.Errorf("start web server failed, %s", err.Error())
    }
}

参考

  1. beego (github.com/astaxie/beego)
  2. http-router(github.com/julienschmidt/httprouter)

联系

Author Email: hdu_willsky@foxmail.com

Documentation

Overview

Copyright 2013 Julien Schmidt. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

Index

Constants

View Source
const Version = "slimgo v1.0.0"

Variables

This section is empty.

Functions

func Alert

func Alert(a ...interface{})

func Alertf

func Alertf(format string, a ...interface{})

func BytesToString

func BytesToString(b *[]byte) string

func CleanURLPath

func CleanURLPath(urlPath string) string

func Close

func Close()

func Debug

func Debug(a ...interface{})

func Debugf

func Debugf(format string, a ...interface{})

func Error

func Error(a ...interface{})

func Errorf

func Errorf(format string, a ...interface{})

func FileSize

func FileSize(s int64) string

FileSize calculates the file size and generate user-friendly string.

func GetFuncInfo

func GetFuncInfo(i interface{}) (funcName, file string, line int)

GetFuncInfo 通过反射获取方法信息

func Info

func Info(a ...interface{})

func Infof

func Infof(format string, a ...interface{})

func NewGroupLogger

func NewGroupLogger(level LogLevel) *groupLogger

func OpenORCreateFile

func OpenORCreateFile(fullname string) (*os.File, error)

open or create log file.

func Register

func Register(name string, impl ILogger)

Register log interface implementator

func SetLevel

func SetLevel(level LogLevel)

func SetOutput

func SetOutput(loggers map[string]string)

func StringToBytes

func StringToBytes(s *string) []byte

func Warning

func Warning(a ...interface{})

func Warningf

func Warningf(format string, a ...interface{})

Types

type Context

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

Context server context

func (*Context) AddHandlers

func (c *Context) AddHandlers(handlers ...Handler)

func (*Context) GetAllHandlers

func (c *Context) GetAllHandlers() []Handler

func (*Context) GetClientIP

func (c *Context) GetClientIP() string

GetClientIP return client IP. if in proxy, return first proxy id; if error ,return 127.0.0.1;

func (*Context) GetCookie

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

Get cookie

func (*Context) GetParam

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

GetParam get router :paramname param value

func (*Context) GetRegURLPath

func (c *Context) GetRegURLPath() string

func (*Context) GetResponseHeader

func (c *Context) GetResponseHeader() http.Header

func (*Context) GetResponseWriter

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

func (*Context) GetSecureCookie

func (c *Context) GetSecureCookie(secret, key string) string

Get secure cookie.

func (*Context) GetValue

func (c *Context) GetValue(key string) (value interface{}, ok bool)

GetValue get data value

func (*Context) NewError

func (c *Context) NewError(statusCode int, errs ...error) error

func (*Context) Next

func (c *Context) Next() (interface{}, error)

func (*Context) ParseJSONRequest

func (c *Context) ParseJSONRequest(target interface{}) error

ParseJSONRequest parse json request

func (*Context) PutValue

func (c *Context) PutValue(key string, value interface{})

func (*Context) SetCookie

func (c *Context) SetCookie(key string, value string, cookiePath string, maxAge int) error

Set cookie.

func (*Context) SetSecureCookie

func (c *Context) SetSecureCookie(secret, cookieName, cookieValue,
	cookiePath string, cookieMaxDay int) error

Set secure cookie.

func (*Context) UploadFiles

func (c *Context) UploadFiles(folder string, maxLen int, allowExt string) ([]string, error)

文件上传 floder 文件所要保存的目录 maxLen 文件最大长度 允许的扩展名[正则表达式],例如:(.png|.jpeg|.jpg|.gif)

func (*Context) WriteHeader

func (c *Context) WriteHeader(code int)

type Handler

type Handler func(context *Context) (interface{}, error)

type ILogger

type ILogger interface {
	Init(config string) error
	Message(message string, level LogLevel) error
	Flush()
	Close()
}

Logger interface

type LogLevel

type LogLevel uint8
const (
	LevelEmergency LogLevel = iota
	LevelAlert
	LevelCritical
	LevelError
	LevelWarning
	LevelNotice
	LevelInformational
	LevelDebug
)

RFC5424 log message levels.

func GetLevel

func GetLevel() LogLevel

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	Written() bool
}

func NewResponseWriter

func NewResponseWriter(res http.ResponseWriter) ResponseWriter

NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter

type Router

type Router struct {

	// Enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the
	// client is redirected to /foo with http status code 301 for GET requests
	// and 307 for all other request methods.
	RedirectTrailingSlash bool

	// If enabled, the router tries to fix the current request path, if no
	// handle is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handle can be found for this route, the router makes a redirection
	// to the corrected path with status code 301 for GET requests and 307 for
	// all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool
	// contains filtered or unexported fields
}

Router server router

func (*Router) Register

func (r *Router) Register(method, urlPath string, handlers ...Handler)

Register registers a new request handle with the given path and method.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

type Server

type Server struct {

	// NotFound Configurable http.Handler which is called when no matching route is
	// found. If it is not set, http.NotFound is used.
	NotFound Handler
	// MethodNotAllowed Configurable http.Handler which is called when a request
	// cannot be routed and HandleMethodNotAllowed is true.
	// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
	// The "Allow" header with allowed request methods is set before the handler
	// is called.
	MethodNotAllowed Handler
	// contains filtered or unexported fields
}

Server http server handler

func New

func New() *Server

New create new server handler so we can use http.ListenAndServe()

func (*Server) AddServerFilter

func (s *Server) AddServerFilter(filters ...Handler)

AddFilter 注册全局过滤器

func (*Server) DELETE

func (s *Server) DELETE(urlPath string, handler Handler)

DELETE is a shortcut for router.Register("DELETE", path, handler)

func (*Server) GET

func (s *Server) GET(urlPath string, handler Handler)

GET is a shortcut for router.Register("GET", path, handler)

func (*Server) HEAD

func (s *Server) HEAD(urlPath string, handler Handler)

HEAD is a shortcut for router.Register("HEAD", path, handler)

func (*Server) OPTIONS

func (s *Server) OPTIONS(urlPath string, handler Handler)

OPTIONS is a shortcut for router.Register("OPTIONS", path, handler)

func (*Server) PATCH

func (s *Server) PATCH(urlPath string, handler Handler)

PATCH is a shortcut for router.Register("PATCH", path, handler)

func (*Server) POST

func (s *Server) POST(urlPath string, handler Handler)

POST is a shortcut for router.Register("POST", path, handler)

func (*Server) PUT

func (s *Server) PUT(urlPath string, handler Handler)

PUT is a shortcut for router.Register("PUT", path, handler)

func (*Server) Root

func (s *Server) Root(rootPath string, handlers ...Handler) *groupRoutes

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)

implement ServeHTTP

func (*Server) Start

func (s *Server) Start(addr string) error

func (*Server) StartTLS

func (s *Server) StartTLS(addr, certFile, keyFile string) error

Jump to

Keyboard shortcuts

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