hst

package module
v0.0.0-...-ed5e65e Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2022 License: MIT Imports: 35 Imported by: 2

README

hst

Codacy Badge

Http/httpS/Tls web服务库

功能

  • HTTP 普通web服务
  • HTTPS 单向认证web服务
  • TLS 双向认证web服务
  • HTTP认证
  • 自签证书生成
  • 支持中间件
  • 支持Session
  • 支持Render渲染模版
  • Static支持gzip输出

安装

go get -v github.com/ohko/hst

使用

http

h := New(nil)
h.HandleFunc("/", func(ctx *Context) {
    fmt.Fprint(ctx.W, "Hello world!")
})
h.ListenHTTP(":8080")

https

h := New(nil)
h.HandleFunc("/", func(ctx *Context) {
    fmt.Fprint(ctx.W, "Hello world!")
})
go h.ListenHTTPS(":8081", "ssl.crt", "ssl.key")
log.Println("wait ctrl+c ...")
Shutdown(time.Second*5, h)

tls

h := NewTLSServer(nil)
h.HandleFunc("/", func(ctx *Context) {
    fmt.Fprint(ctx.W, "Hello world!")
})
go h.ListenTLS(":8081", "ca.crt", "ssl.crt", "ssl.key")

http认证

h.HandleFunc("/", BasicAuth("账户", "密码"), func(ctx *Context) {
    fmt.Fprint(ctx.W, "Success")
})

制作自签证书

if !MakeTLSFile("ca证书密码", "https证书密码", "pfx安装证书密码", "证书生成路径", "域名", "邮件地址") {
    t.Fatal("make tls error!")
}

TODO

  • 路径参数
  • 表单验证
  • 上传文件,分片上传
  • JSONP
  • 静态文件打包
  • http2 push
  • 多服务器
  • 自定义HTTP配置

更多

更多例子查看 hst_test.go

Documentation

Overview

Example (Main)
s := New(nil)
s.ListenHTTP(":8080")
Output:

Index

Examples

Constants

View Source
const (
	// http://www.useragentstring.com
	UserAgentSafari  = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36`
	UserAgentFirefox = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0`
	UserAgentEdge    = `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36`
	UserAgentIE11    = `Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko`
)

Variables

This section is empty.

Functions

func GetLocalIP

func GetLocalIP() (string, error)

GetLocalIP 获取局域网IP地址

func GetRealIP

func GetRealIP(ctx *Context) string

GetRealIP 获取客户的真实IP

func MakeGUID

func MakeGUID() string

MakeGUID 生成唯一的GUID

func MakeTLSFile

func MakeTLSFile(passRoot, passKey, passPfx, path, domain, email string) bool

MakeTLSFile 生成TLS双向认证证书 # 1.创建根证书密钥文件(自己做CA)root.key: openssl genrsa -des3 -passout pass:123 -out ssl/root.key 2048 # 2.创建根证书的申请文件root.csr: openssl req -passin pass:123 -new -subj "/C=CN/ST=Shanghai/L=Shanghai/O=MyCompany/OU=MyCompany/CN=localhost/emailAddress=hk@cdeyun.com" -key ssl/root.key -out ssl/root.csr # 3.创建根证书root.crt: openssl x509 -passin pass:123 -req -days 3650 -sha256 -extensions v3_ca -signkey ssl/root.key -in ssl/root.csr -out ssl/root.crt rm -rf ssl/root.csr

