gohttp

package module
v0.0.0-...-7e989b4 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2019 License: Apache-2.0 Imports: 26 Imported by: 6

README

gohttp

BuildStatus GoDoc GoWalker License


gohttp is used for RESTful APIs, Web apps, Http services in Golang. It is used similar with Tornado.

GO verion

GOVERSION >= 1.9.0

Getting started

Sample example
  • Simple Server Application: server
  • Simple Client Application: client
Complete Example
package main

import (
    "net/http"

    "github.com/luopengift/gohttp"
)

type baz struct {
    gohttp.BaseHTTPHandler
}

func (ctx *baz) GET() {
    ctx.Output("baz ok")
}

func main() {
    app := gohttp.Init()
    // register route "/foo"
    app.RouteFunc("/foo", func(resp http.ResponseWriter, req *http.Request) {
        resp.Write([]byte("foo ok"))
    })
    // register route "/bar"
    app.RouteFunCtx("/bar", func(ctx *gohttp.Context) {
        ctx.Output("bar ok")
    })
    // register route "/baz"
    app.Route("/baz", &baz{})
    app.Run(":8888")
}
Download and Install
go get github.com/luopengift/gohttp
Generate https tls cert/key file
go run  $GOROOT/src/crypto/tls/generate_cert.go --host localhost
Run
go run  $GOPATH/src/github.com/luopengift/gohttp/sample/server.go

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Author

@luopengift

License

gohttp source code is licensed under the Apache Licence 2.0.

Documentation

Overview

Package gohttp is sample http server framework This package is 1. used like std net/http app.Init()

app.RouteFunc("/foo", func(resp http.ResponseWriter, req http.Request) {
	   resp.Write([]byte("foo ok")
})

2. used gohttp.Context app.Init()

app.RouteFunCtx("/bar", func(ctx *gohttp.Context) {
    ctx.Output("bar ok")
})

3. used like tornado

type baz struct {
    gohttp.Context
}
func (ctx *baz) GET() {
 ctx.Output("baz ok")
}

app.Init() app.Route("/baz", &baz{})

Index

Constants

View Source
const (
	// VERSION version
	VERSION = "0.2.7.041819_beta"
)

Variables

View Source
var (
	// StartTrace 运行trace
	StartTrace = func(ctx *Context) {
		f, err := os.Create("trace.out")
		if err != nil {
			panic(err)
		}
		err = trace.Start(f)
		if err != nil {
			panic(err)
		}
	}

	// StopTrace 停止trace
	StopTrace = func(ctx *Context) {
		trace.Stop()
	}

	// StartGC 手动触发GC
	StartGC = func(ctx *Context) {
		runtime.GC()
	}

	// StopGC stop gc
	StopGC = func(ctx *Context) {
		debug.SetGCPercent(-1)
	}

	// Index wapper pprof.Index, default path is /debug/pprof/
	Index = pprof.Index

	// Cmdline wapper pprof.Cmdline, default path is /debug/pprof/cmdline
	Cmdline = pprof.Cmdline

	// Profile wapper pprof.Profile, default path is /debug/pprof/profile
	Profile = pprof.Profile

	// Symbol wapper pprof.Symbol, default path is /debug/pprof/symbol
	Symbol = pprof.Symbol

	// Trace wapper pprof.Trace, default path is /debug/pprof/trace
	Trace = pprof.Trace
)
View Source
var ErrMap = map[int]string{
	0:    "success",
	1000: "success",
	1001: "fail",
	1002: "",
}

ErrMap xx

Functions

func InitLog

func InitLog() *log.Log

InitLog inits gohttp loghandler

func RegistErrCode

func RegistErrCode(code int, msg string) error

RegistErrCode regist api error code and msg.

func WalkDir

func WalkDir(path string, matchs ...func(path string) bool) ([]string, error)

WalkDir walk dir path

Types

type APIHandler

type APIHandler struct {
	APIOutput
	BaseHTTPHandler
}

APIHandler designed for http api. It can used easily.

func (APIHandler) CloseNotify

func (resp APIHandler) CloseNotify() <-chan bool

Implements the http.CloseNotify interface

func (*APIHandler) Finish

func (ctx *APIHandler) Finish()

Finish finish

func (APIHandler) Finished

func (resp APIHandler) Finished() bool

func (APIHandler) Flush

func (resp APIHandler) Flush()

Implements the http.Flush interface

func (APIHandler) Header

func (resp APIHandler) Header() http.Header

rewrite http.ResponseWriter interface method

func (APIHandler) Hijack

func (resp APIHandler) Hijack() (net.Conn, *bufio.ReadWriter, error)

Implements the http.Hijacker interface

func (APIHandler) Size

func (resp APIHandler) Size() int

func (APIHandler) Status

func (resp APIHandler) Status() int

func (APIHandler) Write

func (resp APIHandler) Write(b []byte) (int, error)

rewrite http.ResponseWriter interface method

func (APIHandler) WriteHeader

func (resp APIHandler) WriteHeader(code int)

rewrite http.ResponseWriter interface method

type APIOutput

type APIOutput struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Err  error       `json:"err"`
	Data interface{} `json:"data"`
}

