Skip to content

Commit

Permalink
Update xhttp
Browse files Browse the repository at this point in the history
  • Loading branch information
onanying committed May 22, 2024
1 parent 70f022f commit f31c942
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
11 changes: 6 additions & 5 deletions src/xhttp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ go get github.com/mix-go/xhttp
| xhttp.WithMiddlewares(middlewares ...Middleware) RequestOption | Set configuration item |
| xhttp.BuildJSON(v interface{}) Body | Generate json string |
| xhttp.BuildQuery(m map[string]string) Body | Generate urlencoded query string |
| xhttp.Shutdown(ctx context.Context) | Do shutdown |

## Debug Log

Expand All @@ -51,10 +52,10 @@ The log object contains the following fields

```go
type Log struct {
Duration time.Duration `json:"duration"`
Request *Request `json:"request"` // The Request.RetryAttempts field records the number of retry attempts
Response *Response `json:"response"` // If request error this field is equal to nil
Error error `json:"error"`
Duration time.Duration `json:"duration"`
Request *Request `json:"request"` // The Request.RetryAttempts field records the number of retry attempts
Response *Response `json:"response"` // If request error this field is equal to nil
Error error `json:"error"`
}
```

Expand Down Expand Up @@ -123,7 +124,7 @@ ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-ch
xhttp.Shutdown()
xhttp.Shutdown(context.Background())
}()
```

Expand Down
20 changes: 16 additions & 4 deletions src/xhttp/shutdownctrl.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package xhttp

import (
"context"
"sync"
"sync/atomic"
)
Expand Down Expand Up @@ -28,11 +29,22 @@ func (sc *ShutdownController) EndRequest() {
sc.waitGroup.Done()
}

func (sc *ShutdownController) InitiateShutdown() {
func (sc *ShutdownController) InitiateShutdown(ctx context.Context) {
atomic.StoreInt32(&sc.shutdownFlag, 1)
sc.waitGroup.Wait()

done := make(chan struct{})
go func() {
sc.waitGroup.Wait()
close(done)
}()
select {
case <-ctx.Done(): // Timeout or ctx canceled, stop waiting.
return
case <-done: // waitGroup has completed
return
}
}

func Shutdown() {
shutdownController.InitiateShutdown()
func Shutdown(ctx context.Context) {
shutdownController.InitiateShutdown(ctx)
}

0 comments on commit f31c942

Please sign in to comment.