rename ngin to rest

master
kevin 4 years ago
parent 0897f60c5d
commit f372ded63c

@ -6,6 +6,6 @@ import (
) )
type Config struct { type Config struct {
rest.RtConf rest.RestConf
Rpc rpcx.RpcClientConf Rpc rpcx.RpcClientConf
} }

@ -24,7 +24,7 @@ func main() {
Client: client, Client: client,
} }
engine := rest.MustNewEngine(c.RtConf) engine := rest.MustNewServer(c.RestConf)
defer engine.Stop() defer engine.Stop()
handler.RegisterHandlers(engine, ctx) handler.RegisterHandlers(engine, ctx)

@ -8,7 +8,7 @@ import (
"zero/rest" "zero/rest"
) )
func RegisterHandlers(engine *rest.Engine, ctx *svc.ServiceContext) { func RegisterHandlers(engine *rest.Server, ctx *svc.ServiceContext) {
engine.AddRoutes([]rest.Route{ engine.AddRoutes([]rest.Route{
{ {
Method: http.MethodGet, Method: http.MethodGet,

@ -6,6 +6,6 @@ import (
) )
type Config struct { type Config struct {
rest.RtConf rest.RestConf
Rpc rpcx.RpcClientConf Rpc rpcx.RpcClientConf
} }

@ -24,7 +24,7 @@ func main() {
Client: client, Client: client,
} }
engine := rest.MustNewEngine(c.RtConf) engine := rest.MustNewServer(c.RestConf)
defer engine.Stop() defer engine.Stop()
handler.RegisterHandlers(engine, ctx) handler.RegisterHandlers(engine, ctx)

@ -8,7 +8,7 @@ import (
"zero/rest" "zero/rest"
) )
func RegisterHandlers(engine *rest.Engine, ctx *svc.ServiceContext) { func RegisterHandlers(engine *rest.Server, ctx *svc.ServiceContext) {
engine.AddRoutes([]rest.Route{ engine.AddRoutes([]rest.Route{
{ {
Method: http.MethodGet, Method: http.MethodGet,

@ -15,7 +15,7 @@ import (
func main() { func main() {
logx.Disable() logx.Disable()
stat.SetReporter(nil) stat.SetReporter(nil)
server := rest.MustNewEngine(rest.RtConf{ server := rest.MustNewServer(rest.RestConf{
ServiceConf: service.ServiceConf{ ServiceConf: service.ServiceConf{
Name: "breaker", Name: "breaker",
Log: logx.LogConf{ Log: logx.LogConf{

@ -47,7 +47,7 @@ func handle(w http.ResponseWriter, r *http.Request) {
func main() { func main() {
flag.Parse() flag.Parse()
engine := rest.MustNewEngine(rest.RtConf{ engine := rest.MustNewServer(rest.RestConf{
ServiceConf: service.ServiceConf{ ServiceConf: service.ServiceConf{
Log: logx.LogConf{ Log: logx.LogConf{
Mode: "console", Mode: "console",

@ -37,7 +37,7 @@ func handlePost(w http.ResponseWriter, r *http.Request) {
func main() { func main() {
flag.Parse() flag.Parse()
engine := rest.MustNewEngine(rest.RtConf{ engine := rest.MustNewServer(rest.RestConf{
ServiceConf: service.ServiceConf{ ServiceConf: service.ServiceConf{
Log: logx.LogConf{ Log: logx.LogConf{
Mode: "console", Mode: "console",

@ -42,7 +42,7 @@ func main() {
flag.Parse() flag.Parse()
logx.Disable() logx.Disable()
engine := rest.MustNewEngine(rest.RtConf{ engine := rest.MustNewServer(rest.RestConf{
ServiceConf: service.ServiceConf{ ServiceConf: service.ServiceConf{
Log: logx.LogConf{ Log: logx.LogConf{
Mode: "console", Mode: "console",

@ -31,7 +31,7 @@ func handle(w http.ResponseWriter, r *http.Request) {
func main() { func main() {
flag.Parse() flag.Parse()
engine := rest.MustNewEngine(rest.RtConf{ engine := rest.MustNewServer(rest.RestConf{
ServiceConf: service.ServiceConf{ ServiceConf: service.ServiceConf{
Log: logx.LogConf{ Log: logx.LogConf{
Path: "logs", Path: "logs",

@ -20,7 +20,7 @@ const jwtUserField = "user"
type ( type (
Config struct { Config struct {
rest.RtConf rest.RestConf
AccessSecret string AccessSecret string
AccessExpire int64 `json:",default=1209600"` // 2 weeks AccessExpire int64 `json:",default=1209600"` // 2 weeks
RefreshSecret string RefreshSecret string
@ -79,7 +79,7 @@ func main() {
var c Config var c Config
conf.MustLoad("user.json", &c) conf.MustLoad("user.json", &c)
engine, err := rest.NewEngine(c.RtConf) engine, err := rest.NewServer(c.RestConf)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

@ -25,7 +25,7 @@ func main() {
}() }()
logx.Disable() logx.Disable()
engine := rest.MustNewEngine(rest.RtConf{ engine := rest.MustNewServer(rest.RestConf{
ServiceConf: service.ServiceConf{ ServiceConf: service.ServiceConf{
Log: logx.LogConf{ Log: logx.LogConf{
Mode: "console", Mode: "console",

@ -42,7 +42,7 @@ func main() {
var c rpcx.RpcClientConf var c rpcx.RpcClientConf
conf.MustLoad(*configFile, &c) conf.MustLoad(*configFile, &c)
client = rpcx.MustNewClient(c) client = rpcx.MustNewClient(c)
engine := rest.MustNewEngine(rest.RtConf{ engine := rest.MustNewServer(rest.RestConf{
ServiceConf: service.ServiceConf{ ServiceConf: service.ServiceConf{
Log: logx.LogConf{ Log: logx.LogConf{
Mode: "console", Mode: "console",

@ -21,10 +21,10 @@ type (
// why not name it as Conf, because we need to consider usage like: // why not name it as Conf, because we need to consider usage like:
// type Config struct { // type Config struct {
// rpcx.RpcConf // rpcx.RpcConf
// rest.RtConf // rest.RestConf
// } // }
// if with the name Conf, there will be two Conf inside Config. // if with the name Conf, there will be two Conf inside Config.
RtConf struct { RestConf struct {
service.ServiceConf service.ServiceConf
Host string `json:",default=0.0.0.0"` Host string `json:",default=0.0.0.0"`
Port int Port int

@ -1,40 +0,0 @@
package internal
import (
"crypto/tls"
"fmt"
"net/http"
)
func StartHttp(host string, port int, handler http.Handler) error {
addr := fmt.Sprintf("%s:%d", host, port)
server := buildHttpServer(addr, handler)
return StartServer(server)
}
func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler) error {
addr := fmt.Sprintf("%s:%d", host, port)
if server, err := buildHttpsServer(addr, handler, certFile, keyFile); err != nil {
return err
} else {
return StartServer(server)
}
}
func buildHttpServer(addr string, handler http.Handler) *http.Server {
return &http.Server{Addr: addr, Handler: handler}
}
func buildHttpsServer(addr string, handler http.Handler, certFile, keyFile string) (*http.Server, error) {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
config := tls.Config{Certificates: []tls.Certificate{cert}}
return &http.Server{
Addr: addr,
Handler: handler,
TLSConfig: &config,
}, nil
}

@ -2,11 +2,28 @@ package internal
import ( import (
"context" "context"
"crypto/tls"
"fmt"
"net/http" "net/http"
"zero/core/proc" "zero/core/proc"
) )
func StartHttp(host string, port int, handler http.Handler) error {
addr := fmt.Sprintf("%s:%d", host, port)
server := buildHttpServer(addr, handler)
return StartServer(server)
}
func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler) error {
addr := fmt.Sprintf("%s:%d", host, port)
if server, err := buildHttpsServer(addr, handler, certFile, keyFile); err != nil {
return err
} else {
return StartServer(server)
}
}
func StartServer(srv *http.Server) error { func StartServer(srv *http.Server) error {
proc.AddWrapUpListener(func() { proc.AddWrapUpListener(func() {
srv.Shutdown(context.Background()) srv.Shutdown(context.Background())
@ -14,3 +31,21 @@ func StartServer(srv *http.Server) error {
return srv.ListenAndServe() return srv.ListenAndServe()
} }
func buildHttpServer(addr string, handler http.Handler) *http.Server {
return &http.Server{Addr: addr, Handler: handler}
}
func buildHttpsServer(addr string, handler http.Handler, certFile, keyFile string) (*http.Server, error) {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
config := tls.Config{Certificates: []tls.Certificate{cert}}
return &http.Server{
Addr: addr,
Handler: handler,
TLSConfig: &config,
}, nil
}

@ -11,19 +11,19 @@ import (
type ( type (
runOptions struct { runOptions struct {
start func(*server) error start func(*engine) error
} }
RunOption func(*Engine) RunOption func(*Server)
Engine struct { Server struct {
srv *server ngin *engine
opts runOptions opts runOptions
} }
) )
func MustNewEngine(c RtConf, opts ...RunOption) *Engine { func MustNewServer(c RestConf, opts ...RunOption) *Server {
engine, err := NewEngine(c, opts...) engine, err := NewServer(c, opts...)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -31,51 +31,51 @@ func MustNewEngine(c RtConf, opts ...RunOption) *Engine {
return engine return engine
} }
func NewEngine(c RtConf, opts ...RunOption) (*Engine, error) { func NewServer(c RestConf, opts ...RunOption) (*Server, error) {
if err := c.SetUp(); err != nil { if err := c.SetUp(); err != nil {
return nil, err return nil, err
} }
engine := &Engine{ server := &Server{
srv: newServer(c), ngin: newEngine(c),
opts: runOptions{ opts: runOptions{
start: func(srv *server) error { start: func(srv *engine) error {
return srv.Start() return srv.Start()
}, },
}, },
} }
for _, opt := range opts { for _, opt := range opts {
opt(engine) opt(server)
} }
return engine, nil return server, nil
} }
func (e *Engine) AddRoutes(rs []Route, opts ...RouteOption) { func (e *Server) AddRoutes(rs []Route, opts ...RouteOption) {
r := featuredRoutes{ r := featuredRoutes{
routes: rs, routes: rs,
} }
for _, opt := range opts { for _, opt := range opts {
opt(&r) opt(&r)
} }
e.srv.AddRoutes(r) e.ngin.AddRoutes(r)
} }
func (e *Engine) AddRoute(r Route, opts ...RouteOption) { func (e *Server) AddRoute(r Route, opts ...RouteOption) {
e.AddRoutes([]Route{r}, opts...) e.AddRoutes([]Route{r}, opts...)
} }
func (e *Engine) Start() { func (e *Server) Start() {
handleError(e.opts.start(e.srv)) handleError(e.opts.start(e.ngin))
} }
func (e *Engine) Stop() { func (e *Server) Stop() {
logx.Close() logx.Close()
} }
func (e *Engine) Use(middleware Middleware) { func (e *Server) Use(middleware Middleware) {
e.srv.use(middleware) e.ngin.use(middleware)
} }
func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware { func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
@ -125,8 +125,8 @@ func WithPriority() RouteOption {
} }
func WithRouter(router router.Router) RunOption { func WithRouter(router router.Router) RunOption {
return func(engine *Engine) { return func(server *Server) {
engine.opts.start = func(srv *server) error { server.opts.start = func(srv *engine) error {
return srv.StartWithRouter(router) return srv.StartWithRouter(router)
} }
} }
@ -142,14 +142,14 @@ func WithSignature(signature SignatureConf) RouteOption {
} }
func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption { func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
return func(engine *Engine) { return func(engine *Server) {
engine.srv.SetUnauthorizedCallback(callback) engine.ngin.SetUnauthorizedCallback(callback)
} }
} }
func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption { func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
return func(engine *Engine) { return func(engine *Server) {
engine.srv.SetUnsignedCallback(callback) engine.ngin.SetUnsignedCallback(callback)
} }
} }

@ -21,11 +21,8 @@ const topCpuUsage = 1000
var ErrSignatureConfig = errors.New("bad config for Signature") var ErrSignatureConfig = errors.New("bad config for Signature")
type ( type engine struct {
Middleware func(next http.HandlerFunc) http.HandlerFunc conf RestConf
server struct {
conf RtConf
routes []featuredRoutes routes []featuredRoutes
unauthorizedCallback handler.UnauthorizedCallback unauthorizedCallback handler.UnauthorizedCallback
unsignedCallback handler.UnsignedCallback unsignedCallback handler.UnsignedCallback
@ -33,10 +30,9 @@ type (
shedder load.Shedder shedder load.Shedder
priorityShedder load.Shedder priorityShedder load.Shedder
} }
)
func newServer(c RtConf) *server { func newEngine(c RestConf) *engine {
srv := &server{ srv := &engine{
conf: c, conf: c,
} }
if c.CpuThreshold > 0 { if c.CpuThreshold > 0 {
@ -48,23 +44,23 @@ func newServer(c RtConf) *server {
return srv return srv
} }
func (s *server) AddRoutes(r featuredRoutes) { func (s *engine) AddRoutes(r featuredRoutes) {
s.routes = append(s.routes, r) s.routes = append(s.routes, r)
} }
func (s *server) SetUnauthorizedCallback(callback handler.UnauthorizedCallback) { func (s *engine) SetUnauthorizedCallback(callback handler.UnauthorizedCallback) {
s.unauthorizedCallback = callback s.unauthorizedCallback = callback
} }
func (s *server) SetUnsignedCallback(callback handler.UnsignedCallback) { func (s *engine) SetUnsignedCallback(callback handler.UnsignedCallback) {
s.unsignedCallback = callback s.unsignedCallback = callback
} }
func (s *server) Start() error { func (s *engine) Start() error {
return s.StartWithRouter(router.NewPatRouter()) return s.StartWithRouter(router.NewPatRouter())
} }
func (s *server) StartWithRouter(router router.Router) error { func (s *engine) StartWithRouter(router router.Router) error {
if err := s.bindRoutes(router); err != nil { if err := s.bindRoutes(router); err != nil {
return err return err
} }
@ -72,7 +68,7 @@ func (s *server) StartWithRouter(router router.Router) error {
return internal.StartHttp(s.conf.Host, s.conf.Port, router) return internal.StartHttp(s.conf.Host, s.conf.Port, router)
} }
func (s *server) appendAuthHandler(fr featuredRoutes, chain alice.Chain, func (s *engine) appendAuthHandler(fr featuredRoutes, chain alice.Chain,
verifier func(alice.Chain) alice.Chain) alice.Chain { verifier func(alice.Chain) alice.Chain) alice.Chain {
if fr.jwt.enabled { if fr.jwt.enabled {
if len(fr.jwt.prevSecret) == 0 { if len(fr.jwt.prevSecret) == 0 {
@ -88,7 +84,7 @@ func (s *server) appendAuthHandler(fr featuredRoutes, chain alice.Chain,
return verifier(chain) return verifier(chain)
} }
func (s *server) bindFeaturedRoutes(router router.Router, fr featuredRoutes, metrics *stat.Metrics) error { func (s *engine) bindFeaturedRoutes(router router.Router, fr featuredRoutes, metrics *stat.Metrics) error {
verifier, err := s.signatureVerifier(fr.signature) verifier, err := s.signatureVerifier(fr.signature)
if err != nil { if err != nil {
return err return err
@ -103,7 +99,7 @@ func (s *server) bindFeaturedRoutes(router router.Router, fr featuredRoutes, met
return nil return nil
} }
func (s *server) bindRoute(fr featuredRoutes, router router.Router, metrics *stat.Metrics, func (s *engine) bindRoute(fr featuredRoutes, router router.Router, metrics *stat.Metrics,
route Route, verifier func(chain alice.Chain) alice.Chain) error { route Route, verifier func(chain alice.Chain) alice.Chain) error {
chain := alice.New( chain := alice.New(
handler.TracingHandler, handler.TracingHandler,
@ -128,7 +124,7 @@ func (s *server) bindRoute(fr featuredRoutes, router router.Router, metrics *sta
return router.Handle(route.Method, route.Path, handle) return router.Handle(route.Method, route.Path, handle)
} }
func (s *server) bindRoutes(router router.Router) error { func (s *engine) bindRoutes(router router.Router) error {
metrics := s.createMetrics() metrics := s.createMetrics()
for _, fr := range s.routes { for _, fr := range s.routes {
@ -140,7 +136,7 @@ func (s *server) bindRoutes(router router.Router) error {
return nil return nil
} }
func (s *server) createMetrics() *stat.Metrics { func (s *engine) createMetrics() *stat.Metrics {
var metrics *stat.Metrics var metrics *stat.Metrics
if len(s.conf.Name) > 0 { if len(s.conf.Name) > 0 {
@ -152,7 +148,7 @@ func (s *server) createMetrics() *stat.Metrics {
return metrics return metrics
} }
func (s *server) getLogHandler() func(http.Handler) http.Handler { func (s *engine) getLogHandler() func(http.Handler) http.Handler {
if s.conf.Verbose { if s.conf.Verbose {
return handler.DetailedLogHandler return handler.DetailedLogHandler
} else { } else {
@ -160,14 +156,14 @@ func (s *server) getLogHandler() func(http.Handler) http.Handler {
} }
} }
func (s *server) getShedder(priority bool) load.Shedder { func (s *engine) getShedder(priority bool) load.Shedder {
if priority && s.priorityShedder != nil { if priority && s.priorityShedder != nil {
return s.priorityShedder return s.priorityShedder
} }
return s.shedder return s.shedder
} }
func (s *server) signatureVerifier(signature signatureSetting) (func(chain alice.Chain) alice.Chain, error) { func (s *engine) signatureVerifier(signature signatureSetting) (func(chain alice.Chain) alice.Chain, error) {
if !signature.enabled { if !signature.enabled {
return func(chain alice.Chain) alice.Chain { return func(chain alice.Chain) alice.Chain {
return chain return chain
@ -207,7 +203,7 @@ func (s *server) signatureVerifier(signature signatureSetting) (func(chain alice
}, nil }, nil
} }
func (s *server) use(middleware Middleware) { func (s *engine) use(middleware Middleware) {
s.middlewares = append(s.middlewares, middleware) s.middlewares = append(s.middlewares, middleware)
} }

@ -3,12 +3,16 @@ package rest
import "net/http" import "net/http"
type ( type (
Middleware func(next http.HandlerFunc) http.HandlerFunc
Route struct { Route struct {
Method string Method string
Path string Path string
Handler http.HandlerFunc Handler http.HandlerFunc
} }
RouteOption func(r *featuredRoutes)
jwtSetting struct { jwtSetting struct {
enabled bool enabled bool
secret string secret string
@ -26,6 +30,4 @@ type (
signature signatureSetting signature signatureSetting
routes []Route routes []Route
} }
RouteOption func(r *featuredRoutes)
) )

@ -3,5 +3,5 @@ package config
import "zero/rest" import "zero/rest"
type Config struct { type Config struct {
rest.RtConf rest.RestConf
} }

@ -17,7 +17,7 @@ func main() {
var c config.Config var c config.Config
conf.MustLoad(*configFile, &c) conf.MustLoad(*configFile, &c)
engine := rest.MustNewEngine(c.RtConf) engine := rest.MustNewServer(c.RestConf)
defer engine.Stop() defer engine.Stop()
handler.RegisterHandlers(engine) handler.RegisterHandlers(engine)

@ -6,7 +6,7 @@ import (
"zero/rest" "zero/rest"
) )
func RegisterHandlers(engine *rest.Engine) { func RegisterHandlers(engine *rest.Server) {
engine.AddRoutes([]rest.Route{ engine.AddRoutes([]rest.Route{
{ {
Method: http.MethodGet, Method: http.MethodGet,

@ -18,7 +18,7 @@ import (
) )
type Config struct { type Config struct {
rest.RtConf rest.RestConf
} }
` `
) )

@ -30,7 +30,7 @@ func main() {
ctx := svc.NewServiceContext(c) ctx := svc.NewServiceContext(c)
engine := rest.MustNewEngine(c.RtConf) engine := rest.MustNewEngine(c.RestConf)
defer engine.Stop() defer engine.Stop()
handler.RegisterHandlers(engine, ctx) handler.RegisterHandlers(engine, ctx)

Loading…
Cancel
Save