# 1.创建客户端证书私钥 openssl genrsa -des3 -passout pass:456 -out ssl/ssl.key 2048 # 2.去除key口令 openssl rsa -passin pass:456 -in ssl/ssl.key -out ssl/ssl.key # 3.创建客户端证书申请文件ssl.csr openssl req -new -subj "/C=CN/ST=Shanghai/L=Shanghai/O=MyCompany/OU=MyCompany/CN=localhost/emailAddress=hk@cdeyun.com" -key ssl/ssl.key -out ssl/ssl.csr # 4.创建客户端证书文件ssl.crt openssl x509 -passin pass:123 -req -days 365 -sha256 -extensions v3_req -CA ssl/root.crt -CAkey ssl/root.key -CAcreateserial -in ssl/ssl.csr -out ssl/ssl.crt rm -rf ssl/ssl.csr rm -rf ssl/root.srl # 5.将客户端证书文件ssl.crt和客户端证书密钥文件ssl.key合并成客户端证书安装包ssl.pfx openssl pkcs12 -export -passout pass:789 -in ssl/ssl.crt -inkey ssl/ssl.key -out ssl/ssl.pfx

func RandIntn

func RandIntn(min, max int) int

RandIntn return min <= x <= max

func Shutdown

func Shutdown(waitTime time.Duration, hss ...*HST)

Shutdown 等待信号,优雅的停止服务

Types

type Context

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

Context 上下文数据

func (*Context) Close

func (o *Context) Close()

Close 结束后面的流程

func (*Context) Cookie

func (o *Context) Cookie(name string) (string, error)

Cookie 获取cookie

func (*Context) Corss

func (o *Context) Corss()

Corss 设置跨域

func (*Context) Data

func (o *Context) Data(statusCode int, data interface{})

Data 输出对象数据

func (*Context) HTMLFromDisk

func (o *Context) HTMLFromDisk(statusCode int, name string, data interface{}, names ...string)

HTMLFromDisk 实时读取模版输出HTML模版,需要hst.SetTemplatePath name: 主模版 names: 需要的其它模版组件

func (*Context) HTMLFromEmbedFS

func (o *Context) HTMLFromEmbedFS(_embeded embed.FS, statusCode int, name string, data interface{}, names ...string)

HTMLFromEmbedFS 实时读取embed模版输出HTML模版,需要hst.SetTemplatePath name: 主模版 names: 需要的其它模版组件

func (*Context) HTMLFromMemory

func (o *Context) HTMLFromMemory(statusCode int, name string, data interface{}, names ...string)

HTMLFromMemory 从模版缓存输出HTML模版,需要hst.ParseGlob或hst.ParseFiles

func (*Context) IsAjax

func (o *Context) IsAjax() bool

IsAjax 是否是ajax请求

func (*Context) JSON

func (o *Context) JSON(statusCode int, data interface{}) error

JSON 返回json数据,自动识别jsonp

func (*Context) JSON2

func (o *Context) JSON2(statusCode int, no int, data interface{}) error

JSON2 返回json数据,自动识别jsonp

func (*Context) SafeFormFloat

func (o *Context) SafeFormFloat(key string) float64

SafeFormFloat 获取form int

func (*Context) SafeFormInt

func (o *Context) SafeFormInt(key string) int

SafeFormInt 获取form int

func (*Context) SafeFormString

func (o *Context) SafeFormString(key string) string

SafeFormString 获取form string

func (*Context) SessionDestory

func (o *Context) SessionDestory() error

SessionDestory 销毁Session

func (*Context) SessionGet

func (o *Context) SessionGet(key string) (interface{}, error)

SessionGet 读取Session

func (*Context) SessionSet

func (o *Context) SessionSet(key string, value interface{}) error

SessionSet 设置Session,默认30分钟后过期

func (*Context) SessionSetExpire

func (o *Context) SessionSetExpire(key string, value interface{}, expire time.Duration) error

SessionSetExpire 设置Session,附带过期时间

func (*Context) SetCookie

