package main
import (
"io"
"os"
"fmt"
"time"
"errors"
"context"
"encoding/json"
"github.com/nats-io/nats.go"
)
func run() string {
bucket,err := NewNATSKV("nats://hTQqVPoiVPRsxtFLEpRjfhYC@192.168.222.222", "temporary_7d", 7)
if err != nil {
return resp(10000000, err)
}
body,err2 := io.ReadAll(os.Stdin)
if err2 != nil {
return resp(10000000, err2)
}
resp(0, bucket)
return resp(0, string(body))
}
func main() {
fmt.Print(run())
}
func resp(code, data any) string {
body, err := json.Marshal(map[string]any{
"code": 0,
"data": data,
})
if err != nil {
return `{"code": 10000000, "message": "invalid response"}`
}
return string(body)
}
// natsKV NATS KV�洢ʵ��
type natsKV struct {
conn *nats.Conn
js nats.JetStreamContext
bucket nats.KeyValue
bucketName string
}
// NewNATSKV �����µ�NATS KV�洢
func NewNATSKV(url string, bucketName string, ttlDay int) (*natsKV, error) {
conn, err := nats.Connect(url)
if err != nil {
return nil, err
}
js, err := conn.JetStream()
if err != nil {
return nil, err
}
bucket, err := js.KeyValue(bucketName)
if err != nil && !errors.Is(err, nats.ErrBucketNotFound) {
return nil, err
}
if bucket == nil { // ����bucket
bucketConfig := &nats.KeyValueConfig{
Bucket: bucketName,
Description: "Criui KV store",
History: 10,
Storage: nats.FileStorage,
}
if ttlDay != 0 {
bucketConfig.TTL = time.Hour * 24 * time.Duration(ttlDay)
}
bucket, err = js.CreateKeyValue(bucketConfig)
if err != nil {
return nil, err
}
}
return &natsKV{
conn: conn,
js: js,
bucket: bucket,
bucketName: bucketName,
}, nil
}
// Get ��ȡֵ
func (n *natsKV) Get(ctx context.Context, key string) ([]byte, error) {
entry, err := n.bucket.Get(key)
if err != nil {
if err == nats.ErrKeyNotFound {
return nil, err
}
return nil, err
}
return entry.Value(), nil
}
// Set ����ֵ
func (n *natsKV) Set(ctx context.Context, key string, value []byte) error {
_, err := n.bucket.Put(key, value)
if err != nil {
return err
}
return nil
}
// Delete ɾ����
func (n *natsKV) Delete(ctx context.Context, key string) error {
err := n.bucket.Delete(key)
if err != nil {
if err == nats.ErrKeyNotFound {
return err
}
return err
}
return nil
}
// List �г����м�
func (n *natsKV) List(ctx context.Context, prefix string) ([]string, error) {
keys, err := n.bucket.Keys()
if err != nil {
// ����bucketΪ�գ����ؿ��б������Ǵ���
if errors.Is(err, nats.ErrNoKeysFound) {
return []string{}, nil
}
// ����bucket�����ڣ�Ҳ���ؿ��б�
if errors.Is(err, nats.ErrBucketNotFound) {
return []string{}, nil
}
return nil, err
}
var result []string
for _, key := range keys {
if prefix == "" || len(key) >= len(prefix) && key[:len(prefix)] == prefix {
result = append(result, key)
}
}
return result, nil
}