APIOutput is sturct data need responsed.

func (*APIOutput) Detail

func (api *APIOutput) Detail() string

Detail detail

func (APIOutput) MarshalJSON

func (api APIOutput) MarshalJSON() ([]byte, error)

MarshalJSON rewrite format to json, implement json.Marshaler interface.

func (*APIOutput) Set

func (api *APIOutput) Set(code int, msg string, errs ...error)

Set set msg

func (*APIOutput) String

func (api *APIOutput) String() string

type Application

type Application struct {
	*Config
	Log Logger
	*Template
	*RouterList
	*http.Server
	sync.Pool
}

Application is a httpserver instance.

func Init

func Init() *Application

Init creates a default httpserver instance by default config.

func (*Application) Run

func (app *Application) Run(addr ...string)

Run starts the server by listen address. HTTP/2.0 is only supported in https, If server is http mode, then HTTP/1.x will be used.

func (*Application) RunTLS

func (app *Application) RunTLS(addr ...string)

RunTLS xxx

func (*Application) ServeHTTP

func (app *Application) ServeHTTP(responsewriter http.ResponseWriter, request *http.Request)

ServeHTTP is HTTP server implement method. It makes App compatible to native http handler.

func (*Application) Stop

func (app *Application) Stop() error

Stop gracefully shuts down the server without interrupting any active connections.

type BaseHTTPHandler

type BaseHTTPHandler struct {
	*Context
}

BaseHTTPHandler http handler

func (BaseHTTPHandler) CloseNotify

func (resp BaseHTTPHandler) CloseNotify() <-chan bool

Implements the http.CloseNotify interface

func (*BaseHTTPHandler) Finish

func (ctx *BaseHTTPHandler) Finish()

Finish func

func (BaseHTTPHandler) Finished

func (resp BaseHTTPHandler) Finished() bool

func (BaseHTTPHandler) Flush

func (resp BaseHTTPHandler) Flush()

Implements the http.Flush interface

func (*BaseHTTPHandler) HEAD

func (ctx *BaseHTTPHandler) HEAD()

HEAD method

func (BaseHTTPHandler) Header

func (resp BaseHTTPHandler) Header() http.Header

rewrite http.ResponseWriter interface method

func (BaseHTTPHandler) Hijack

func (resp BaseHTTPHandler) Hijack() (net.Conn, *bufio.ReadWriter, error)

Implements the http.Hijacker interface

func (*BaseHTTPHandler) Initialize

func (ctx *BaseHTTPHandler) Initialize()

Initialize init

func (*BaseHTTPHandler) Prepare

func (ctx *BaseHTTPHandler) Prepare()

Prepare xx

func (*BaseHTTPHandler) SetCookie

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

SetCookie set cookie for response

