Skip to content

Commit

Permalink
fix: Logf override the past. update OnStart and OnShutdown.
Browse files Browse the repository at this point in the history
  • Loading branch information
luopengift committed Nov 16, 2024
1 parent f099ba3 commit 859bf41
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 44 deletions.
22 changes: 19 additions & 3 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,15 @@ type Options struct {
MaxConns int
Verify bool
Stream func(int64, []byte) error
Log func(ctx context.Context, stat *Stat)

Transport http.RoundTripper
HttpRoundTripper []func(http.RoundTripper) http.RoundTripper

Handler http.Handler
HttpHandler []func(http.Handler) http.Handler
OnStart func(*http.Server)
OnShutdown func(*http.Server)

certFile string
keyFile string
Expand All @@ -53,6 +56,9 @@ func newOptions(opts []Option, extends ...Option) Options {
Timeout: 30 * time.Second,
MaxConns: 100,
Proxy: http.ProxyFromEnvironment,

OnStart: func(*http.Server) {},
OnShutdown: func(*http.Server) {},
}
for _, o := range opts {
o(&opt)
Expand Down Expand Up @@ -283,10 +289,20 @@ func RoundTripper(tr http.RoundTripper) Option {
}

// Logf print log
func Logf(f func(ctx context.Context, stat *Stat)) Option {
func Logf(f func(context.Context, *Stat)) Option {
return func(o *Options) {
o.Log = f
}
}

func OnStart(f func(*http.Server)) Option {
return func(o *Options) {
o.HttpRoundTripper = append(o.HttpRoundTripper, printRoundTripper(f))
o.HttpHandler = append(o.HttpHandler, printHandler(f))
o.OnStart = f
}
}

func OnShutdown(f func(*http.Server)) Option {
return func(o *Options) {
o.OnShutdown = f
}
}
5 changes: 3 additions & 2 deletions requests_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func Test_PostBody(t *testing.T) {
sess := New(
BasicAuth("user", "123456"),
Logf(func(context.Context, *Stat) {
fmt.Println("session")
fmt.Println("111111111")

}),
)
Expand All @@ -71,7 +71,8 @@ func Test_PostBody(t *testing.T) {
Header("hello", "world"),
//TraceLv(9),
Logf(func(ctx context.Context, stat *Stat) {
t.Logf("%v", stat.String())
fmt.Println(22222222)
//t.Logf("%v", stat.String())
}),
)
if err != nil {
Expand Down
45 changes: 17 additions & 28 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ func (mux *ServeMux) Use(fn ...func(http.Handler) http.Handler) {
func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
current := mux.root.Find(r.URL.Path[1:])
handler, options := current.handler, newOptions(mux.opts, current.opts...)
if options.Log != nil {
options.HttpHandler = append(options.HttpHandler, printHandler(options.Log))
}
for _, h := range options.HttpHandler {
handler = h(handler)
}
Expand All @@ -172,47 +175,35 @@ func (mux *ServeMux) Pprof() {
type Server struct {
options Options
server *http.Server

onStartup func(*http.Server)
onShutdown func(*http.Server)
}

// NewServer new server, opts is not add to ServeMux
func NewServer(ctx context.Context, h http.Handler, opts ...Option) *Server {
s := &Server{server: &http.Server{Handler: h}, onStartup: func(*http.Server) {}, onShutdown: func(*http.Server) {}}
if mux, ok := h.(*ServeMux); ok {
s.options = newOptions(mux.opts, opts...)
} else {
s.options = newOptions(opts)
s := &Server{server: &http.Server{Handler: h}}
mux, ok := h.(*ServeMux)
if !ok {
mux = NewServeMux()
}
s.options = newOptions(mux.opts, opts...)

u, err := url.Parse(s.options.URL)
if err != nil {
panic(err)
}

s.server.Addr = u.Host
s.server.RegisterOnShutdown(func() { s.onShutdown(s.server) })

go func() {
select {
case <-ctx.Done():
if err := s.server.Shutdown(ctx); err != nil {
panic(err)
}
}
}()
s.options.OnStart(s.server)
s.server.RegisterOnShutdown(func() { s.options.OnShutdown(s.server) })
go s.Shutdown(ctx)
return s
}

// OnStartup do something before serve startup
func (s *Server) OnStartup(f func(s *http.Server)) {
s.onStartup = f
}

// OnShutdown do something after serve shutdown
func (s *Server) OnShutdown(f func(s *http.Server)) {
s.onShutdown = f
// Shutdown gracefully shuts down the server without interrupting any active connections.
func (s *Server) Shutdown(ctx context.Context) error {
select {
case <-ctx.Done():
return s.server.Shutdown(ctx)
}
}

// ListenAndServe listens on the TCP network address srv.Addr and then
Expand All @@ -231,8 +222,6 @@ func (s *Server) OnShutdown(f func(s *http.Server)) {
// ListenAndServe(TLS) always returns a non-nil error. After [Server.Shutdown] or
// [Server.Close], the returned error is [ErrServerClosed].
func (s *Server) ListenAndServe() (err error) {

s.onStartup(s.server)
if s.options.certFile == "" || s.options.keyFile == "" {
return s.server.ListenAndServe()
}
Expand Down
33 changes: 23 additions & 10 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,27 @@ func (h) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
func Test_Server(t *testing.T) {

mux := requests.NewServeMux()
mux := requests.NewServeMux(requests.Logf(func(ctx context.Context, stat *requests.Stat) {
fmt.Println("serveMux11111----------")
}), requests.Logf(func(ctx context.Context, stat *requests.Stat) {
fmt.Println("serveMux222222----------")
}),
)
mux.Pprof()
s := requests.NewServer(context.Background(), mux, requests.URL("http://127.0.0.1:6066"))
s.OnStartup(func(s *http.Server) { fmt.Println("http serve") })
mux.Handle("/handle", h{})
s := requests.NewServer(
context.Background(),
mux,
requests.URL("http://127.0.0.1:6066"),
requests.Logf(func(ctx context.Context, stat *requests.Stat) {
fmt.Println("--------server")
}),
requests.OnStart(func(s *http.Server) {
fmt.Println("OnStart", s.Addr)
}),
)
mux.Handle("/handle", h{}, requests.Logf(func(ctx context.Context, stat *requests.Stat) {
fmt.Println("handle------")
}))
mux.HandleFunc("/handler", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("handler ok"))
})
Expand Down Expand Up @@ -80,10 +96,9 @@ func Test_Use(t *testing.T) {
)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
s := requests.NewServer(ctx, r, requests.URL("http://0.0.0.0:9099"))
s.OnShutdown(func(s *http.Server) {
s := requests.NewServer(ctx, r, requests.URL("http://0.0.0.0:9099"), requests.OnShutdown(func(s *http.Server) {
t.Logf("http: %s shutdown...", s.Addr)
})
}))
r.Pprof()
go s.ListenAndServe()
time.Sleep(1 * time.Second)
Expand All @@ -93,9 +108,7 @@ func Test_Use(t *testing.T) {
//sess.DoRequest(context.Background(), Path("/ping"), Logf(LogS))
//sess.DoRequest(context.Background(), Path("/1234"), Logf(LogS))

select {
case <-ctx.Done():
}
time.Sleep(3 * time.Second)

}

Expand Down
4 changes: 3 additions & 1 deletion transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,9 @@ func (t *Transport) RoundTripper(opts ...Option) http.RoundTripper {
if options.Transport == nil {
options.Transport = t.Transport
}

if options.Log != nil {
options.HttpRoundTripper = append(options.HttpRoundTripper, printRoundTripper(options.Log))
}
for _, tr := range options.HttpRoundTripper {
options.Transport = tr(options.Transport)
}
Expand Down

0 comments on commit 859bf41

Please sign in to comment.