fmx

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2022 License: MIT, MIT Imports: 24 Imported by: 1

README

fmx is a golang http router. mainly for rest api service development. it's much like gin framework, but fmx has better compatibility with http.Handler.

features:

  1. can serve static files, json string, plain string.
  2. middleware-style http handlers . easy to scale.
  3. detailed http log, easy to debug.
  4. support per-request level custome KV data, which can pass through middlers.

pull the codes. and check examples for detail. have fun !

more examples see https://github.com/carr123/fmx_demo


package main

import (
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/carr123/fmx"
)

func main() {
	router := fmx.NewServeMux()
	router.Use() //fmx.SimpleLogger()

	router.GET("/api/profile", fmx.FullLogger(), GetProfile) //get json response
	router.GET("/api/export", ExportFile)                    //export file (web browser will download this file)
	router.POST("/api/profile", PostProfile)                 //client post json data to server
	router.POST("/api/avatar", PostImage)                    //post image to server through form data

	router.ServeDir("/", filepath.Join(getAppDir(), "www")) //server your static web pages

	fmt.Println("server start ...")
	fmt.Println("open your browser and navigate to: http://127.0.0.1:8080")
	err := http.ListenAndServe("127.0.0.1:8080", fmx.PanicHandler(router, func(s string) {
		fmt.Println("panic:", s)
	}))
	if err != nil {
		fmt.Println(err)
	}
}

func getAppDir() string {
	file, _ := exec.LookPath(os.Args[0])
	apppath, _ := filepath.Abs(file)
	dir := filepath.Dir(apppath)
	return dir
}



Documentation

Index

Constants

View Source
const (
	AbortIndex = math.MaxInt16 / 2
)
View Source
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

TimeFormat is the time format to use when generating times in HTTP headers. It is like time.RFC1123 but hard-codes GMT as the time zone. The time being formatted must be in UTC for Format to generate the correct format.

For parsing this time format, see ParseTime.

View Source
const (
	Version string = "1.0.3"
)

Variables

This section is empty.

Functions

func DetectContentType

func DetectContentType(data []byte) string

DetectContentType implements the algorithm described at http://mimesniff.spec.whatwg.org/ to determine the Content-Type of the given data. It considers at most the first 512 bytes of data. DetectContentType always returns a valid MIME type: if it cannot determine a more specific one, it returns "application/octet-stream".

func ErrCode

func ErrCode(err error, def ...int) int

func ErrorReply

func ErrorReply(w http.ResponseWriter, error string, code int)

Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.

func FileServer2

func FileServer2(root http.FileSystem) http.Handler

func GetAppPath

func GetAppPath() string

func PanicHandler

func PanicHandler(forward http.Handler, logwriter func(string)) http.HandlerFunc

func ParseTime

func ParseTime(text string) (t time.Time, err error)

ParseTime parses a time header (such as the Date: header), trying each of the three formats allowed by HTTP/1.1: TimeFormat, time.RFC850, and time.ANSIC.

func RecoverFn

func RecoverFn(logwriter func(string)) func()

func ServeFile2

func ServeFile2(w http.ResponseWriter, r *http.Request, name string)

//////////////////////// ServeFile replies to the request with the contents of the named file or directory.

If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling ServeFile. As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element.

As a special case, ServeFile redirects any request where r.URL.Path ends in "/index.html" to the same path, without the final "index.html". To avoid such redirects either modify the path or use ServeContent.

Types

type Context

type Context struct {
	Writer   IWriter
	Request  *http.Request
	Keys     map[string]interface{}
	HasError bool
	// contains filtered or unexported fields
}

func (*Context) Abort

func (c *Context) Abort()

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int)

func (*Context) AddError

func (c *Context) AddError(err error)

func (*Context) AddLog

func (c *Context) AddLog(info ...string)

func (*Context) ClientIP

func (c *Context) ClientIP() string

func (*Context) Data

func (c *Context) Data(code int, contentType string, data []byte)

Data writes some data into the body stream and updates the HTTP code.

func (*Context) File

func (c *Context) File(filepath string)

func (*Context) Get

func (c *Context) Get(key string) (value interface{}, exists bool)

Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)

func (*Context) GetErrors

func (c *Context) GetErrors() []error

func (*Context) GetLogs

func (c *Context) GetLogs() []string

func (*Context) JSON

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

code: http response code, eg. 200, 404, ... this function marshal v to json string, and send it to client as http response body.

func (*Context) MustGet

func (c *Context) MustGet(key string) interface{}

MustGet returns the value for the given key if it exists, otherwise it panics.

func (*Context) Next

func (c *Context) Next()

func (*Context) Param

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

Param get param from route

func (*Context) Query

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

func (*Context) QueryByte

func (c *Context) QueryByte(key string, def byte) byte

func (*Context) QueryFloat64

func (c *Context) QueryFloat64(key string, def float64) float64