func (BaseHTTPHandler) Size

func (resp BaseHTTPHandler) Size() int

func (BaseHTTPHandler) Status

func (resp BaseHTTPHandler) Status() int

func (BaseHTTPHandler) Write

func (resp BaseHTTPHandler) Write(b []byte) (int, error)

rewrite http.ResponseWriter interface method

func (BaseHTTPHandler) WriteHeader

func (resp BaseHTTPHandler) WriteHeader(code int)

rewrite http.ResponseWriter interface method

type Config

type Config struct {
	Debug             bool     `json:"debug" yaml:"debug"`
	Addr              string   `json:"addr" yaml:"addr"`
	ReadTimeout       int      `json:"readtimeout" yaml:"readtimeout"`
	ReadHeaderTimeout int      `json:"readheadertime" yaml:"readheadertime"`
	WriteTimeout      int      `json:"writetime" yaml:"writetime"`
	MaxHeaderBytes    int      `json:"maxheaderbytes" yaml:"maxheaderbytes"`
	CertFile          string   `json:"cert" yaml:"cert"`
	KeyFile           string   `json:"key" yaml:"key"`
	WebPath           string   `json:"web_path" yaml:"web_path"`
	StaticPath        []string `json:"static_path" yaml:"static_path"`
	LogFormat         string   `json:"log_format" yaml:"log_format"`
}

Config config

func InitConfig

func InitConfig() *Config

InitConfig init config

func (*Config) SetAddress

func (cfg *Config) SetAddress(addr string)

SetAddress set address

func (*Config) SetDebug

func (cfg *Config) SetDebug(debug bool)

SetDebug set debug model

func (*Config) SetLogFormat

func (cfg *Config) SetLogFormat(format string)

SetLogFormat set log format

func (*Config) SetMaxHeaderBytes

func (cfg *Config) SetMaxHeaderBytes(max int)

SetMaxHeaderBytes set max header bytes

func (*Config) SetStaticPath

func (cfg *Config) SetStaticPath(static ...string)

SetStaticPath set static path

func (*Config) SetTLS

func (cfg *Config) SetTLS(cert, key string)

SetTLS set tls

func (*Config) SetTimeout

func (cfg *Config) SetTimeout(timeout int)

SetTimeout set time out

func (*Config) SetWebPath

func (cfg *Config) SetWebPath(web string)

SetWebPath set web path

type Context

type Context struct {
	*http.Request

	*Application
	// contains filtered or unexported fields
}

Context gohttp context

func (Context) CloseNotify

func (resp Context) CloseNotify() <-chan bool

Implements the http.CloseNotify interface

func (*Context) Download

func (ctx *Context) Download(file string)

Download file download response by file path.

func (Context) Finished

func (resp Context) Finished() bool

func (Context) Flush

func (resp Context) Flush()

Implements the http.Flush interface

func (*Context) GetBody

func (ctx *Context) GetBody(name string) interface{}

GetBody fetch body argument named by <name>

func (*Context) GetBodyArgs

func (ctx *Context) GetBodyArgs() []byte

GetBodyArgs fetch body arguments

func (*Context) GetCookie

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

GetCookie get cookie

func (*Context) GetCookies

func (ctx *Context) GetCookies() []*http.Cookie

GetCookies get cookies

func (*Context) GetForm

func (ctx *Context) GetForm() (map[string]string, map[string]*multipart.FileHeader, error)

GetForm formdata, Content-Type must be multipart/form-data. TODO: RemoveAll removes any temporary files associated with a Form.

func (*Context) GetMatch

func (ctx *Context) GetMatch(name string, null string) string

GetMatch fetch match argument named by <name>, null is default value defined by user

func (*Context) GetMatchArgs

func (ctx *Context) GetMatchArgs() map[string]string

GetMatchArgs get match args

func (*Context) GetQuery

func (ctx *Context) GetQuery(name string, null string) string

GetQuery fetch query argument named by <name>, null is default value defined by user

