mirror of
https://github.com/metabarcoding/obitools4.git
synced 2026-04-30 03:50:39 +00:00
🔧 refactor(http): use thread-safe lazy-initialized HTTP client with connection pooling
- Replace global _httpClient variable by a sync.Once-based lazy initialization - Add getHTTPClient() function to safely initialize client with connection pooling settings (MaxIdleConnsPerHost, Max Con ns/Conn per host) - Set connection pool size based on obidefault.ParallelWorkers() This ensures safe concurrent access and better resource management in multi-threaded Lua environments.
This commit is contained in:
+21
-3
@@ -4,15 +4,33 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.metabarcoding.org/obitools/obitools4/obitools4/pkg/obidefault"
|
||||||
lua "github.com/yuin/gopher-lua"
|
lua "github.com/yuin/gopher-lua"
|
||||||
)
|
)
|
||||||
|
|
||||||
const httpClientTimeout = 30 * time.Second
|
const httpClientTimeout = 30 * time.Second
|
||||||
|
|
||||||
var _httpClient = &http.Client{
|
var (
|
||||||
Timeout: httpClientTimeout,
|
_httpClient *http.Client
|
||||||
|
_httpClientOnce sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
|
func getHTTPClient() *http.Client {
|
||||||
|
_httpClientOnce.Do(func() {
|
||||||
|
conns := 2 * obidefault.ParallelWorkers()
|
||||||
|
_httpClient = &http.Client{
|
||||||
|
Transport: &http.Transport{
|
||||||
|
MaxIdleConnsPerHost: conns,
|
||||||
|
MaxConnsPerHost: conns,
|
||||||
|
IdleConnTimeout: 90 * time.Second,
|
||||||
|
},
|
||||||
|
Timeout: httpClientTimeout,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return _httpClient
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterHTTP registers the http module in the Lua state as a global,
|
// RegisterHTTP registers the http module in the Lua state as a global,
|
||||||
@@ -46,7 +64,7 @@ func luaHTTPPost(L *lua.LState) int {
|
|||||||
}
|
}
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
resp, err := _httpClient.Do(req)
|
resp, err := getHTTPClient().Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
L.Push(lua.LNil)
|
L.Push(lua.LNil)
|
||||||
L.Push(lua.LString(err.Error()))
|
L.Push(lua.LString(err.Error()))
|
||||||
|
|||||||
Reference in New Issue
Block a user