52 lines
1.0 KiB
Go
Raw Normal View History

2024-12-19 15:03:36 +08:00
package gateway
import (
"context"
"fmt"
"net/http/httputil"
"net/url"
"sync/atomic"
"esway/internal/log"
"esway/internal/opt"
"github.com/loveuer/nf"
)
func proxy(ctx context.Context) (nf.HandlerFunc, error) {
if len(opt.Cfg.Endpoints) == 0 {
return nil, fmt.Errorf("gateway: 必须要指定 elasticsearch endpoints")
}
urls := make([]*url.URL, 0)
for _, item := range opt.Cfg.Endpoints {
ins, err := url.Parse(item)
if err != nil {
log.Warn(ctx, "gateway: endpoint invalid, endpoint = %s, err = %s", item, err.Error())
}
urls = append(urls, ins)
}
if len(urls) == 0 {
return nil, fmt.Errorf("gateway: no valid elasticsearch endpoint")
}
svcs := make([]*httputil.ReverseProxy, len(urls))
for idx, item := range urls {
svcs[idx] = httputil.NewSingleHostReverseProxy(item)
}
var (
round int64 = 0
length = int64(len(svcs))
)
return func(c *nf.Ctx) error {
svc := svcs[atomic.SwapInt64(&round, (round+1)%length)]
svc.ServeHTTP(c.Writer, c.Request)
return nil
}, nil
}