func (o *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie 设置cookie

type Group

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

Group 路由分组

func (*Group) DELETE

func (o *Group) DELETE(pattern string, handler ...HandlerFunc) *HST

DELETE ...

func (*Group) GET

func (o *Group) GET(pattern string, handler ...HandlerFunc) *HST

GET ...

func (*Group) HandleFunc

func (o *Group) HandleFunc(pattern string, handler ...HandlerFunc) *HST

HandleFunc ... Example:

HandleFunc("/", func(c *hst.Context){}, func(c *hst.Context){})

func (*Group) OPTIONS

func (o *Group) OPTIONS(pattern string, handler ...HandlerFunc) *HST

OPTIONS ...

func (*Group) PATCH

func (o *Group) PATCH(pattern string, handler ...HandlerFunc) *HST

PATCH ...

func (*Group) POST

func (o *Group) POST(pattern string, handler ...HandlerFunc) *HST

POST ...

func (*Group) PUT

func (o *Group) PUT(pattern string, handler ...HandlerFunc) *HST

PUT ...

func (*Group) Use

func (o *Group) Use(handler ...HandlerFunc)

添加全局中间件, 调用该方法后,之后的路由都会调用该中间件

type HST

type HST struct {
	Addr string

	CrossOrigin                     string // 支持跨域 "*" / "a.com,b.com"
	DisableRouteLog                 bool   // 禁止显示启动时的route路径显示
	ContentSecurityPolicyReportOnly string // https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only

	DisableAutoGzip bool // 禁止自动gzip
	// contains filtered or unexported fields
}

HST ...

func New

func New(handlers *Handlers) *HST

New ...

func (*HST) DELETE

func (o *HST) DELETE(pattern string, handler ...HandlerFunc) *HST

DELETE ...

func (*HST) Favicon

func (o *HST) Favicon() *HST

Favicon 显示favicon.ico

func (*HST) GET

func (o *HST) GET(pattern string, handler ...HandlerFunc) *HST

GET ...

func (*HST) Group

func (o *HST) Group(name string, handler ...HandlerFunc) *Group

Group 路由分组

func (*HST) Handle

func (o *HST) Handle(pattern string, handler http.Handler) *HST

Handle 添加路由 Example:

Handle("/", http.Handler)

func (*HST) HandleFunc

func (o *HST) HandleFunc(pattern string, handler ...HandlerFunc) *HST

HandleFunc 添加路由 Example:

HandleFunc("/", func(c *hst.Context){}, func(c *hst.Context){})

func (*HST) HandlePfx

func (o *HST) HandlePfx(partten, pfxPath string) *HST

HandlePfx 输出pfx证书给浏览器安装 Example:

HandlePfx("/ssl.pfx", "/a/b/c.ssl.pfx"))

func (*HST) ListenAutoCert

func (o *HST) ListenAutoCert(cacheDir string, hosts ...string) error

ListenAutoCert 同时监听http/https,自动获取https证书 "golang.org/x/crypto/acme/autocert"

func (*HST) ListenHTTP

func (o *HST) ListenHTTP(addr string) error

ListenHTTP 启动HTTP服务

func (*HST) ListenHTTPS

func (o *HST) ListenHTTPS(addr, crt, key string) error

ListenHTTPS 启动HTTPS服务

func (*HST) ListenTLS

func (o *HST) ListenTLS(addr, ca, crt, key string) error

ListenTLS 启动TLS服务

func (*HST) OPTIONS

func (o *HST) OPTIONS(pattern string, handler ...HandlerFunc) *HST

OPTIONS ...

func (*HST) PATCH

func (o *HST) PATCH(pattern string, handler ...HandlerFunc) *HST

PATCH ...

func (*HST) POST

func (o *HST) POST(pattern string, handler ...HandlerFunc) *HST

POST ...

func (*HST) PUT

func (o *HST) PUT(pattern string, handler ...HandlerFunc) *HST

PUT ...

func (*HST) ParseFS

func (o *HST) ParseFS(fs fs.FS, patterns ...string) (*template.Template, error)

ParseFiles 载模版文件

func (*HST) ParseFiles

func (o *HST) ParseFiles(filenames ...string) (*template.Template, error)

ParseFiles 载模版文件

func (*HST) ParseGlob

func (o *HST) ParseGlob(pattern string) (*template.Template, error)

ParseGlob 载模版文件

func (*HST) RegisterHandle

