You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/rest/server.go

215 lines
5.4 KiB
Go

package rest
4 years ago
import (
"errors"
"fmt"
"net/http"
"time"
"github.com/justinas/alice"
"github.com/tal-tech/go-zero/core/codec"
"github.com/tal-tech/go-zero/core/load"
"github.com/tal-tech/go-zero/core/stat"
"github.com/tal-tech/go-zero/rest/handler"
"github.com/tal-tech/go-zero/rest/httpx"
"github.com/tal-tech/go-zero/rest/internal"
"github.com/tal-tech/go-zero/rest/internal/router"
4 years ago
)
// use 1000m to represent 100%
const topCpuUsage = 1000
var ErrSignatureConfig = errors.New("bad config for Signature")
type engine struct {
conf RestConf
routes []featuredRoutes
unauthorizedCallback handler.UnauthorizedCallback
unsignedCallback handler.UnsignedCallback
middlewares []Middleware
shedder load.Shedder
priorityShedder load.Shedder
}
func newEngine(c RestConf) *engine {
srv := &engine{
4 years ago
conf: c,
}
if c.CpuThreshold > 0 {
srv.shedder = load.NewAdaptiveShedder(load.WithCpuThreshold(c.CpuThreshold))
srv.priorityShedder = load.NewAdaptiveShedder(load.WithCpuThreshold(
(c.CpuThreshold + topCpuUsage) >> 1))
}
return srv
}
func (s *engine) AddRoutes(r featuredRoutes) {
4 years ago
s.routes = append(s.routes, r)
}
func (s *engine) SetUnauthorizedCallback(callback handler.UnauthorizedCallback) {
4 years ago
s.unauthorizedCallback = callback
}
func (s *engine) SetUnsignedCallback(callback handler.UnsignedCallback) {
4 years ago
s.unsignedCallback = callback
}
func (s *engine) Start() error {
4 years ago
return s.StartWithRouter(router.NewPatRouter())
4 years ago
}
func (s *engine) StartWithRouter(router httpx.Router) error {
4 years ago
if err := s.bindRoutes(router); err != nil {
return err
}
4 years ago
return internal.StartHttp(s.conf.Host, s.conf.Port, router)
4 years ago
}
func (s *engine) appendAuthHandler(fr featuredRoutes, chain alice.Chain,
4 years ago
verifier func(alice.Chain) alice.Chain) alice.Chain {
if fr.jwt.enabled {
if len(fr.jwt.prevSecret) == 0 {
4 years ago
chain = chain.Append(handler.Authorize(fr.jwt.secret,
handler.WithUnauthorizedCallback(s.unauthorizedCallback)))
4 years ago
} else {
4 years ago
chain = chain.Append(handler.Authorize(fr.jwt.secret,
handler.WithPrevSecret(fr.jwt.prevSecret),
handler.WithUnauthorizedCallback(s.unauthorizedCallback)))
4 years ago
}
}
return verifier(chain)
}
func (s *engine) bindFeaturedRoutes(router httpx.Router, fr featuredRoutes, metrics *stat.Metrics) error {
4 years ago
verifier, err := s.signatureVerifier(fr.signature)
if err != nil {
return err
}
for _, route := range fr.routes {
if err := s.bindRoute(fr, router, metrics, route, verifier); err != nil {
return err
}
}
return nil
}
func (s *engine) bindRoute(fr featuredRoutes, router httpx.Router, metrics *stat.Metrics,
4 years ago
route Route, verifier func(chain alice.Chain) alice.Chain) error {
chain := alice.New(
4 years ago
handler.TracingHandler,
4 years ago
s.getLogHandler(),
4 years ago
handler.MaxConns(s.conf.MaxConns),
handler.BreakerHandler(route.Method, route.Path, metrics),
handler.SheddingHandler(s.getShedder(fr.priority), metrics),
handler.TimeoutHandler(time.Duration(s.conf.Timeout)*time.Millisecond),
handler.RecoverHandler,
handler.MetricHandler(metrics),
handler.PromMetricHandler(route.Path),
handler.MaxBytesHandler(s.conf.MaxBytes),
handler.GunzipHandler,
4 years ago
)
chain = s.appendAuthHandler(fr, chain, verifier)
for _, middleware := range s.middlewares {
chain = chain.Append(convertMiddleware(middleware))
}
handle := chain.ThenFunc(route.Handler)
return router.Handle(route.Method, route.Path, handle)
}
func (s *engine) bindRoutes(router httpx.Router) error {
4 years ago
metrics := s.createMetrics()
for _, fr := range s.routes {
if err := s.bindFeaturedRoutes(router, fr, metrics); err != nil {
return err
}
}
return nil
}
func (s *engine) createMetrics() *stat.Metrics {
4 years ago
var metrics *stat.Metrics
if len(s.conf.Name) > 0 {
metrics = stat.NewMetrics(s.conf.Name)
} else {
metrics = stat.NewMetrics(fmt.Sprintf("%s:%d", s.conf.Host, s.conf.Port))
}
return metrics
}
func (s *engine) getLogHandler() func(http.Handler) http.Handler {
4 years ago
if s.conf.Verbose {
4 years ago
return handler.DetailedLogHandler
4 years ago
} else {
4 years ago
return handler.LogHandler
4 years ago
}
}
func (s *engine) getShedder(priority bool) load.Shedder {
4 years ago
if priority && s.priorityShedder != nil {
return s.priorityShedder
}
return s.shedder
}
func (s *engine) signatureVerifier(signature signatureSetting) (func(chain alice.Chain) alice.Chain, error) {
4 years ago
if !signature.enabled {
return func(chain alice.Chain) alice.Chain {
return chain
}, nil
}
if len(signature.PrivateKeys) == 0 {
if signature.Strict {
return nil, ErrSignatureConfig
} else {
return func(chain alice.Chain) alice.Chain {
return chain
}, nil
}
}
decrypters := make(map[string]codec.RsaDecrypter)
for _, key := range signature.PrivateKeys {
fingerprint := key.Fingerprint
file := key.KeyFile
decrypter, err := codec.NewRsaDecrypter(file)
if err != nil {
return nil, err
}
decrypters[fingerprint] = decrypter
}
return func(chain alice.Chain) alice.Chain {
if s.unsignedCallback != nil {
4 years ago
return chain.Append(handler.ContentSecurityHandler(
4 years ago
decrypters, signature.Expiry, signature.Strict, s.unsignedCallback))
} else {
4 years ago
return chain.Append(handler.ContentSecurityHandler(
4 years ago
decrypters, signature.Expiry, signature.Strict))
}
}, nil
}
func (s *engine) use(middleware Middleware) {
4 years ago
s.middlewares = append(s.middlewares, middleware)
}
func convertMiddleware(ware Middleware) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(ware(next.ServeHTTP))
}
}