func (*Context) GetQueryArgs

func (ctx *Context) GetQueryArgs() map[string][]string

GetQueryArgs get query args

func (*Context) HTML

func (ctx *Context) HTML(v interface{}, code ...int)

HTML response html data

func (*Context) HTTPError

func (ctx *Context) HTTPError(msg string, code int)

HTTPError response Http Error

func (Context) Header

func (resp Context) Header() http.Header

rewrite http.ResponseWriter interface method

func (Context) Hijack

func (resp Context) Hijack() (net.Conn, *bufio.ReadWriter, error)

Implements the http.Hijacker interface

func (*Context) JSON

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

JSON response json data

func (*Context) Output

func (ctx *Context) Output(v interface{}, code ...int)

Output xx

func (*Context) RecvFile

func (ctx *Context) RecvFile(name string, path string) (string, error)

RecvFile recv file

func (*Context) Redirect

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

Redirect response redirect

func (*Context) RemoteAddr

func (ctx *Context) RemoteAddr() string

RemoteAddr remote addr for request, copied from net/url.stripPort

func (*Context) Render

func (ctx *Context) Render(tpl string, data interface{})

Render render template no cache

func (*Context) SaveFile

func (ctx *Context) SaveFile(fh *multipart.FileHeader, path string, name ...string) (string, error)

SaveFile save file to disk

func (Context) Size

func (resp Context) Size() int

func (Context) Status

func (resp Context) Status() int

func (Context) Write

func (resp Context) Write(b []byte) (int, error)

rewrite http.ResponseWriter interface method

func (Context) WriteHeader

func (resp Context) WriteHeader(code int)

rewrite http.ResponseWriter interface method

func (*Context) XML

func (ctx *Context) XML(v interface{}, code ...int)

XML response xml data

type Entry

type Entry struct {
	reflect.Type
}

Entry handle implements HandleHTTP interface

func (Entry) Exec

func (entry Entry) Exec(ctx *Context)

Exec implements HandleHTTP interface

type HandleFunCtx

type HandleFunCtx func(*Context)

HandleFunCtx handle fun ctx

func (HandleFunCtx) Exec

func (f HandleFunCtx) Exec(ctx *Context)

Exec implements HandleHTTP interface

type HandleFunc

type HandleFunc func(http.ResponseWriter, *http.Request)

HandleFunc handle func

func (HandleFunc) Exec

func (f HandleFunc) Exec(ctx *Context)

Exec implements HandleHTTP interface

type HandleHTTP

type HandleHTTP interface {
	Exec(*Context)
}

HandleHTTP handle http interface

type Handler

type Handler interface {
	// Handler implements ServeHTTP(http.ResponseWriter, *http.Request) func.
	http.Handler
	// Prepare invoked before Init.
	Prepare()
	// Initialize invoked before httpMethod func.
	Initialize()
	// Finish invoked after httpMethod func.
	Finish()
	WriteHeader(code int)
	// contains filtered or unexported methods
}

Handler implements http handler interface. Initialize -> Prepare -> GET/POST... -> Finish

type InfoHandler

type InfoHandler struct {
	BaseHTTPHandler
}

InfoHandler info handler

func (InfoHandler) CloseNotify

func (resp InfoHandler) CloseNotify() <-chan bool

Implements the http.CloseNotify interface

func (InfoHandler) Finished

func (resp InfoHandler) Finished() bool

func (InfoHandler) Flush

func (resp InfoHandler) Flush()

Implements the http.Flush interface

func (*InfoHandler) GET

func (ctx *InfoHandler) GET()

GET method

func (InfoHandler) Header

func (resp InfoHandler) Header() http.Header

rewrite http.ResponseWriter interface method

func (InfoHandler) Hijack

func (resp InfoHandler) Hijack() (net.Conn, *bufio.ReadWriter, error)

Implements the http.Hijacker interface

func (InfoHandler) Size

func (resp InfoHandler) Size() int

func (InfoHandler) Status