func (*Context) QueryInt

func (c *Context) QueryInt(key string, def int) int

func (*Context) QueryInt64

func (c *Context) QueryInt64(key string, def int64) int64

func (*Context) QueryString

func (c *Context) QueryString(key, def string) string

func (*Context) QueryUint

func (c *Context) QueryUint(key string, def uint) uint

func (*Context) ReadBody

func (c *Context) ReadBody() []byte

func (*Context) ReadReqBodyJson

func (c *Context) ReadReqBodyJson(v interface{}) error

func (*Context) Redirect

func (c *Context) Redirect(code int, Location string)

func (*Context) Set

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

Set is used to store a new key/value pair exclusivelly for this context. It also lazy initializes c.Keys if it was not used previously.

func (*Context) String

func (c *Context) String(code int, format string, values ...interface{})

type Engine

type Engine struct {
	*Router
	// contains filtered or unexported fields
}

func NewServeMux

func NewServeMux() *Engine

type ErrorWithPos

type ErrorWithPos interface {
	error
	Where() []string
	String() string
}

func Error

func Error(err error, code ...int) ErrorWithPos

func ErrorAppend

func ErrorAppend(err error, szExtra ...string) ErrorWithPos

append text description to err, return a new err

func Errorf

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

type H

type H = map[string]interface{}

type HandlerFunc

type HandlerFunc func(*Context)

func Logger

func Logger(bShowReqBody bool, bShowRespBody bool) HandlerFunc

func LoggerWithFunc

func LoggerWithFunc(bShowReqBody bool, bShowRespBody bool, fn LoggerFunc) HandlerFunc

type IWriter

type IWriter interface {
	http.ResponseWriter
	http.Hijacker
	GetStatusCode() int
	Init(w http.ResponseWriter)
	SetRecordRespBody(bool)
	GetRespBody() io.Reader
}

func NewWriter

func NewWriter(w http.ResponseWriter) IWriter

type LoggerFunc

type LoggerFunc func(c *Context, szLog []byte)

func DefaultLoggerFunc

func DefaultLoggerFunc() LoggerFunc

type Router

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

Router http router

func (*Router) Any

func (r *Router) Any(path string, handlers ...HandlerFunc)

Any registers a route that matches all the HTTP methods. GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE

func (*Router) CONNECT

func (r *Router) CONNECT(path string, handlers ...HandlerFunc)

CONNECT handle CONNECT method

func (*Router) DELETE

func (r *Router) DELETE(path string, handlers ...HandlerFunc)

DELETE handle DELETE method

func (*Router) GET

func (r *Router) GET(path string, handlers ...HandlerFunc)

GET handle GET method

func (*Router) Group

func (r *Router) Group(handlers ...HandlerFunc) *Router

Group group route

func (*Router) HEAD

func (r *Router) HEAD(path string, handlers ...HandlerFunc)

HEAD handle HEAD method

func (*Router) Handle

func (r *Router) Handle(method, path string, handlers []HandlerFunc)

Handle handle with specific method

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handlers ...HandlerFunc)

OPTIONS handle OPTIONS method

func (*Router) PATCH

func (r *Router) PATCH(path string, handlers ...HandlerFunc)

PATCH handle PATCH method

func (*Router) POST

func (r *Router) POST(path string, handlers ...HandlerFunc)

POST handle POST method

func (*Router) PUT

func (r *Router) PUT(path string, handlers ...HandlerFunc)

PUT handle PUT method

func (*Router) ServeDir

func (r *Router) ServeDir(prefix string, dir string)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

Conforms to the http.Handler interface.

func (*Router) TRACE

func (r *Router) TRACE(path string, handlers ...HandlerFunc)

TRACE handle TRACE method

func (*Router) Use

func (r *Router) Use(middlewares ...HandlerFunc) *Router

Use register middleware these middlewares are combined and added to Router

func (*Router) UseNotFound

func (r *Router) UseNotFound(fn HandlerFunc)

use fn to handle http 404

type WriterImpl

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

func (*WriterImpl) GetRespBody

func (this *WriterImpl) GetRespBody() io.Reader

func (*WriterImpl) GetStatusCode

func (this *WriterImpl) GetStatusCode() int

func (*WriterImpl) Header

func (this *WriterImpl) Header() http.Header

func (*WriterImpl) Hijack

func (this *WriterImpl) Hijack() (net.Conn, *bufio.ReadWriter, error)

func (*WriterImpl) Init

func (this *WriterImpl) Init(w http.ResponseWriter)

func (*WriterImpl) SetRecordRespBody

func (this *WriterImpl) SetRecordRespBody(bRecordBody bool)

func (*WriterImpl) Write

func (this *WriterImpl) Write(p []byte) (int, error)

func (*WriterImpl) WriteHeader

func (this *WriterImpl) WriteHeader(status int)

Jump to

Keyboard shortcuts

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