func (o *HST) RegisterHandle(middleware []HandlerFunc, classes ...interface{}) *HST

RegisterHandle 注册自动路由 Example:

RegisterHandle(&User{}, &Other{})

func (*HST) SetDelims

func (o *HST) SetDelims(left, right string) *HST

SetDelims 定义模板符号

func (*HST) SetLogger

func (o *HST) SetLogger(logger io.Writer) *HST

SetLogger 设置日志记录

func (*HST) SetSession

func (o *HST) SetSession(sess Session) *HST

SetSession 设置Session

func (*HST) SetTemplateFunc

func (o *HST) SetTemplateFunc(funcMap template.FuncMap) *HST

SetTemplateFunc 设置模板函数

func (*HST) SetTemplatePath

func (o *HST) SetTemplatePath(pathname string) *HST

SetTemplatePath 设置模版文件跟路径

func (*HST) Static

func (o *HST) Static(partten, path string) *HST

Static 静态文件

func (*HST) StaticGzip

func (o *HST) StaticGzip(partten, path string) *HST

StaticGzip 静态文件,增加gzip压缩

func (*HST) StaticGzipEmbedFS

func (o *HST) StaticGzipEmbedFS(partten, gmtTime string, efs embed.FS) *HST

StaticGzipEmbedFS 静态文件,增加gzip压缩

func (*HST) Use

func (o *HST) Use(handler ...HandlerFunc)

添加全局中间件, 调用该方法后,之后的路由都会调用该中间件

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc ...

func BasicAuth

func BasicAuth(user, pass string) HandlerFunc

BasicAuth http验证

type Handlers

type Handlers map[string][]HandlerFunc

Handlers ...

func NewHandlers

func NewHandlers() Handlers

NewHandlers ...

func (Handlers) HandlerFunc

func (o Handlers) HandlerFunc(pattern string, handler ...HandlerFunc)

HandlerFunc ...

type HstROption

type HstROption struct {
	Method, Address    string
	Body               io.Reader // 请求数据
	InsecureSkipVerify bool      // 是否忽略ssl验证
	DisableReadData    bool      // 是否禁用调用内置读取数据,默认调用;读取数据后返回在Data中

	IsPostFrom bool // 是否是From提交表单,自动加上"Content-Type":"application/x-www-form-urlencoded"
	IsPostFile bool // 是否是From提交表单,自动加上"Content-Type":"multipart/form-data"
	IsPostJSON bool // 是否是From提交表单,自动加上"Content-Type":"application/json;charset=utf-8"
	IsPostXML  bool // 是否是From提交表单,自动加上"Content-Type":"text/xml"

	// 自定义header头
	// "Cookie":"..."
	Header          map[string]string
	Timeout         time.Duration // 超时时间,0为一直等待
	IdleConnTimeout time.Duration // 防止长连接使用
	TryCount        int           // 网络错误情况下,重试次数,默认不重试
	TryWaitTime     time.Duration // 重试间隔时间,默认不间隔
	Proxy           *url.URL      // 代理

	// 重定向回调
	// func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }
	CheckRedirect func(req *http.Request, via []*http.Request) error
	Client        *http.Client // 重用连接

	// TLS
	CaFile  string
	CrtFile string
	KeyFile string
}

func (*HstROption) GetCURL

func (o *HstROption) GetCURL() string

GetCURL 生成curl命令行

type HstRResponse

type HstRResponse struct {
	Data        []byte        // 返回数据
	ElapsedTime time.Duration // 消耗时间
	Client      *http.Client
	Req         *http.Request
	Res         *http.Response
	Opt         *HstROption
}

func Request

func Request(method, address string, opt *HstROption) (hrr *HstRResponse, err error)

Request 网络请求数据

func (*HstRResponse) Cookies

func (o *HstRResponse) Cookies() string

Cookies 返回cookie字符串 a=1;b=2;c=3...

type JSONData