func (resp InfoHandler) Status() int

func (InfoHandler) Write

func (resp InfoHandler) Write(b []byte) (int, error)

rewrite http.ResponseWriter interface method

func (InfoHandler) WriteHeader

func (resp InfoHandler) WriteHeader(code int)

rewrite http.ResponseWriter interface method

type Logger

type Logger interface {
	Debugf(string, ...interface{})
	Infof(string, ...interface{})
	Warnf(string, ...interface{})
	Errorf(string, ...interface{})
	Fatalf(string, ...interface{})
}

Logger interface

type ResponseWriter

type ResponseWriter interface {
	// ResponseWriter have three method:
	// Header() Header <1>
	// Write([]byte) (int, error) <2>
	// WriteHeader(int) <3>
	http.ResponseWriter

	http.Flusher
	http.Hijacker
	// Status returns the status code of the response or 0 if the response has not been written.
	Status() int
	// Finished returns whether or not the ResponseWriter has been finished.
	Finished() bool
	// Size returns the size of the response body.
	Size() int
}

ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response. It is recommended that middleware handlers use this construct to wrap a responsewriter if the functionality calls for it.

type RouteHandler

type RouteHandler struct {
	BaseHTTPHandler
}

RouteHandler routehandler

func (RouteHandler) CloseNotify

func (resp RouteHandler) CloseNotify() <-chan bool

Implements the http.CloseNotify interface

func (RouteHandler) Finished

func (resp RouteHandler) Finished() bool

func (RouteHandler) Flush

func (resp RouteHandler) Flush()

Implements the http.Flush interface

func (*RouteHandler) GET

func (ctx *RouteHandler) GET()

GET method

func (RouteHandler) Header

func (resp RouteHandler) Header() http.Header

rewrite http.ResponseWriter interface method

func (RouteHandler) Hijack

func (resp RouteHandler) Hijack() (net.Conn, *bufio.ReadWriter, error)

Implements the http.Hijacker interface

func (RouteHandler) Size

func (resp RouteHandler) Size() int

func (RouteHandler) Status

func (resp RouteHandler) Status() int

func (RouteHandler) Write

func (resp RouteHandler) Write(b []byte) (int, error)

rewrite http.ResponseWriter interface method

func (RouteHandler) WriteHeader

func (resp RouteHandler) WriteHeader(code int)

rewrite http.ResponseWriter interface method

type RouterList

type RouterList []*route

RouterList router List

func InitRouterList

func InitRouterList() *RouterList

InitRouterList init route list

func (*RouterList) Remove

func (r *RouterList) Remove(path string)

Remove remove route

func (*RouterList) Route

func (r *RouterList) Route(path string, handler Handler)

Route route

func (*RouterList) RouteCtxMethod

func (r *RouterList) RouteCtxMethod(method, path string, f HandleFunCtx)

RouteCtxMethod route by method

func (*RouterList) RouteFunCtx

func (r *RouterList) RouteFunCtx(path string, f HandleFunCtx)

RouteFunCtx route handle func

func (*RouterList) RouteFunc

func (r *RouterList) RouteFunc(path string, f HandleFunc)

RouteFunc route handle func

func (*RouterList) RouteMethod

func (r *RouterList) RouteMethod(method, path string, f HandleFunc)

RouteMethod route by method

func (*RouterList) RouteStdHandler

func (r *RouterList) RouteStdHandler(path string, h http.Handler)

RouteStdHandler route wapper by net/http.Handler

func (*RouterList) String

func (r *RouterList) String() string

type Template

type Template map[string]*template.Template

Template template

func InitTemplate

func InitTemplate(webpath string) (*Template, error)

InitTemplate init template

func (*Template) Add

func (t *Template) Add(name, tpl string)

Add string to template

func (*Template) AddFile

func (t *Template) AddFile(tpl string)

AddFile to template

func (*Template) Lookup

func (t *Template) Lookup(path string) error

Lookup walk around path

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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