chore: move '/internal/pkg' to '/pkg'

This commit is contained in:
Fu Diwei
2025-06-17 15:54:21 +08:00
parent 30840bbba5
commit 205275b52d
611 changed files with 693 additions and 693 deletions

View File

@@ -0,0 +1,67 @@
package serverchan
import (
"context"
"errors"
"fmt"
"log/slog"
"github.com/go-resty/resty/v2"
"github.com/usual2970/certimate/pkg/core"
)
type NotifierProviderConfig struct {
// ServerChan 服务地址。
ServerUrl string `json:"serverUrl"`
}
type NotifierProvider struct {
config *NotifierProviderConfig
logger *slog.Logger
httpClient *resty.Client
}
var _ core.Notifier = (*NotifierProvider)(nil)
func NewNotifierProvider(config *NotifierProviderConfig) (*NotifierProvider, error) {
if config == nil {
return nil, errors.New("the configuration of the notifier provider is nil")
}
client := resty.New()
return &NotifierProvider{
config: config,
logger: slog.Default(),
httpClient: client,
}, nil
}
func (n *NotifierProvider) SetLogger(logger *slog.Logger) {
if logger == nil {
n.logger = slog.New(slog.DiscardHandler)
} else {
n.logger = logger
}
}
func (n *NotifierProvider) Notify(ctx context.Context, subject string, message string) (*core.NotifyResult, error) {
// REF: https://sct.ftqq.com/
req := n.httpClient.R().
SetContext(ctx).
SetHeader("Content-Type", "application/json").
SetHeader("User-Agent", "certimate").
SetBody(map[string]any{
"text": subject,
"desp": message,
})
resp, err := req.Post(n.config.ServerUrl)
if err != nil {
return nil, fmt.Errorf("serverchan api error: failed to send request: %w", err)
} else if resp.IsError() {
return nil, fmt.Errorf("serverchan api error: unexpected status code: %d, resp: %s", resp.StatusCode(), resp.String())
}
return &core.NotifyResult{}, nil
}

View File

@@ -0,0 +1,57 @@
package serverchan_test
import (
"context"
"flag"
"fmt"
"strings"
"testing"
provider "github.com/usual2970/certimate/pkg/core/notifier/providers/serverchan"
)
const (
mockSubject = "test_subject"
mockMessage = "test_message"
)
var fUrl string
func init() {
argsPrefix := "CERTIMATE_NOTIFIER_SERVERCHAN_"
flag.StringVar(&fUrl, argsPrefix+"URL", "", "")
}
/*
Shell command to run this test:
go test -v ./serverchan_test.go -args \
--CERTIMATE_NOTIFIER_SERVERCHAN_URL="https://example.com/your-webhook-url" \
*/
func TestNotify(t *testing.T) {
flag.Parse()
t.Run("Notify", func(t *testing.T) {
t.Log(strings.Join([]string{
"args:",
fmt.Sprintf("URL: %v", fUrl),
}, "\n"))
notifier, err := provider.NewNotifierProvider(&provider.NotifierProviderConfig{
ServerUrl: fUrl,
})
if err != nil {
t.Errorf("err: %+v", err)
return
}
res, err := notifier.Notify(context.Background(), mockSubject, mockMessage)
if err != nil {
t.Errorf("err: %+v", err)
return
}
t.Logf("ok: %v", res)
})
}