type JSONData struct {
	No   int         `json:"no"`
	Data interface{} `json:"data"`
}

JSONData 输出数据JSON格式

type LogData

type LogData struct {
	RemoteIP    string
	LocalTime   time.Time
	Status      int
	UseTime     time.Duration
	URI         string
	Sent        int
	Referer     string
	UserAgent   string
	XForwardFor string
}

LogData 127.0.0.1 [2006-01-02 15:04:05] 200 123s "GET / HTTP/1.1" 1234 "referer" "user_agent" "http_x_forwarded_for"

type Session

type Session interface {
	GetCookieExpire() time.Duration
	Set(c *Context, key string, value interface{}, expire time.Duration) error
	Get(c *Context, key string) (interface{}, error)
	Destory(c *Context) error
}

Session ...

func NewSessionFile

func NewSessionFile(cookieDomain, cookiePath, cookieName, path string, maxExpire time.Duration) Session

NewSessionFile ...

func NewSessionMemory

func NewSessionMemory(cookieDomain, cookiePath, cookieName string, maxExpire time.Duration) Session

NewSessionMemory ...

type SessionFile

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

SessionFile ...

func (*SessionFile) Destory

func (o *SessionFile) Destory(c *Context) error

Destory 销毁Session

func (*SessionFile) Get

func (o *SessionFile) Get(c *Context, key string) (interface{}, error)

Get 读取Session

func (*SessionFile) GetCookieExpire

func (o *SessionFile) GetCookieExpire() time.Duration

GetCookieExpire 获取cookie的过期时间

func (*SessionFile) Set

func (o *SessionFile) Set(c *Context, key string, value interface{}, expire time.Duration) error

Set 设置Session

type SessionMemory

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

SessionMemory ...

func (*SessionMemory) Destory

func (o *SessionMemory) Destory(c *Context) error

Destory 销毁Session

func (*SessionMemory) Get

func (o *SessionMemory) Get(c *Context, key string) (interface{}, error)

Get 读取Session

func (*SessionMemory) GetCookieExpire

func (o *SessionMemory) GetCookieExpire() time.Duration

GetCookieExpire 获取cookie的过期时间

func (*SessionMemory) Set

func (o *SessionMemory) Set(c *Context, key string, value interface{}, expire time.Duration) error

Set 设置Session

Directories

Path Synopsis
golang.org
x/crypto/acme
Package acme provides an implementation of the Automatic Certificate Management Environment (ACME) spec, most famously used by Let's Encrypt.
Package acme provides an implementation of the Automatic Certificate Management Environment (ACME) spec, most famously used by Let's Encrypt.
x/crypto/acme/autocert
Package autocert provides automatic access to certificates from Let's Encrypt and any other ACME-based CA.
Package autocert provides automatic access to certificates from Let's Encrypt and any other ACME-based CA.
x/net/idna
Package idna implements IDNA2008 using the compatibility processing defined by UTS (Unicode Technical Standard) #46, which defines a standard to deal with the transition from IDNA2003.
Package idna implements IDNA2008 using the compatibility processing defined by UTS (Unicode Technical Standard) #46, which defines a standard to deal with the transition from IDNA2003.
x/net/internal/socks
Package socks provides a SOCKS version 5 client implementation.
Package socks provides a SOCKS version 5 client implementation.
x/net/proxy
Package proxy provides support for a variety of protocols to proxy network data.
Package proxy provides support for a variety of protocols to proxy network data.
x/text/secure/bidirule
Package bidirule implements the Bidi Rule defined by RFC 5893.
Package bidirule implements the Bidi Rule defined by RFC 5893.
x/text/transform
Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations.
Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations.
x/text/unicode/bidi
Package bidi contains functionality for bidirectional text support.
Package bidi contains functionality for bidirectional text support.
x/text/unicode/norm
Package norm contains types and functions for normalizing Unicode strings.
Package norm contains types and functions for normalizing Unicode strings.

Jump to

Keyboard shortcuts

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