feat: 实现 Go 与 JS/TS SDK 连接收发与其余接口
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package nixmsg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Register 静态方法:HTTP 自助注册。url 可为连接地址或注册地址。
|
||||
func Register(ctx context.Context, connectOrRegisterURL, registrationCode string, opt RegisterOptions) (RegisterResult, error) {
|
||||
regURL := connectOrRegisterURL
|
||||
if u, err := RegisterURLFromConnect(connectOrRegisterURL); err == nil {
|
||||
regURL = u
|
||||
}
|
||||
body := map[string]any{
|
||||
"registration_code": registrationCode,
|
||||
"id": opt.ID,
|
||||
"login_password": opt.LoginPassword,
|
||||
"name": opt.Name,
|
||||
"talk_password": opt.TalkPassword,
|
||||
}
|
||||
payload, err := marshalJSON(body)
|
||||
if err != nil {
|
||||
return RegisterResult{}, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, regURL, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return RegisterResult{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return RegisterResult{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
if err != nil {
|
||||
return RegisterResult{}, err
|
||||
}
|
||||
var wrap struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
ID string `json:"id"`
|
||||
LoginPassword string `json:"login_password"`
|
||||
} `json:"data"`
|
||||
Error *struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &wrap); err != nil {
|
||||
return RegisterResult{}, fmt.Errorf("注册响应无效: %w", err)
|
||||
}
|
||||
if !wrap.OK {
|
||||
code, msg := CodeBadRequest, "注册失败"
|
||||
if wrap.Error != nil {
|
||||
code, msg = wrap.Error.Code, wrap.Error.Message
|
||||
}
|
||||
return RegisterResult{}, apiErr(code, msg)
|
||||
}
|
||||
return RegisterResult{ID: wrap.Data.ID, LoginPassword: wrap.Data.LoginPassword}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user