repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/mcp/mcp_api/internal/handler/listtoolshandler.go | app/mcp/mcp_api/internal/handler/listtoolshandler.go | package handler
import (
"net/http"
"beaver/app/mcp/mcp_api/internal/logic"
"beaver/app/mcp/mcp_api/internal/svc"
"github.com/zeromicro/go-zero/rest/httpx"
)
// 获取所有可用工具列表
func ListToolsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := logic.NewListToolsLogic(r.Context(), svcCtx)
resp, err := l.ListTools()
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/mcp/mcp_api/internal/handler/executetoolhandler.go | app/mcp/mcp_api/internal/handler/executetoolhandler.go | package handler
import (
"net/http"
"beaver/app/mcp/mcp_api/internal/logic"
"beaver/app/mcp/mcp_api/internal/svc"
"beaver/app/mcp/mcp_api/internal/types"
"github.com/zeromicro/go-zero/rest/httpx"
)
// 执行MCP工具
func ExecuteToolHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ExecuteToolReq
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := logic.NewExecuteToolLogic(r.Context(), svcCtx)
resp, err := l.ExecuteTool(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/mcp/mcp_api/internal/handler/routes.go | app/mcp/mcp_api/internal/handler/routes.go | // Code generated by goctl. DO NOT EDIT.
package handler
import (
"net/http"
"beaver/app/mcp/mcp_api/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
// 执行MCP工具
Method: http.MethodPost,
Path: "/api/mcp/execute",
Handler: ExecuteToolHandler(serverCtx),
},
{
// 获取所有可用工具列表
Method: http.MethodGet,
Path: "/api/mcp/tools",
Handler: ListToolsHandler(serverCtx),
},
},
)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/mcp/mcp_api/internal/logic/executetoollogic.go | app/mcp/mcp_api/internal/logic/executetoollogic.go | package logic
import (
"context"
"beaver/app/mcp/mcp_api/internal/svc"
"beaver/app/mcp/mcp_api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type ExecuteToolLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 执行MCP工具
func NewExecuteToolLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ExecuteToolLogic {
return &ExecuteToolLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ExecuteToolLogic) ExecuteTool(req *types.ExecuteToolReq) (resp *types.ExecuteToolRes, err error) {
// todo: add your logic here and delete this line
return
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/mcp/mcp_api/internal/logic/listtoolslogic.go | app/mcp/mcp_api/internal/logic/listtoolslogic.go | package logic
import (
"context"
"beaver/app/mcp/mcp_api/internal/svc"
"beaver/app/mcp/mcp_api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type ListToolsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 获取所有可用工具列表
func NewListToolsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListToolsLogic {
return &ListToolsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ListToolsLogic) ListTools() (resp *types.ListToolsRes, err error) {
// todo: add your logic here and delete this line
return
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_models/friend_model.go | app/friend/friend_models/friend_model.go | package friend_models
import (
"beaver/common/models"
"fmt"
"gorm.io/gorm"
)
/**
* @description: 好友表
*/
type FriendModel struct {
models.Model
FriendID string `gorm:"column:friend_id;size:64;uniqueIndex" json:"friendId"`
FriendshipID string `gorm:"size:64;unique;index" json:"friendshipId"` // 好友关系唯一ID (min_user_id_max_user_id)
SendUserID string `gorm:"size:64;index" json:"sendUserId"` // 发起验证方的 UserID
RevUserID string `gorm:"size:64;index" json:"revUserId"` // 接收验证方的 UserID
SendUserNotice string `gorm:"size: 128" json:"sendUserNotice"` //发起验证方备注
RevUserNotice string `gorm:"size: 128" json:"revUserNotice"` //接收验证方备注
Source string `gorm:"size: 32" json:"source"` // 好友关系来源:qrcode/search/group/recommend
IsDeleted bool `gorm:"not null;default:false" json:"isDeleted"` // 标记用户是否删除会话
Version int64 `gorm:"not null;default:0;index"` // 版本号(用于数据同步)
}
// GenerateFriendshipID 生成好友关系唯一ID (使用min_user_id_max_user_id格式)
func GenerateFriendshipID(userA, userB string) string {
if userA < userB {
return fmt.Sprintf("%s_%s", userA, userB)
}
return fmt.Sprintf("%s_%s", userB, userA)
}
// BeforeCreate GORM钩子:在创建前生成FriendshipID
func (f *FriendModel) BeforeCreate(tx *gorm.DB) error {
if f.FriendshipID == "" {
f.FriendshipID = GenerateFriendshipID(f.SendUserID, f.RevUserID)
}
return nil
}
// BeforeUpdate GORM钩子:在更新前确保FriendshipID存在
func (f *FriendModel) BeforeUpdate(tx *gorm.DB) error {
if f.FriendshipID == "" {
f.FriendshipID = GenerateFriendshipID(f.SendUserID, f.RevUserID)
}
return nil
}
// MigrateFriendshipIDs 迁移现有数据,为空的FriendshipID字段生成值
func MigrateFriendshipIDs(db *gorm.DB) error {
var friends []FriendModel
err := db.Where("friendship_id IS NULL OR friendship_id = ''").Find(&friends).Error
if err != nil {
return err
}
for _, friend := range friends {
friendshipID := GenerateFriendshipID(friend.SendUserID, friend.RevUserID)
err = db.Model(&friend).Update("friendship_id", friendshipID).Error
if err != nil {
return err
}
}
return nil
}
func (f *FriendModel) IsFriend(db *gorm.DB, A, B string) bool {
err := db.Take(&f, "((send_user_id = ? and rev_user_id = ?) or (send_user_id = ? and rev_user_id = ?) ) and is_deleted = ?", A, B, B, A, false).Error
return err == nil
}
/**
* @description: 获取用户的备注
* @param {uint} userId
*/
func (f *FriendModel) GetUserNotice(userID string) string {
if userID == f.SendUserID {
// 如果我是发起方
return f.SendUserNotice
}
if userID == f.RevUserID {
// 如果我是接收方
return f.RevUserNotice
}
return ""
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_models/friend_verify_model.go | app/friend/friend_models/friend_verify_model.go | package friend_models
import (
"beaver/common/models"
)
/**
* @description: 好友验证
*/
type FriendVerifyModel struct {
models.Model
VerifyID string `gorm:"column:verify_id;size:64;uniqueIndex" json:"verifyId"`
SendUserID string `gorm:"size:64;index" json:"sendUserId"` // 使用 VARCHAR(64)
RevUserID string `gorm:"size:64;index" json:"revUserId"` // 使用 VARCHAR(64)
SendStatus int8 `json:"sendStatus"` // 发起方状态 0:未处理 1:已通过 2:已拒绝 3: 忽略 4:删除
RevStatus int8 `json:"revStatus"` // 接收方状态 0:未处理 1:已通过 2:已拒绝 3: 忽略 4:删除
Message string `gorm:"size: 128" json:"message"` // 附加消息
Source string `gorm:"size: 32" json:"source"` // 添加好友来源:qrcode/search/group/recommend
Version int64 `gorm:"not null;default:0;index"` // 序列号(用于数据同步)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/friendrpc.go | app/friend/friend_rpc/friendrpc.go | package main
import (
"flag"
"fmt"
"beaver/app/friend/friend_rpc/internal/config"
"beaver/app/friend/friend_rpc/internal/server"
"beaver/app/friend/friend_rpc/internal/svc"
"beaver/app/friend/friend_rpc/types/friend_rpc"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
var configFile = flag.String("f", "etc/friendrpc.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
friend_rpc.RegisterFriendServer(grpcServer, server.NewFriendServer(ctx))
if c.Mode == service.DevMode || c.Mode == service.TestMode {
reflection.Register(grpcServer)
}
})
defer s.Stop()
fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
s.Start()
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/types/friend_rpc/friend_rpc_grpc.pb.go | app/friend/friend_rpc/types/friend_rpc/friend_rpc_grpc.pb.go | // Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v4.25.3
// source: friend_rpc.proto
package friend_rpc
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
Friend_GetFriendIds_FullMethodName = "/friend_rpc.friend/GetFriendIds"
Friend_GetFriendVersions_FullMethodName = "/friend_rpc.friend/GetFriendVersions"
Friend_GetFriendVerifyVersions_FullMethodName = "/friend_rpc.friend/GetFriendVerifyVersions"
Friend_GetFriendsListByIds_FullMethodName = "/friend_rpc.friend/GetFriendsListByIds"
Friend_GetFriendVerifiesListByIds_FullMethodName = "/friend_rpc.friend/GetFriendVerifiesListByIds"
Friend_GetFriendDetail_FullMethodName = "/friend_rpc.friend/GetFriendDetail"
)
// FriendClient is the client API for Friend service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type FriendClient interface {
GetFriendIds(ctx context.Context, in *GetFriendIdsRequest, opts ...grpc.CallOption) (*GetFriendIdsResponse, error)
GetFriendVersions(ctx context.Context, in *GetFriendVersionsReq, opts ...grpc.CallOption) (*GetFriendVersionsRes, error)
GetFriendVerifyVersions(ctx context.Context, in *GetFriendVerifyVersionsReq, opts ...grpc.CallOption) (*GetFriendVerifyVersionsRes, error)
GetFriendsListByIds(ctx context.Context, in *GetFriendsListByIdsReq, opts ...grpc.CallOption) (*GetFriendsListByIdsRes, error)
GetFriendVerifiesListByIds(ctx context.Context, in *GetFriendVerifiesListByIdsReq, opts ...grpc.CallOption) (*GetFriendVerifiesListByIdsRes, error)
GetFriendDetail(ctx context.Context, in *GetFriendDetailReq, opts ...grpc.CallOption) (*GetFriendDetailRes, error)
}
type friendClient struct {
cc grpc.ClientConnInterface
}
func NewFriendClient(cc grpc.ClientConnInterface) FriendClient {
return &friendClient{cc}
}
func (c *friendClient) GetFriendIds(ctx context.Context, in *GetFriendIdsRequest, opts ...grpc.CallOption) (*GetFriendIdsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetFriendIdsResponse)
err := c.cc.Invoke(ctx, Friend_GetFriendIds_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *friendClient) GetFriendVersions(ctx context.Context, in *GetFriendVersionsReq, opts ...grpc.CallOption) (*GetFriendVersionsRes, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetFriendVersionsRes)
err := c.cc.Invoke(ctx, Friend_GetFriendVersions_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *friendClient) GetFriendVerifyVersions(ctx context.Context, in *GetFriendVerifyVersionsReq, opts ...grpc.CallOption) (*GetFriendVerifyVersionsRes, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetFriendVerifyVersionsRes)
err := c.cc.Invoke(ctx, Friend_GetFriendVerifyVersions_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *friendClient) GetFriendsListByIds(ctx context.Context, in *GetFriendsListByIdsReq, opts ...grpc.CallOption) (*GetFriendsListByIdsRes, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetFriendsListByIdsRes)
err := c.cc.Invoke(ctx, Friend_GetFriendsListByIds_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *friendClient) GetFriendVerifiesListByIds(ctx context.Context, in *GetFriendVerifiesListByIdsReq, opts ...grpc.CallOption) (*GetFriendVerifiesListByIdsRes, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetFriendVerifiesListByIdsRes)
err := c.cc.Invoke(ctx, Friend_GetFriendVerifiesListByIds_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *friendClient) GetFriendDetail(ctx context.Context, in *GetFriendDetailReq, opts ...grpc.CallOption) (*GetFriendDetailRes, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetFriendDetailRes)
err := c.cc.Invoke(ctx, Friend_GetFriendDetail_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// FriendServer is the server API for Friend service.
// All implementations must embed UnimplementedFriendServer
// for forward compatibility.
type FriendServer interface {
GetFriendIds(context.Context, *GetFriendIdsRequest) (*GetFriendIdsResponse, error)
GetFriendVersions(context.Context, *GetFriendVersionsReq) (*GetFriendVersionsRes, error)
GetFriendVerifyVersions(context.Context, *GetFriendVerifyVersionsReq) (*GetFriendVerifyVersionsRes, error)
GetFriendsListByIds(context.Context, *GetFriendsListByIdsReq) (*GetFriendsListByIdsRes, error)
GetFriendVerifiesListByIds(context.Context, *GetFriendVerifiesListByIdsReq) (*GetFriendVerifiesListByIdsRes, error)
GetFriendDetail(context.Context, *GetFriendDetailReq) (*GetFriendDetailRes, error)
mustEmbedUnimplementedFriendServer()
}
// UnimplementedFriendServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedFriendServer struct{}
func (UnimplementedFriendServer) GetFriendIds(context.Context, *GetFriendIdsRequest) (*GetFriendIdsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetFriendIds not implemented")
}
func (UnimplementedFriendServer) GetFriendVersions(context.Context, *GetFriendVersionsReq) (*GetFriendVersionsRes, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetFriendVersions not implemented")
}
func (UnimplementedFriendServer) GetFriendVerifyVersions(context.Context, *GetFriendVerifyVersionsReq) (*GetFriendVerifyVersionsRes, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetFriendVerifyVersions not implemented")
}
func (UnimplementedFriendServer) GetFriendsListByIds(context.Context, *GetFriendsListByIdsReq) (*GetFriendsListByIdsRes, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetFriendsListByIds not implemented")
}
func (UnimplementedFriendServer) GetFriendVerifiesListByIds(context.Context, *GetFriendVerifiesListByIdsReq) (*GetFriendVerifiesListByIdsRes, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetFriendVerifiesListByIds not implemented")
}
func (UnimplementedFriendServer) GetFriendDetail(context.Context, *GetFriendDetailReq) (*GetFriendDetailRes, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetFriendDetail not implemented")
}
func (UnimplementedFriendServer) mustEmbedUnimplementedFriendServer() {}
func (UnimplementedFriendServer) testEmbeddedByValue() {}
// UnsafeFriendServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to FriendServer will
// result in compilation errors.
type UnsafeFriendServer interface {
mustEmbedUnimplementedFriendServer()
}
func RegisterFriendServer(s grpc.ServiceRegistrar, srv FriendServer) {
// If the following call pancis, it indicates UnimplementedFriendServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&Friend_ServiceDesc, srv)
}
func _Friend_GetFriendIds_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetFriendIdsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FriendServer).GetFriendIds(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Friend_GetFriendIds_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FriendServer).GetFriendIds(ctx, req.(*GetFriendIdsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Friend_GetFriendVersions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetFriendVersionsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FriendServer).GetFriendVersions(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Friend_GetFriendVersions_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FriendServer).GetFriendVersions(ctx, req.(*GetFriendVersionsReq))
}
return interceptor(ctx, in, info, handler)
}
func _Friend_GetFriendVerifyVersions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetFriendVerifyVersionsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FriendServer).GetFriendVerifyVersions(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Friend_GetFriendVerifyVersions_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FriendServer).GetFriendVerifyVersions(ctx, req.(*GetFriendVerifyVersionsReq))
}
return interceptor(ctx, in, info, handler)
}
func _Friend_GetFriendsListByIds_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetFriendsListByIdsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FriendServer).GetFriendsListByIds(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Friend_GetFriendsListByIds_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FriendServer).GetFriendsListByIds(ctx, req.(*GetFriendsListByIdsReq))
}
return interceptor(ctx, in, info, handler)
}
func _Friend_GetFriendVerifiesListByIds_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetFriendVerifiesListByIdsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FriendServer).GetFriendVerifiesListByIds(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Friend_GetFriendVerifiesListByIds_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FriendServer).GetFriendVerifiesListByIds(ctx, req.(*GetFriendVerifiesListByIdsReq))
}
return interceptor(ctx, in, info, handler)
}
func _Friend_GetFriendDetail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetFriendDetailReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FriendServer).GetFriendDetail(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Friend_GetFriendDetail_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FriendServer).GetFriendDetail(ctx, req.(*GetFriendDetailReq))
}
return interceptor(ctx, in, info, handler)
}
// Friend_ServiceDesc is the grpc.ServiceDesc for Friend service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Friend_ServiceDesc = grpc.ServiceDesc{
ServiceName: "friend_rpc.friend",
HandlerType: (*FriendServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetFriendIds",
Handler: _Friend_GetFriendIds_Handler,
},
{
MethodName: "GetFriendVersions",
Handler: _Friend_GetFriendVersions_Handler,
},
{
MethodName: "GetFriendVerifyVersions",
Handler: _Friend_GetFriendVerifyVersions_Handler,
},
{
MethodName: "GetFriendsListByIds",
Handler: _Friend_GetFriendsListByIds_Handler,
},
{
MethodName: "GetFriendVerifiesListByIds",
Handler: _Friend_GetFriendVerifiesListByIds_Handler,
},
{
MethodName: "GetFriendDetail",
Handler: _Friend_GetFriendDetail_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "friend_rpc.proto",
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/types/friend_rpc/friend_rpc.pb.go | app/friend/friend_rpc/types/friend_rpc/friend_rpc.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.7
// protoc v4.25.3
// source: friend_rpc.proto
package friend_rpc
import (
reflect "reflect"
sync "sync"
unsafe "unsafe"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type GetFriendIdsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
UserID string `protobuf:"bytes,1,opt,name=UserID,proto3" json:"UserID,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendIdsRequest) Reset() {
*x = GetFriendIdsRequest{}
mi := &file_friend_rpc_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendIdsRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendIdsRequest) ProtoMessage() {}
func (x *GetFriendIdsRequest) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendIdsRequest.ProtoReflect.Descriptor instead.
func (*GetFriendIdsRequest) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{0}
}
func (x *GetFriendIdsRequest) GetUserID() string {
if x != nil {
return x.UserID
}
return ""
}
type GetFriendIdsResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
FriendIds []string `protobuf:"bytes,1,rep,name=friend_ids,json=friendIds,proto3" json:"friend_ids,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendIdsResponse) Reset() {
*x = GetFriendIdsResponse{}
mi := &file_friend_rpc_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendIdsResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendIdsResponse) ProtoMessage() {}
func (x *GetFriendIdsResponse) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendIdsResponse.ProtoReflect.Descriptor instead.
func (*GetFriendIdsResponse) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{1}
}
func (x *GetFriendIdsResponse) GetFriendIds() []string {
if x != nil {
return x.FriendIds
}
return nil
}
// 通过ID获取好友列表
type GetFriendsListByIdsReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
Ids []string `protobuf:"bytes,1,rep,name=ids,proto3" json:"ids,omitempty"` // 唯一ID列表
Since int64 `protobuf:"varint,2,opt,name=since,proto3" json:"since,omitempty"` // 时间戳,从此时间戳之后获取变更的记录
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendsListByIdsReq) Reset() {
*x = GetFriendsListByIdsReq{}
mi := &file_friend_rpc_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendsListByIdsReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendsListByIdsReq) ProtoMessage() {}
func (x *GetFriendsListByIdsReq) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendsListByIdsReq.ProtoReflect.Descriptor instead.
func (*GetFriendsListByIdsReq) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{2}
}
func (x *GetFriendsListByIdsReq) GetIds() []string {
if x != nil {
return x.Ids
}
return nil
}
func (x *GetFriendsListByIdsReq) GetSince() int64 {
if x != nil {
return x.Since
}
return 0
}
type FriendListById struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` // 唯一ID
SendUserId string `protobuf:"bytes,2,opt,name=sendUserId,proto3" json:"sendUserId,omitempty"` // 发送者用户ID
RevUserId string `protobuf:"bytes,3,opt,name=revUserId,proto3" json:"revUserId,omitempty"` // 接收者用户ID
SendUserNotice string `protobuf:"bytes,4,opt,name=sendUserNotice,proto3" json:"sendUserNotice,omitempty"` // 发送者备注
RevUserNotice string `protobuf:"bytes,5,opt,name=revUserNotice,proto3" json:"revUserNotice,omitempty"` // 接收者备注
Source string `protobuf:"bytes,6,opt,name=source,proto3" json:"source,omitempty"` // 添加好友来源
IsDeleted bool `protobuf:"varint,7,opt,name=isDeleted,proto3" json:"isDeleted,omitempty"` // 是否已删除
Version int64 `protobuf:"varint,8,opt,name=version,proto3" json:"version,omitempty"` // 版本号
CreatedAt int64 `protobuf:"varint,9,opt,name=createdAt,proto3" json:"createdAt,omitempty"` // 创建时间
UpdatedAt int64 `protobuf:"varint,10,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` // 更新时间
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FriendListById) Reset() {
*x = FriendListById{}
mi := &file_friend_rpc_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FriendListById) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FriendListById) ProtoMessage() {}
func (x *FriendListById) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use FriendListById.ProtoReflect.Descriptor instead.
func (*FriendListById) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{3}
}
func (x *FriendListById) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *FriendListById) GetSendUserId() string {
if x != nil {
return x.SendUserId
}
return ""
}
func (x *FriendListById) GetRevUserId() string {
if x != nil {
return x.RevUserId
}
return ""
}
func (x *FriendListById) GetSendUserNotice() string {
if x != nil {
return x.SendUserNotice
}
return ""
}
func (x *FriendListById) GetRevUserNotice() string {
if x != nil {
return x.RevUserNotice
}
return ""
}
func (x *FriendListById) GetSource() string {
if x != nil {
return x.Source
}
return ""
}
func (x *FriendListById) GetIsDeleted() bool {
if x != nil {
return x.IsDeleted
}
return false
}
func (x *FriendListById) GetVersion() int64 {
if x != nil {
return x.Version
}
return 0
}
func (x *FriendListById) GetCreateAt() int64 {
if x != nil {
return x.CreatedAt
}
return 0
}
func (x *FriendListById) GetUpdateAt() int64 {
if x != nil {
return x.UpdatedAt
}
return 0
}
type GetFriendsListByIdsRes struct {
state protoimpl.MessageState `protogen:"open.v1"`
Friends []*FriendListById `protobuf:"bytes,1,rep,name=friends,proto3" json:"friends,omitempty"` // 好友列表
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendsListByIdsRes) Reset() {
*x = GetFriendsListByIdsRes{}
mi := &file_friend_rpc_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendsListByIdsRes) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendsListByIdsRes) ProtoMessage() {}
func (x *GetFriendsListByIdsRes) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendsListByIdsRes.ProtoReflect.Descriptor instead.
func (*GetFriendsListByIdsRes) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{4}
}
func (x *GetFriendsListByIdsRes) GetFriends() []*FriendListById {
if x != nil {
return x.Friends
}
return nil
}
// 获取用户好友版本信息
type GetFriendVersionsReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
UserId string `protobuf:"bytes,1,opt,name=userId,proto3" json:"userId,omitempty"` // 用户ID
Since int64 `protobuf:"varint,2,opt,name=since,proto3" json:"since,omitempty"` // 从这个版本号之后开始同步
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendVersionsReq) Reset() {
*x = GetFriendVersionsReq{}
mi := &file_friend_rpc_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendVersionsReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendVersionsReq) ProtoMessage() {}
func (x *GetFriendVersionsReq) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendVersionsReq.ProtoReflect.Descriptor instead.
func (*GetFriendVersionsReq) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{5}
}
func (x *GetFriendVersionsReq) GetUserId() string {
if x != nil {
return x.UserId
}
return ""
}
func (x *GetFriendVersionsReq) GetSince() int64 {
if x != nil {
return x.Since
}
return 0
}
type GetFriendVersionsRes struct {
state protoimpl.MessageState `protogen:"open.v1"`
FriendVersions []*GetFriendVersionsRes_FriendVersion `protobuf:"bytes,1,rep,name=friendVersions,proto3" json:"friendVersions,omitempty"` // 好友版本列表
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendVersionsRes) Reset() {
*x = GetFriendVersionsRes{}
mi := &file_friend_rpc_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendVersionsRes) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendVersionsRes) ProtoMessage() {}
func (x *GetFriendVersionsRes) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendVersionsRes.ProtoReflect.Descriptor instead.
func (*GetFriendVersionsRes) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{6}
}
func (x *GetFriendVersionsRes) GetFriendVersions() []*GetFriendVersionsRes_FriendVersion {
if x != nil {
return x.FriendVersions
}
return nil
}
// 获取用户好友验证版本信息
type GetFriendVerifyVersionsReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
UserId string `protobuf:"bytes,1,opt,name=userId,proto3" json:"userId,omitempty"` // 用户ID
Since int64 `protobuf:"varint,2,opt,name=since,proto3" json:"since,omitempty"` // 从这个版本号之后开始同步
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendVerifyVersionsReq) Reset() {
*x = GetFriendVerifyVersionsReq{}
mi := &file_friend_rpc_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendVerifyVersionsReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendVerifyVersionsReq) ProtoMessage() {}
func (x *GetFriendVerifyVersionsReq) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendVerifyVersionsReq.ProtoReflect.Descriptor instead.
func (*GetFriendVerifyVersionsReq) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{7}
}
func (x *GetFriendVerifyVersionsReq) GetUserId() string {
if x != nil {
return x.UserId
}
return ""
}
func (x *GetFriendVerifyVersionsReq) GetSince() int64 {
if x != nil {
return x.Since
}
return 0
}
type GetFriendVerifyVersionsRes struct {
state protoimpl.MessageState `protogen:"open.v1"`
FriendVerifyVersions []*GetFriendVerifyVersionsRes_FriendVerifyVersion `protobuf:"bytes,1,rep,name=friendVerifyVersions,proto3" json:"friendVerifyVersions,omitempty"` // 好友验证版本列表
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendVerifyVersionsRes) Reset() {
*x = GetFriendVerifyVersionsRes{}
mi := &file_friend_rpc_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendVerifyVersionsRes) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendVerifyVersionsRes) ProtoMessage() {}
func (x *GetFriendVerifyVersionsRes) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendVerifyVersionsRes.ProtoReflect.Descriptor instead.
func (*GetFriendVerifyVersionsRes) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{8}
}
func (x *GetFriendVerifyVersionsRes) GetFriendVerifyVersions() []*GetFriendVerifyVersionsRes_FriendVerifyVersion {
if x != nil {
return x.FriendVerifyVersions
}
return nil
}
// 通过ID获取好友验证列表
type GetFriendVerifiesListByIdsReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
VerifyIds []string `protobuf:"bytes,1,rep,name=verify_ids,json=verifyIds,proto3" json:"verify_ids,omitempty"` // 验证记录ID列表
Since int64 `protobuf:"varint,2,opt,name=since,proto3" json:"since,omitempty"` // 时间戳,从此时间戳之后获取变更的记录
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendVerifiesListByIdsReq) Reset() {
*x = GetFriendVerifiesListByIdsReq{}
mi := &file_friend_rpc_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendVerifiesListByIdsReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendVerifiesListByIdsReq) ProtoMessage() {}
func (x *GetFriendVerifiesListByIdsReq) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendVerifiesListByIdsReq.ProtoReflect.Descriptor instead.
func (*GetFriendVerifiesListByIdsReq) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{9}
}
func (x *GetFriendVerifiesListByIdsReq) GetVerifyIds() []string {
if x != nil {
return x.VerifyIds
}
return nil
}
func (x *GetFriendVerifiesListByIdsReq) GetSince() int64 {
if x != nil {
return x.Since
}
return 0
}
type FriendVerifyListById struct {
state protoimpl.MessageState `protogen:"open.v1"`
VerifyId string `protobuf:"bytes,1,opt,name=verify_id,json=verifyId,proto3" json:"verify_id,omitempty"` // 验证记录ID
SendUserId string `protobuf:"bytes,2,opt,name=sendUserId,proto3" json:"sendUserId,omitempty"` // 发送者用户ID
RevUserId string `protobuf:"bytes,3,opt,name=revUserId,proto3" json:"revUserId,omitempty"` // 接收者用户ID
SendStatus int32 `protobuf:"varint,4,opt,name=sendStatus,proto3" json:"sendStatus,omitempty"` // 发送方状态:0(未处理)/1(已通过)/2(已拒绝)/3(忽略)/4(删除)
RevStatus int32 `protobuf:"varint,5,opt,name=revStatus,proto3" json:"revStatus,omitempty"` // 接收方状态:0(未处理)/1(已通过)/2(已拒绝)/3(忽略)/4(删除)
Message string `protobuf:"bytes,6,opt,name=message,proto3" json:"message,omitempty"` // 附加消息
Source string `protobuf:"bytes,7,opt,name=source,proto3" json:"source,omitempty"` // 添加好友来源
Version int64 `protobuf:"varint,8,opt,name=version,proto3" json:"version,omitempty"` // 版本号
CreatedAt int64 `protobuf:"varint,9,opt,name=createdAt,proto3" json:"createdAt,omitempty"` // 创建时间
UpdatedAt int64 `protobuf:"varint,10,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` // 更新时间
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FriendVerifyListById) Reset() {
*x = FriendVerifyListById{}
mi := &file_friend_rpc_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FriendVerifyListById) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FriendVerifyListById) ProtoMessage() {}
func (x *FriendVerifyListById) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use FriendVerifyListById.ProtoReflect.Descriptor instead.
func (*FriendVerifyListById) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{10}
}
func (x *FriendVerifyListById) GetVerifyId() string {
if x != nil {
return x.VerifyId
}
return ""
}
func (x *FriendVerifyListById) GetSendUserId() string {
if x != nil {
return x.SendUserId
}
return ""
}
func (x *FriendVerifyListById) GetRevUserId() string {
if x != nil {
return x.RevUserId
}
return ""
}
func (x *FriendVerifyListById) GetSendStatus() int32 {
if x != nil {
return x.SendStatus
}
return 0
}
func (x *FriendVerifyListById) GetRevStatus() int32 {
if x != nil {
return x.RevStatus
}
return 0
}
func (x *FriendVerifyListById) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
func (x *FriendVerifyListById) GetSource() string {
if x != nil {
return x.Source
}
return ""
}
func (x *FriendVerifyListById) GetVersion() int64 {
if x != nil {
return x.Version
}
return 0
}
func (x *FriendVerifyListById) GetCreateAt() int64 {
if x != nil {
return x.CreatedAt
}
return 0
}
func (x *FriendVerifyListById) GetUpdateAt() int64 {
if x != nil {
return x.UpdatedAt
}
return 0
}
type GetFriendVerifiesListByIdsRes struct {
state protoimpl.MessageState `protogen:"open.v1"`
FriendVerifies []*FriendVerifyListById `protobuf:"bytes,1,rep,name=friendVerifies,proto3" json:"friendVerifies,omitempty"` // 好友验证列表
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendVerifiesListByIdsRes) Reset() {
*x = GetFriendVerifiesListByIdsRes{}
mi := &file_friend_rpc_proto_msgTypes[11]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendVerifiesListByIdsRes) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendVerifiesListByIdsRes) ProtoMessage() {}
func (x *GetFriendVerifiesListByIdsRes) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[11]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendVerifiesListByIdsRes.ProtoReflect.Descriptor instead.
func (*GetFriendVerifiesListByIdsRes) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{11}
}
func (x *GetFriendVerifiesListByIdsRes) GetFriendVerifies() []*FriendVerifyListById {
if x != nil {
return x.FriendVerifies
}
return nil
}
// 获取好友详细信息(包含用户基础信息和好友关系信息)
type GetFriendDetailReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
UserId string `protobuf:"bytes,1,opt,name=userId,proto3" json:"userId,omitempty"` // 当前用户ID
FriendIds []string `protobuf:"bytes,2,rep,name=friendIds,proto3" json:"friendIds,omitempty"` // 好友ID列表
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendDetailReq) Reset() {
*x = GetFriendDetailReq{}
mi := &file_friend_rpc_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendDetailReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendDetailReq) ProtoMessage() {}
func (x *GetFriendDetailReq) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendDetailReq.ProtoReflect.Descriptor instead.
func (*GetFriendDetailReq) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{12}
}
func (x *GetFriendDetailReq) GetUserId() string {
if x != nil {
return x.UserId
}
return ""
}
func (x *GetFriendDetailReq) GetFriendIds() []string {
if x != nil {
return x.FriendIds
}
return nil
}
type FriendDetailItem struct {
state protoimpl.MessageState `protogen:"open.v1"`
UserId string `protobuf:"bytes,1,opt,name=userId,proto3" json:"userId,omitempty"` // 用户ID
NickName string `protobuf:"bytes,2,opt,name=nickName,proto3" json:"nickName,omitempty"` // 用户昵称
Avatar string `protobuf:"bytes,3,opt,name=avatar,proto3" json:"avatar,omitempty"` // 用户头像
Notice string `protobuf:"bytes,4,opt,name=notice,proto3" json:"notice,omitempty"` // 好友备注
FriendAt int64 `protobuf:"varint,5,opt,name=friendAt,proto3" json:"friendAt,omitempty"` // 成为好友的时间
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FriendDetailItem) Reset() {
*x = FriendDetailItem{}
mi := &file_friend_rpc_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FriendDetailItem) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FriendDetailItem) ProtoMessage() {}
func (x *FriendDetailItem) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use FriendDetailItem.ProtoReflect.Descriptor instead.
func (*FriendDetailItem) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{13}
}
func (x *FriendDetailItem) GetUserId() string {
if x != nil {
return x.UserId
}
return ""
}
func (x *FriendDetailItem) GetNickName() string {
if x != nil {
return x.NickName
}
return ""
}
func (x *FriendDetailItem) GetAvatar() string {
if x != nil {
return x.Avatar
}
return ""
}
func (x *FriendDetailItem) GetNotice() string {
if x != nil {
return x.Notice
}
return ""
}
func (x *FriendDetailItem) GetFriendAt() int64 {
if x != nil {
return x.FriendAt
}
return 0
}
type GetFriendDetailRes struct {
state protoimpl.MessageState `protogen:"open.v1"`
Friends []*FriendDetailItem `protobuf:"bytes,1,rep,name=friends,proto3" json:"friends,omitempty"` // 好友详细信息列表
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendDetailRes) Reset() {
*x = GetFriendDetailRes{}
mi := &file_friend_rpc_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendDetailRes) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendDetailRes) ProtoMessage() {}
func (x *GetFriendDetailRes) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendDetailRes.ProtoReflect.Descriptor instead.
func (*GetFriendDetailRes) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{14}
}
func (x *GetFriendDetailRes) GetFriends() []*FriendDetailItem {
if x != nil {
return x.Friends
}
return nil
}
type GetFriendVersionsRes_FriendVersion struct {
state protoimpl.MessageState `protogen:"open.v1"`
FriendId string `protobuf:"bytes,1,opt,name=friendId,proto3" json:"friendId,omitempty"`
Version int64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` // 版本号
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendVersionsRes_FriendVersion) Reset() {
*x = GetFriendVersionsRes_FriendVersion{}
mi := &file_friend_rpc_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendVersionsRes_FriendVersion) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendVersionsRes_FriendVersion) ProtoMessage() {}
func (x *GetFriendVersionsRes_FriendVersion) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[15]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendVersionsRes_FriendVersion.ProtoReflect.Descriptor instead.
func (*GetFriendVersionsRes_FriendVersion) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{6, 0}
}
func (x *GetFriendVersionsRes_FriendVersion) GetFriendId() string {
if x != nil {
return x.FriendId
}
return ""
}
func (x *GetFriendVersionsRes_FriendVersion) GetVersion() int64 {
if x != nil {
return x.Version
}
return 0
}
type GetFriendVerifyVersionsRes_FriendVerifyVersion struct {
state protoimpl.MessageState `protogen:"open.v1"`
VerifyId string `protobuf:"bytes,1,opt,name=verify_id,json=verifyId,proto3" json:"verify_id,omitempty"` // 验证记录ID
Version int64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` // 版本号
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetFriendVerifyVersionsRes_FriendVerifyVersion) Reset() {
*x = GetFriendVerifyVersionsRes_FriendVerifyVersion{}
mi := &file_friend_rpc_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetFriendVerifyVersionsRes_FriendVerifyVersion) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetFriendVerifyVersionsRes_FriendVerifyVersion) ProtoMessage() {}
func (x *GetFriendVerifyVersionsRes_FriendVerifyVersion) ProtoReflect() protoreflect.Message {
mi := &file_friend_rpc_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetFriendVerifyVersionsRes_FriendVerifyVersion.ProtoReflect.Descriptor instead.
func (*GetFriendVerifyVersionsRes_FriendVerifyVersion) Descriptor() ([]byte, []int) {
return file_friend_rpc_proto_rawDescGZIP(), []int{8, 0}
}
func (x *GetFriendVerifyVersionsRes_FriendVerifyVersion) GetVerifyId() string {
if x != nil {
return x.VerifyId
}
return ""
}
func (x *GetFriendVerifyVersionsRes_FriendVerifyVersion) GetVersion() int64 {
if x != nil {
return x.Version
}
return 0
}
var File_friend_rpc_proto protoreflect.FileDescriptor
const file_friend_rpc_proto_rawDesc = "" +
"\n" +
"\x10friend_rpc.proto\x12\n" +
"friend_rpc\"-\n" +
"\x13GetFriendIdsRequest\x12\x16\n" +
"\x06UserID\x18\x01 \x01(\tR\x06UserID\"5\n" +
"\x14GetFriendIdsResponse\x12\x1d\n" +
"\n" +
"friend_ids\x18\x01 \x03(\tR\tfriendIds\"@\n" +
"\x16GetFriendsListByIdsReq\x12\x10\n" +
"\x03ids\x18\x01 \x03(\tR\x03ids\x12\x14\n" +
"\x05since\x18\x02 \x01(\x03R\x05since\"\xb4\x02\n" +
"\x0eFriendListById\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\x12\x1e\n" +
"\n" +
"sendUserId\x18\x02 \x01(\tR\n" +
"sendUserId\x12\x1c\n" +
"\trevUserId\x18\x03 \x01(\tR\trevUserId\x12&\n" +
"\x0esendUserNotice\x18\x04 \x01(\tR\x0esendUserNotice\x12$\n" +
"\rrevUserNotice\x18\x05 \x01(\tR\rrevUserNotice\x12\x16\n" +
"\x06source\x18\x06 \x01(\tR\x06source\x12\x1c\n" +
"\tisDeleted\x18\a \x01(\bR\tisDeleted\x12\x18\n" +
"\aversion\x18\b \x01(\x03R\aversion\x12\x1a\n" +
"\bcreateAt\x18\t \x01(\x03R\bcreateAt\x12\x1a\n" +
"\bupdateAt\x18\n" +
" \x01(\x03R\bupdateAt\"N\n" +
"\x16GetFriendsListByIdsRes\x124\n" +
"\afriends\x18\x01 \x03(\v2\x1a.friend_rpc.FriendListByIdR\afriends\"D\n" +
"\x14GetFriendVersionsReq\x12\x16\n" +
"\x06userId\x18\x01 \x01(\tR\x06userId\x12\x14\n" +
"\x05since\x18\x02 \x01(\x03R\x05since\"\xb5\x01\n" +
"\x14GetFriendVersionsRes\x12V\n" +
"\x0efriendVersions\x18\x01 \x03(\v2..friend_rpc.GetFriendVersionsRes.FriendVersionR\x0efriendVersions\x1aE\n" +
"\rFriendVersion\x12\x1a\n" +
"\bfriendId\x18\x01 \x01(\tR\bfriendId\x12\x18\n" +
"\aversion\x18\x02 \x01(\x03R\aversion\"J\n" +
"\x1aGetFriendVerifyVersionsReq\x12\x16\n" +
"\x06userId\x18\x01 \x01(\tR\x06userId\x12\x14\n" +
"\x05since\x18\x02 \x01(\x03R\x05since\"\xda\x01\n" +
"\x1aGetFriendVerifyVersionsRes\x12n\n" +
"\x14friendVerifyVersions\x18\x01 \x03(\v2:.friend_rpc.GetFriendVerifyVersionsRes.FriendVerifyVersionR\x14friendVerifyVersions\x1aL\n" +
"\x13FriendVerifyVersion\x12\x1b\n" +
"\tverify_id\x18\x01 \x01(\tR\bverifyId\x12\x18\n" +
"\aversion\x18\x02 \x01(\x03R\aversion\"T\n" +
"\x1dGetFriendVerifiesListByIdsReq\x12\x1d\n" +
"\n" +
"verify_ids\x18\x01 \x03(\tR\tverifyIds\x12\x14\n" +
"\x05since\x18\x02 \x01(\x03R\x05since\"\xb3\x02\n" +
"\x14FriendVerifyListById\x12\x1b\n" +
"\tverify_id\x18\x01 \x01(\tR\bverifyId\x12\x1e\n" +
"\n" +
"sendUserId\x18\x02 \x01(\tR\n" +
"sendUserId\x12\x1c\n" +
"\trevUserId\x18\x03 \x01(\tR\trevUserId\x12\x1e\n" +
"\n" +
"sendStatus\x18\x04 \x01(\x05R\n" +
"sendStatus\x12\x1c\n" +
"\trevStatus\x18\x05 \x01(\x05R\trevStatus\x12\x18\n" +
"\amessage\x18\x06 \x01(\tR\amessage\x12\x16\n" +
"\x06source\x18\a \x01(\tR\x06source\x12\x18\n" +
"\aversion\x18\b \x01(\x03R\aversion\x12\x1a\n" +
"\bcreateAt\x18\t \x01(\x03R\bcreateAt\x12\x1a\n" +
"\bupdateAt\x18\n" +
" \x01(\x03R\bupdateAt\"i\n" +
"\x1dGetFriendVerifiesListByIdsRes\x12H\n" +
"\x0efriendVerifies\x18\x01 \x03(\v2 .friend_rpc.FriendVerifyListByIdR\x0efriendVerifies\"J\n" +
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | true |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/internal/svc/servicecontext.go | app/friend/friend_rpc/internal/svc/servicecontext.go | package svc
import (
"beaver/app/friend/friend_rpc/internal/config"
"beaver/app/user/user_rpc/types/user_rpc"
"beaver/app/user/user_rpc/user"
"beaver/common/zrpc_interceptor"
"beaver/core"
"github.com/zeromicro/go-zero/zrpc"
"gorm.io/gorm"
)
type ServiceContext struct {
Config config.Config
UserRpc user_rpc.UserClient
DB *gorm.DB
}
func NewServiceContext(c config.Config) *ServiceContext {
mysqlDb := core.InitGorm(c.Mysql.DataSource)
return &ServiceContext{
Config: c,
UserRpc: user.NewUser(zrpc.MustNewClient(c.UserRpc, zrpc.WithUnaryClientInterceptor(zrpc_interceptor.ClientInfoInterceptor))),
DB: mysqlDb,
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/internal/server/friendserver.go | app/friend/friend_rpc/internal/server/friendserver.go | // Code generated by goctl. DO NOT EDIT.
// goctl 1.8.5
// Source: friend_rpc.proto
package server
import (
"context"
"beaver/app/friend/friend_rpc/internal/logic"
"beaver/app/friend/friend_rpc/internal/svc"
"beaver/app/friend/friend_rpc/types/friend_rpc"
)
type FriendServer struct {
svcCtx *svc.ServiceContext
friend_rpc.UnimplementedFriendServer
}
func NewFriendServer(svcCtx *svc.ServiceContext) *FriendServer {
return &FriendServer{
svcCtx: svcCtx,
}
}
func (s *FriendServer) GetFriendIds(ctx context.Context, in *friend_rpc.GetFriendIdsRequest) (*friend_rpc.GetFriendIdsResponse, error) {
l := logic.NewGetFriendIdsLogic(ctx, s.svcCtx)
return l.GetFriendIds(in)
}
func (s *FriendServer) GetFriendVersions(ctx context.Context, in *friend_rpc.GetFriendVersionsReq) (*friend_rpc.GetFriendVersionsRes, error) {
l := logic.NewGetFriendVersionsLogic(ctx, s.svcCtx)
return l.GetFriendVersions(in)
}
func (s *FriendServer) GetFriendVerifyVersions(ctx context.Context, in *friend_rpc.GetFriendVerifyVersionsReq) (*friend_rpc.GetFriendVerifyVersionsRes, error) {
l := logic.NewGetFriendVerifyVersionsLogic(ctx, s.svcCtx)
return l.GetFriendVerifyVersions(in)
}
func (s *FriendServer) GetFriendsListByIds(ctx context.Context, in *friend_rpc.GetFriendsListByIdsReq) (*friend_rpc.GetFriendsListByIdsRes, error) {
l := logic.NewGetFriendsListByIdsLogic(ctx, s.svcCtx)
return l.GetFriendsListByIds(in)
}
func (s *FriendServer) GetFriendVerifiesListByIds(ctx context.Context, in *friend_rpc.GetFriendVerifiesListByIdsReq) (*friend_rpc.GetFriendVerifiesListByIdsRes, error) {
l := logic.NewGetFriendVerifiesListByIdsLogic(ctx, s.svcCtx)
return l.GetFriendVerifiesListByIds(in)
}
func (s *FriendServer) GetFriendDetail(ctx context.Context, in *friend_rpc.GetFriendDetailReq) (*friend_rpc.GetFriendDetailRes, error) {
l := logic.NewGetFriendDetailLogic(ctx, s.svcCtx)
return l.GetFriendDetail(in)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/internal/config/config.go | app/friend/friend_rpc/internal/config/config.go | package config
import "github.com/zeromicro/go-zero/zrpc"
type Config struct {
zrpc.RpcServerConf
Mysql struct {
DataSource string
}
RedisConf struct {
Addr string
Password string
Db int
}
UserRpc zrpc.RpcClientConf
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/internal/logic/getfrienddetaillogic.go | app/friend/friend_rpc/internal/logic/getfrienddetaillogic.go | package logic
import (
"context"
"time"
"beaver/app/friend/friend_models"
"beaver/app/friend/friend_rpc/internal/svc"
"beaver/app/friend/friend_rpc/types/friend_rpc"
"beaver/app/user/user_rpc/types/user_rpc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetFriendDetailLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetFriendDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFriendDetailLogic {
return &GetFriendDetailLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetFriendDetailLogic) GetFriendDetail(in *friend_rpc.GetFriendDetailReq) (*friend_rpc.GetFriendDetailRes, error) {
// 查询当前用户与指定好友的好友关系
var friends []friend_models.FriendModel
err := l.svcCtx.DB.Where("((send_user_id = ? AND rev_user_id IN (?)) OR (rev_user_id = ? AND send_user_id IN (?))) AND is_deleted = ?",
in.UserId, in.FriendIds, in.UserId, in.FriendIds, false).Find(&friends).Error
if err != nil {
logx.Errorf("failed to query friends: %v", err)
return nil, err
}
// 提取好友ID列表
var friendIds []string
for _, friend := range friends {
if friend.SendUserID == in.UserId {
friendIds = append(friendIds, friend.RevUserID)
} else {
friendIds = append(friendIds, friend.SendUserID)
}
}
// 通过UserRpc批量获取用户信息
var userInfoMap map[string]*user_rpc.UserInfo
if len(friendIds) > 0 {
userListRes, err := l.svcCtx.UserRpc.UserListInfo(l.ctx, &user_rpc.UserListInfoReq{
UserIdList: friendIds,
})
if err != nil {
logx.Errorf("failed to get user info from UserRpc: %v", err)
return nil, err
}
userInfoMap = userListRes.UserInfo
}
// 构建好友ID到好友关系的映射
friendMap := make(map[string]friend_models.FriendModel)
for _, friend := range friends {
if friend.SendUserID == in.UserId {
// 当前用户是发起方,对方是接收方
friendMap[friend.RevUserID] = friend
} else {
// 当前用户是接收方,对方是发起方
friendMap[friend.SendUserID] = friend
}
}
// 构建响应
var friendDetails []*friend_rpc.FriendDetailItem
for _, friendId := range friendIds {
userInfo, userExists := userInfoMap[friendId]
friend, friendExists := friendMap[friendId]
if !userExists || !friendExists {
continue
}
// 获取备注信息
var notice string
if friend.SendUserID == in.UserId {
// 当前用户是发起方,使用接收方的备注
notice = friend.RevUserNotice
} else {
// 当前用户是接收方,使用发起方的备注
notice = friend.SendUserNotice
}
// 获取成为好友的时间(取最早的创建时间)
friendAt := time.Time(friend.CreatedAt).Unix()
friendDetails = append(friendDetails, &friend_rpc.FriendDetailItem{
UserId: friendId, // userInfoMap的key就是用户ID
NickName: userInfo.NickName,
Avatar: userInfo.Avatar,
Notice: notice,
FriendAt: friendAt,
})
}
return &friend_rpc.GetFriendDetailRes{
Friends: friendDetails,
}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/internal/logic/getfriendverifieslistbyidslogic.go | app/friend/friend_rpc/internal/logic/getfriendverifieslistbyidslogic.go | package logic
import (
"context"
"time"
"beaver/app/friend/friend_models"
"beaver/app/friend/friend_rpc/internal/svc"
"beaver/app/friend/friend_rpc/types/friend_rpc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetFriendVerifiesListByIdsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetFriendVerifiesListByIdsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFriendVerifiesListByIdsLogic {
return &GetFriendVerifiesListByIdsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetFriendVerifiesListByIdsLogic) GetFriendVerifiesListByIds(in *friend_rpc.GetFriendVerifiesListByIdsReq) (*friend_rpc.GetFriendVerifiesListByIdsRes, error) {
if len(in.VerifyIds) == 0 {
l.Errorf("验证记录ID列表为空")
return &friend_rpc.GetFriendVerifiesListByIdsRes{FriendVerifies: []*friend_rpc.FriendVerifyListById{}}, nil
}
// 查询指定ID列表中的好友验证信息
var friendVerifies []friend_models.FriendVerifyModel
query := l.svcCtx.DB.Where("verify_id IN (?)", in.VerifyIds)
// 增量同步:只返回版本号大于since的记录
if in.Since > 0 {
query = query.Where("version > ?", in.Since)
}
err := query.Find(&friendVerifies).Error
if err != nil {
l.Errorf("查询好友验证信息失败: ids=%v, since=%d, error=%v", in.VerifyIds, in.Since, err)
return nil, err
}
l.Infof("查询到 %d 个好友验证信息", len(friendVerifies))
// 转换为响应格式
var friendVerifiesList []*friend_rpc.FriendVerifyListById
for _, verify := range friendVerifies {
friendVerifiesList = append(friendVerifiesList, &friend_rpc.FriendVerifyListById{
VerifyId: verify.VerifyID,
SendUserId: verify.SendUserID,
RevUserId: verify.RevUserID,
SendStatus: int32(verify.SendStatus),
RevStatus: int32(verify.RevStatus),
Message: verify.Message,
Source: verify.Source,
Version: verify.Version,
CreatedAt: time.Time(verify.CreatedAt).UnixMilli(),
UpdatedAt: time.Time(verify.UpdatedAt).UnixMilli(),
})
}
return &friend_rpc.GetFriendVerifiesListByIdsRes{FriendVerifies: friendVerifiesList}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/internal/logic/getfriendidslogic.go | app/friend/friend_rpc/internal/logic/getfriendidslogic.go | package logic
import (
"context"
"beaver/app/friend/friend_models"
"beaver/app/friend/friend_rpc/internal/svc"
"beaver/app/friend/friend_rpc/types/friend_rpc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetFriendIdsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetFriendIdsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFriendIdsLogic {
return &GetFriendIdsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetFriendIdsLogic) GetFriendIds(in *friend_rpc.GetFriendIdsRequest) (*friend_rpc.GetFriendIdsResponse, error) {
var friends []friend_models.FriendModel
err := l.svcCtx.DB.Where("(send_user_id = ? OR rev_user_id = ?) AND is_deleted = false", in.UserID, in.UserID).Find(&friends).Error
if err != nil {
logx.Errorf("failed to query friends: %v", err)
return nil, err
}
var friendIds []string
for _, friend := range friends {
if friend.SendUserID == in.UserID {
friendIds = append(friendIds, friend.RevUserID)
} else {
friendIds = append(friendIds, friend.SendUserID)
}
}
return &friend_rpc.GetFriendIdsResponse{
FriendIds: friendIds,
}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/internal/logic/getfriendversionslogic.go | app/friend/friend_rpc/internal/logic/getfriendversionslogic.go | package logic
import (
"context"
"beaver/app/friend/friend_models"
"beaver/app/friend/friend_rpc/internal/svc"
"beaver/app/friend/friend_rpc/types/friend_rpc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetFriendVersionsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetFriendVersionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFriendVersionsLogic {
return &GetFriendVersionsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetFriendVersionsLogic) GetFriendVersions(in *friend_rpc.GetFriendVersionsReq) (*friend_rpc.GetFriendVersionsRes, error) {
// 查询用户相关的所有好友关系(作为发送者或接收者,且未删除)
var friends []friend_models.FriendModel
query := l.svcCtx.DB.Where("(send_user_id = ? OR rev_user_id = ?) AND is_deleted = ?",
in.UserId, in.UserId, false)
// 增量同步:只返回版本号大于since的记录
if in.Since > 0 {
query = query.Where("version > ?", in.Since)
}
err := query.Find(&friends).Error
if err != nil {
l.Errorf("查询用户好友版本信息失败: userId=%s, since=%d, error=%v", in.UserId, in.Since, err)
return nil, err
}
l.Infof("查询到用户 %s 的 %d 个好友版本信息", in.UserId, len(friends))
// 转换为响应格式
var friendVersions []*friend_rpc.GetFriendVersionsRes_FriendVersion
for _, friend := range friends {
friendVersions = append(friendVersions, &friend_rpc.GetFriendVersionsRes_FriendVersion{
FriendId: friend.FriendID, // 使用数据库记录的ID作为唯一标识符
Version: friend.Version,
})
}
return &friend_rpc.GetFriendVersionsRes{FriendVersions: friendVersions}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/internal/logic/getfriendslistbyidslogic.go | app/friend/friend_rpc/internal/logic/getfriendslistbyidslogic.go | package logic
import (
"context"
"time"
"beaver/app/friend/friend_models"
"beaver/app/friend/friend_rpc/internal/svc"
"beaver/app/friend/friend_rpc/types/friend_rpc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetFriendsListByIdsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetFriendsListByIdsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFriendsListByIdsLogic {
return &GetFriendsListByIdsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetFriendsListByIdsLogic) GetFriendsListByIds(in *friend_rpc.GetFriendsListByIdsReq) (*friend_rpc.GetFriendsListByIdsRes, error) {
if len(in.Ids) == 0 {
l.Errorf("ID列表为空")
return &friend_rpc.GetFriendsListByIdsRes{Friends: []*friend_rpc.FriendListById{}}, nil
}
// 查询指定ID列表中的好友信息
var friends []friend_models.FriendModel
query := l.svcCtx.DB.Where("friend_id IN (?)", in.Ids)
// 增量同步:只返回版本号大于since的记录
if in.Since > 0 {
query = query.Where("version > ?", in.Since)
}
err := query.Find(&friends).Error
if err != nil {
l.Errorf("查询好友信息失败: ids=%v, since=%d, error=%v", in.Ids, in.Since, err)
return nil, err
}
l.Infof("查询到 %d 个好友信息", len(friends))
// 转换为响应格式
var friendsList []*friend_rpc.FriendListById
for _, friend := range friends {
friendsList = append(friendsList, &friend_rpc.FriendListById{
Id: friend.FriendID,
SendUserId: friend.SendUserID,
RevUserId: friend.RevUserID,
SendUserNotice: friend.SendUserNotice,
RevUserNotice: friend.RevUserNotice,
Source: friend.Source,
IsDeleted: friend.IsDeleted,
Version: friend.Version,
CreatedAt: time.Time(friend.CreatedAt).UnixMilli(),
UpdatedAt: time.Time(friend.UpdatedAt).UnixMilli(),
})
}
return &friend_rpc.GetFriendsListByIdsRes{Friends: friendsList}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/internal/logic/getfriendverifyversionslogic.go | app/friend/friend_rpc/internal/logic/getfriendverifyversionslogic.go | package logic
import (
"context"
"beaver/app/friend/friend_models"
"beaver/app/friend/friend_rpc/internal/svc"
"beaver/app/friend/friend_rpc/types/friend_rpc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetFriendVerifyVersionsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetFriendVerifyVersionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFriendVerifyVersionsLogic {
return &GetFriendVerifyVersionsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetFriendVerifyVersionsLogic) GetFriendVerifyVersions(in *friend_rpc.GetFriendVerifyVersionsReq) (*friend_rpc.GetFriendVerifyVersionsRes, error) {
// 查询用户相关的所有好友验证记录(作为发送者或接收者)
var friendVerifies []friend_models.FriendVerifyModel
query := l.svcCtx.DB.Where("send_user_id = ? OR rev_user_id = ?", in.UserId, in.UserId)
// 增量同步:只返回版本号大于since的记录
if in.Since > 0 {
query = query.Where("version > ?", in.Since)
}
err := query.Find(&friendVerifies).Error
if err != nil {
l.Errorf("查询用户好友验证版本信息失败: userId=%s, since=%d, error=%v", in.UserId, in.Since, err)
return nil, err
}
l.Infof("查询到用户 %s 的 %d 个好友验证版本信息", in.UserId, len(friendVerifies))
// 转换为响应格式
var friendVerifyVersions []*friend_rpc.GetFriendVerifyVersionsRes_FriendVerifyVersion
for _, verify := range friendVerifies {
friendVerifyVersions = append(friendVerifyVersions, &friend_rpc.GetFriendVerifyVersionsRes_FriendVerifyVersion{
VerifyId: verify.VerifyID,
Version: verify.Version,
})
}
return &friend_rpc.GetFriendVerifyVersionsRes{FriendVerifyVersions: friendVerifyVersions}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_rpc/friend/friend.go | app/friend/friend_rpc/friend/friend.go | // Code generated by goctl. DO NOT EDIT.
// goctl 1.8.5
// Source: friend_rpc.proto
package friend
import (
"context"
"beaver/app/friend/friend_rpc/types/friend_rpc"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
)
type (
FriendDetailItem = friend_rpc.FriendDetailItem
FriendListById = friend_rpc.FriendListById
FriendVerifyListById = friend_rpc.FriendVerifyListById
GetFriendDetailReq = friend_rpc.GetFriendDetailReq
GetFriendDetailRes = friend_rpc.GetFriendDetailRes
GetFriendIdsRequest = friend_rpc.GetFriendIdsRequest
GetFriendIdsResponse = friend_rpc.GetFriendIdsResponse
GetFriendVerifiesListByIdsReq = friend_rpc.GetFriendVerifiesListByIdsReq
GetFriendVerifiesListByIdsRes = friend_rpc.GetFriendVerifiesListByIdsRes
GetFriendVerifyVersionsReq = friend_rpc.GetFriendVerifyVersionsReq
GetFriendVerifyVersionsRes = friend_rpc.GetFriendVerifyVersionsRes
GetFriendVerifyVersionsRes_FriendVerifyVersion = friend_rpc.GetFriendVerifyVersionsRes_FriendVerifyVersion
GetFriendVersionsReq = friend_rpc.GetFriendVersionsReq
GetFriendVersionsRes = friend_rpc.GetFriendVersionsRes
GetFriendVersionsRes_FriendVersion = friend_rpc.GetFriendVersionsRes_FriendVersion
GetFriendsListByIdsReq = friend_rpc.GetFriendsListByIdsReq
GetFriendsListByIdsRes = friend_rpc.GetFriendsListByIdsRes
Friend interface {
GetFriendIds(ctx context.Context, in *GetFriendIdsRequest, opts ...grpc.CallOption) (*GetFriendIdsResponse, error)
GetFriendVersions(ctx context.Context, in *GetFriendVersionsReq, opts ...grpc.CallOption) (*GetFriendVersionsRes, error)
GetFriendVerifyVersions(ctx context.Context, in *GetFriendVerifyVersionsReq, opts ...grpc.CallOption) (*GetFriendVerifyVersionsRes, error)
GetFriendsListByIds(ctx context.Context, in *GetFriendsListByIdsReq, opts ...grpc.CallOption) (*GetFriendsListByIdsRes, error)
GetFriendVerifiesListByIds(ctx context.Context, in *GetFriendVerifiesListByIdsReq, opts ...grpc.CallOption) (*GetFriendVerifiesListByIdsRes, error)
GetFriendDetail(ctx context.Context, in *GetFriendDetailReq, opts ...grpc.CallOption) (*GetFriendDetailRes, error)
}
defaultFriend struct {
cli zrpc.Client
}
)
func NewFriend(cli zrpc.Client) Friend {
return &defaultFriend{
cli: cli,
}
}
func (m *defaultFriend) GetFriendIds(ctx context.Context, in *GetFriendIdsRequest, opts ...grpc.CallOption) (*GetFriendIdsResponse, error) {
client := friend_rpc.NewFriendClient(m.cli.Conn())
return client.GetFriendIds(ctx, in, opts...)
}
func (m *defaultFriend) GetFriendVersions(ctx context.Context, in *GetFriendVersionsReq, opts ...grpc.CallOption) (*GetFriendVersionsRes, error) {
client := friend_rpc.NewFriendClient(m.cli.Conn())
return client.GetFriendVersions(ctx, in, opts...)
}
func (m *defaultFriend) GetFriendVerifyVersions(ctx context.Context, in *GetFriendVerifyVersionsReq, opts ...grpc.CallOption) (*GetFriendVerifyVersionsRes, error) {
client := friend_rpc.NewFriendClient(m.cli.Conn())
return client.GetFriendVerifyVersions(ctx, in, opts...)
}
func (m *defaultFriend) GetFriendsListByIds(ctx context.Context, in *GetFriendsListByIdsReq, opts ...grpc.CallOption) (*GetFriendsListByIdsRes, error) {
client := friend_rpc.NewFriendClient(m.cli.Conn())
return client.GetFriendsListByIds(ctx, in, opts...)
}
func (m *defaultFriend) GetFriendVerifiesListByIds(ctx context.Context, in *GetFriendVerifiesListByIdsReq, opts ...grpc.CallOption) (*GetFriendVerifiesListByIdsRes, error) {
client := friend_rpc.NewFriendClient(m.cli.Conn())
return client.GetFriendVerifiesListByIds(ctx, in, opts...)
}
func (m *defaultFriend) GetFriendDetail(ctx context.Context, in *GetFriendDetailReq, opts ...grpc.CallOption) (*GetFriendDetailRes, error) {
client := friend_rpc.NewFriendClient(m.cli.Conn())
return client.GetFriendDetail(ctx, in, opts...)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/friend.go | app/friend/friend_api/friend.go | package main
import (
"flag"
"fmt"
"beaver/app/friend/friend_api/internal/config"
"beaver/app/friend/friend_api/internal/handler"
"beaver/app/friend/friend_api/internal/svc"
"beaver/common/etcd"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var configFile = flag.String("f", "etc/friend.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
ctx := svc.NewServiceContext(c)
handler.RegisterHandlers(server, ctx)
etcd.DeliveryAddress(c.Etcd, c.Name+"_api", fmt.Sprintf("%s:%d", c.Host, c.Port))
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/svc/servicecontext.go | app/friend/friend_api/internal/svc/servicecontext.go | package svc
import (
"beaver/app/chat/chat_rpc/chat"
"beaver/app/chat/chat_rpc/types/chat_rpc"
"beaver/app/friend/friend_api/internal/config"
"beaver/app/friend/friend_rpc/friend"
"beaver/app/friend/friend_rpc/types/friend_rpc"
"beaver/app/notification/notification_rpc/notification"
"beaver/app/user/user_rpc/types/user_rpc"
"beaver/app/user/user_rpc/user"
"beaver/common/zrpc_interceptor"
"beaver/core"
versionPkg "beaver/core/version"
"github.com/go-redis/redis"
"github.com/zeromicro/go-zero/zrpc"
"gorm.io/gorm"
)
type ServiceContext struct {
Config config.Config
DB *gorm.DB
Redis *redis.Client
UserRpc user_rpc.UserClient
ChatRpc chat_rpc.ChatClient
FriendRpc friend_rpc.FriendClient
NotifyRpc notification.Notification
VersionGen *versionPkg.VersionGenerator
}
func NewServiceContext(c config.Config) *ServiceContext {
mysqlDb := core.InitGorm(c.Mysql.DataSource)
client := core.InitRedis(c.Redis.Addr, c.Redis.Password, c.Redis.Db)
versionGen := versionPkg.NewVersionGenerator(client, mysqlDb)
return &ServiceContext{
Config: c,
DB: mysqlDb,
Redis: client,
ChatRpc: chat.NewChat(zrpc.MustNewClient(c.ChatRpc, zrpc.WithUnaryClientInterceptor(zrpc_interceptor.ClientInfoInterceptor))),
UserRpc: user.NewUser(zrpc.MustNewClient(c.UserRpc, zrpc.WithUnaryClientInterceptor(zrpc_interceptor.ClientInfoInterceptor))),
FriendRpc: friend.NewFriend(zrpc.MustNewClient(c.FriendRpc, zrpc.WithUnaryClientInterceptor(zrpc_interceptor.ClientInfoInterceptor))),
NotifyRpc: notification.NewNotification(zrpc.MustNewClient(c.NotificationRpc, zrpc.WithUnaryClientInterceptor(zrpc_interceptor.ClientInfoInterceptor))),
VersionGen: versionGen,
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/types/types.go | app/friend/friend_api/internal/types/types.go | // Code generated by goctl. DO NOT EDIT.
package types
type AddFriendReq struct {
UserID string `header:"Beaver-User-Id"` // 当前用户ID
FriendID string `json:"friendId"` // 要添加的好友用户ID
Verify string `json:"verify,optional"` // 验证消息,可选
Source string `json:"source"` // 添加好友来源:email(邮箱搜索)/qrcode(扫码)/userId(用户ID搜索)
}
type AddFriendRes struct {
Version int64 `json:"version"` // 好友验证版本号
}
type FriendByUuid struct {
FriendID string `json:"friendId"` // 好友记录ID
SendUserID string `json:"sendUserId"` // 发送者用户ID
RevUserID string `json:"revUserId"` // 接收者用户ID
SendUserNotice string `json:"sendUserNotice"` // 发送者备注
RevUserNotice string `json:"revUserNotice"` // 接收者备注
Source string `json:"source"` // 添加好友来源
IsDeleted bool `json:"isDeleted"` // 是否已删除
Version int64 `json:"version"` // 版本号
CreatedAt int64 `json:"createdAt"` // 创建时间戳
UpdatedAt int64 `json:"updatedAt"` // 更新时间戳
}
type FriendInfoReq struct {
UserID string `header:"Beaver-User-Id"` // 当前用户ID
FriendID string `form:"friendId"` // 好友用户ID
}
type FriendInfoRes struct {
UserID string `json:"userId"` // 用户ID
NickName string `json:"nickName"` // 用户昵称
Avatar string `json:"avatar"` // 用户头像文件名
Abstract string `json:"abstract"` // 用户签名
Notice string `json:"notice"` // 好友备注
IsFriend bool `json:"isFriend"` // 是否为好友关系
ConversationID string `json:"conversationId"` // 会话ID
Email string `json:"email"` // 用户邮箱
Source string `json:"source"` // 好友关系来源:email/qrcode
}
type FriendListReq struct {
UserID string `header:"Beaver-User-Id"` // 当前用户ID
Page int `form:"page,optional"` // 页码,可选,默认1
Limit int `form:"limit,optional"` // 每页数量,可选,默认20
}
type FriendListRes struct {
List []FriendInfoRes `json:"list"` // 好友列表
}
type FriendValidInfo struct {
UserID string `json:"userId"` // 用户ID
NickName string `json:"nickName"` // 用户昵称
Avatar string `json:"avatar"` // 用户头像文件名
Message string `json:"message"` // 验证消息
Source string `json:"source"` // 添加好友来源:email/qrcode
Id string `json:"id"` // 验证记录ID(作为唯一标识)
Flag string `json:"flag"` // 用户角色:send(发送者)/receive(接收者)
Status int8 `json:"status"` // 验证状态:0(未处理)/1(已通过)/2(已拒绝)
CreatedAt string `json:"createdAt"` // 验证时间
}
type FriendValidStatusReq struct {
UserID string `header:"Beaver-User-Id"` // 当前用户ID
VerifyID string `json:"verifyId"` // 验证记录ID
Status int8 `json:"status"` // 处理状态:1(同意)/2(拒绝)
}
type FriendValidStatusRes struct {
Version int64 `json:"version"` // 处理后的好友版本号
}
type FriendVerifyById struct {
VerifyID string `json:"verifyId"` // 验证记录ID
SendUserID string `json:"sendUserId"` // 发送者用户ID
RevUserID string `json:"revUserId"` // 接收者用户ID
SendStatus int32 `json:"sendStatus"` // 发送方状态:0(未处理)/1(已通过)/2(已拒绝)/3(忽略)/4(删除)
RevStatus int32 `json:"revStatus"` // 接收方状态:0(未处理)/1(已通过)/2(已拒绝)/3(忽略)/4(删除)
Message string `json:"message"` // 附加消息
Source string `json:"source"` // 添加好友来源
Version int64 `json:"version"` // 版本号
CreatedAt int64 `json:"createdAt"` // 创建时间戳
UpdatedAt int64 `json:"updatedAt"` // 更新时间戳
}
type GetFriendVerifiesListByIdsReq struct {
VerifyIds []string `json:"verifyIds"` // 验证记录ID列表
}
type GetFriendVerifiesListByIdsRes struct {
FriendVerifies []FriendVerifyById `json:"friendVerifies"` // 好友验证列表
}
type GetFriendsListByUuidsReq struct {
FriendIds []string `json:"friendIds"` // 好友记录ID列表
}
type GetFriendsListByUuidsRes struct {
Friends []FriendByUuid `json:"friends"` // 好友列表
}
type NoticeUpdateReq struct {
UserID string `header:"Beaver-User-Id"` // 当前用户ID
FriendID string `json:"friendId"` // 好友用户ID
Notice string `json:"notice"` // 新的备注内容
}
type NoticeUpdateRes struct {
Version int64 `json:"version"` // 更新后的好友版本号
}
type SearchReq struct {
UserID string `header:"Beaver-User-Id"` // 当前用户ID
Keyword string `form:"keyword"` // 搜索关键词(用户ID或邮箱)
Type string `form:"type,optional"` // 搜索类型:userId(用户ID)/email(邮箱),默认email
}
type SearchRes struct {
UserID string `json:"userId"` // 用户ID
NickName string `json:"nickName"` // 用户昵称
Avatar string `json:"avatar"` // 用户头像文件名
Abstract string `json:"abstract"` // 用户签名
Notice string `json:"notice"` // 好友备注
IsFriend bool `json:"isFriend"` // 是否为好友关系
ConversationID string `json:"conversationId"` // 会话ID
Email string `json:"email"` // 用户邮箱
}
type SearchValidInfoReq struct {
UserID string `header:"Beaver-User-Id"` // 当前用户ID
FriendID string `json:"friendId"` // 好友用户ID
}
type SearchValidInfoRes struct {
ValidID string `json:"validId"` // 验证记录ID
}
type ValidListReq struct {
UserID string `header:"Beaver-User-Id"` // 当前用户ID
Page int `json:"page,optional"` // 页码,可选,默认1
Limit int `json:"limit,optional"` // 每页数量,可选,默认20
}
type ValidListRes struct {
List []FriendValidInfo `json:"list"` // 验证记录列表
Count int64 `json:"count"` // 总记录数
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/config/config.go | app/friend/friend_api/internal/config/config.go | package config
import (
"github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/zrpc"
)
type Config struct {
rest.RestConf
Mysql struct {
DataSource string
}
Etcd string
Redis struct {
Addr string
Password string
Db int
}
UserRpc zrpc.RpcClientConf
FriendRpc zrpc.RpcClientConf
ChatRpc zrpc.RpcClientConf
NotificationRpc zrpc.RpcClientConf
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/noticeupdatehandler.go | app/friend/friend_api/internal/handler/noticeupdatehandler.go | package handler
import (
"beaver/app/friend/friend_api/internal/logic"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/common/response"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
func noticeUpdateHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.NoticeUpdateReq
if err := httpx.Parse(r, &req); err != nil {
response.Response(r, w, nil, err)
return
}
l := logic.NewNoticeUpdateLogic(r.Context(), svcCtx)
resp, err := l.NoticeUpdate(&req)
response.Response(r, w, resp, err)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/searchvalidinfohandler.go | app/friend/friend_api/internal/handler/searchvalidinfohandler.go | package handler
import (
"beaver/app/friend/friend_api/internal/logic"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/common/response"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
func searchValidInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.SearchValidInfoReq
if err := httpx.Parse(r, &req); err != nil {
response.Response(r, w, nil, err)
return
}
l := logic.NewSearchValidInfoLogic(r.Context(), svcCtx)
resp, err := l.SearchValidInfo(&req)
response.Response(r, w, resp, err)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/friendinfohandler.go | app/friend/friend_api/internal/handler/friendinfohandler.go | package handler
import (
"beaver/app/friend/friend_api/internal/logic"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/common/response"
"errors"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
func friendInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.FriendInfoReq
if err := httpx.Parse(r, &req); err != nil {
response.Response(r, w, nil, err)
return
}
// 参数验证
if req.FriendID == "" {
response.Response(r, w, nil, errors.New("好友ID不能为空"))
return
}
// 不能查询自己的信息
if req.UserID == req.FriendID {
response.Response(r, w, nil, errors.New("不能查询自己的信息"))
return
}
l := logic.NewFriendInfoLogic(r.Context(), svcCtx)
resp, err := l.FriendInfo(&req)
response.Response(r, w, resp, err)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/getfriendverifieslistbyidshandler.go | app/friend/friend_api/internal/handler/getfriendverifieslistbyidshandler.go | package handler
import (
"beaver/app/friend/friend_api/internal/logic"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/common/response"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
func getFriendVerifiesListByIdsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.GetFriendVerifiesListByIdsReq
if err := httpx.Parse(r, &req); err != nil {
response.Response(r, w, nil, err)
return
}
l := logic.NewGetFriendVerifiesListByIdsLogic(r.Context(), svcCtx)
resp, err := l.GetFriendVerifiesListByIds(&req)
response.Response(r, w, resp, err)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/searchhandler.go | app/friend/friend_api/internal/handler/searchhandler.go | package handler
import (
"beaver/app/friend/friend_api/internal/logic"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/common/response"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
func searchHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.SearchReq
if err := httpx.Parse(r, &req); err != nil {
response.Response(r, w, nil, err)
return
}
l := logic.NewSearchLogic(r.Context(), svcCtx)
resp, err := l.Search(&req)
response.Response(r, w, resp, err)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/getfriendslistbyuuidshandler.go | app/friend/friend_api/internal/handler/getfriendslistbyuuidshandler.go | package handler
import (
"beaver/app/friend/friend_api/internal/logic"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/common/response"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
func getFriendsListByUuidsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.GetFriendsListByUuidsReq
if err := httpx.Parse(r, &req); err != nil {
response.Response(r, w, nil, err)
return
}
l := logic.NewGetFriendsListByUuidsLogic(r.Context(), svcCtx)
resp, err := l.GetFriendsListByUuids(&req)
response.Response(r, w, resp, err)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/addfriendhandler.go | app/friend/friend_api/internal/handler/addfriendhandler.go | package handler
import (
"beaver/app/friend/friend_api/internal/logic"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/common/response"
"errors"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
func addFriendHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.AddFriendReq
if err := httpx.Parse(r, &req); err != nil {
response.Response(r, w, nil, err)
return
}
// 参数验证
if req.UserID == "" || req.FriendID == "" {
response.Response(r, w, nil, errors.New("用户ID和好友ID不能为空"))
return
}
// 验证来源字段
if req.Source == "" {
response.Response(r, w, nil, errors.New("来源字段不能为空"))
return
}
// 验证来源值是否合法
validSources := map[string]bool{
"email": true,
"qrcode": true,
"userId": true,
}
if !validSources[req.Source] {
response.Response(r, w, nil, errors.New("无效的来源值,只支持email和qrcode"))
return
}
// 不能添加自己为好友
if req.UserID == req.FriendID {
response.Response(r, w, nil, errors.New("不能添加自己为好友"))
return
}
l := logic.NewAddFriendLogic(r.Context(), svcCtx)
resp, err := l.AddFriend(&req)
response.Response(r, w, resp, err, "发送成功")
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/friendlisthandler.go | app/friend/friend_api/internal/handler/friendlisthandler.go | package handler
import (
"beaver/app/friend/friend_api/internal/logic"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/common/response"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
func friendListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.FriendListReq
if err := httpx.Parse(r, &req); err != nil {
response.Response(r, w, nil, err)
return
}
l := logic.NewFriendListLogic(r.Context(), svcCtx)
resp, err := l.FriendList(&req)
response.Response(r, w, resp, err)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/validlisthandler.go | app/friend/friend_api/internal/handler/validlisthandler.go | package handler
import (
"beaver/app/friend/friend_api/internal/logic"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/common/response"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
func validListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ValidListReq
if err := httpx.Parse(r, &req); err != nil {
response.Response(r, w, nil, err)
return
}
l := logic.NewValidListLogic(r.Context(), svcCtx)
resp, err := l.ValidList(&req)
response.Response(r, w, resp, err)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/routes.go | app/friend/friend_api/internal/handler/routes.go | // Code generated by goctl. DO NOT EDIT.
package handler
import (
"net/http"
"beaver/app/friend/friend_api/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
// 发送好友验证请求
Method: http.MethodPost,
Path: "/api/friend/add_friend",
Handler: addFriendHandler(serverCtx),
},
{
// 获取好友详细信息
Method: http.MethodGet,
Path: "/api/friend/friend_info",
Handler: friendInfoHandler(serverCtx),
},
{
// 获取好友列表
Method: http.MethodGet,
Path: "/api/friend/friend_list",
Handler: friendListHandler(serverCtx),
},
{
// 批量获取好友验证数据(通过ID)
Method: http.MethodPost,
Path: "/api/friend/getFriendVerifiesListByIds",
Handler: getFriendVerifiesListByIdsHandler(serverCtx),
},
{
// 批量获取好友数据(通过ID)
Method: http.MethodPost,
Path: "/api/friend/getFriendsListByIds",
Handler: getFriendsListByUuidsHandler(serverCtx),
},
{
// 通过用户ID或邮箱搜索用户
Method: http.MethodGet,
Path: "/api/friend/search",
Handler: searchHandler(serverCtx),
},
{
// 查询好友验证记录
Method: http.MethodPost,
Path: "/api/friend/searchValidInfo",
Handler: searchValidInfoHandler(serverCtx),
},
{
// 修改好友备注
Method: http.MethodPost,
Path: "/api/friend/update_notice",
Handler: noticeUpdateHandler(serverCtx),
},
{
// 处理好友验证请求(同意/拒绝)
Method: http.MethodPost,
Path: "/api/friend/valid",
Handler: userValidStatusHandler(serverCtx),
},
{
// 获取好友验证请求列表
Method: http.MethodPost,
Path: "/api/friend/valid_list",
Handler: validListHandler(serverCtx),
},
},
)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/handler/uservalidstatushandler.go | app/friend/friend_api/internal/handler/uservalidstatushandler.go | package handler
import (
"beaver/app/friend/friend_api/internal/logic"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/common/response"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
func userValidStatusHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.FriendValidStatusReq
if err := httpx.Parse(r, &req); err != nil {
response.Response(r, w, nil, err)
return
}
l := logic.NewUserValidStatusLogic(r.Context(), svcCtx)
resp, err := l.UserValidStatus(&req)
response.Response(r, w, resp, err)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/logic/uservalidstatuslogic.go | app/friend/friend_api/internal/logic/uservalidstatuslogic.go | package logic
import (
"context"
"encoding/json"
"errors"
"fmt"
"sort"
"beaver/app/chat/chat_rpc/types/chat_rpc"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/app/friend/friend_models"
"beaver/app/notification/notification_models"
"beaver/app/notification/notification_rpc/types/notification_rpc"
"beaver/common/ajax"
"beaver/common/wsEnum/wsCommandConst"
"beaver/common/wsEnum/wsTypeConst"
"github.com/google/uuid"
"github.com/zeromicro/go-zero/core/logx"
)
type UserValidStatusLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUserValidStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserValidStatusLogic {
return &UserValidStatusLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UserValidStatusLogic) UserValidStatus(req *types.FriendValidStatusReq) (resp *types.FriendValidStatusRes, err error) {
// 参数验证
if req.UserID == "" || req.VerifyID == "" {
return nil, errors.New("用户ID和验证ID不能为空")
}
// 状态值验证
if req.Status < 1 || req.Status > 4 {
return nil, errors.New("无效的状态值")
}
var friendVerify friend_models.FriendVerifyModel
var conversationID string
var friendNextVersion int64
var friendID string
var decisionStatus int32
// 查询好友验证记录,确保当前用户是接收方
err = l.svcCtx.DB.Take(&friendVerify, "verify_id = ? and rev_user_id = ?", req.VerifyID, req.UserID).Error
if err != nil {
l.Logger.Errorf("好友验证记录不存在: verifyID=%s, userID=%s, error=%v", req.VerifyID, req.UserID, err)
return nil, errors.New("好友验证不存在")
}
// 检查验证状态是否已处理
if friendVerify.RevStatus != 0 {
l.Logger.Errorf("好友验证已处理: verifyID=%s, currentStatus=%d", req.VerifyID, friendVerify.RevStatus)
return nil, errors.New("该验证已处理,无法重复操作")
}
// 处理不同的状态
switch req.Status {
case 1: // 同意
friendVerify.RevStatus = 1
decisionStatus = 1
// 获取下一个版本号
friendNextVersion = l.svcCtx.VersionGen.GetNextVersion("friends", "", "")
if friendNextVersion == -1 {
l.Logger.Errorf("获取好友版本号失败")
return nil, errors.New("系统错误")
}
// 生成好友记录ID
friendID = uuid.New().String()
// 创建好友关系,同步来源信息
err = l.svcCtx.DB.Create(&friend_models.FriendModel{
FriendID: friendID, // 使用预生成的ID
SendUserID: friendVerify.SendUserID,
RevUserID: friendVerify.RevUserID,
Source: friendVerify.Source, // 同步来源字段
Version: friendNextVersion, // 设置初始版本号
}).Error
if err != nil {
l.Logger.Errorf("创建好友关系失败: %v", err)
return nil, errors.New("创建好友关系失败")
}
// 生成私聊会话ID(微信风格:排序后拼接)
userIds := []string{friendVerify.SendUserID, friendVerify.RevUserID}
sort.Strings(userIds) // 确保ID顺序一致
conversationId := fmt.Sprintf("private_%s_%s", userIds[0], userIds[1])
// 调用Chat服务初始化私聊会话
initResp, err := l.svcCtx.ChatRpc.InitializeConversation(context.Background(), &chat_rpc.InitializeConversationReq{
ConversationId: conversationId,
Type: 1, // 私聊
UserIds: []string{friendVerify.SendUserID, friendVerify.RevUserID},
})
if err != nil {
l.Logger.Errorf("初始化私聊会话失败: %v", err)
return nil, fmt.Errorf("初始化私聊会话失败: %v", err)
}
conversationID = initResp.ConversationId
// 异步发送通知欢迎消息(通过专门的通知消息服务)
go func() {
defer func() {
if r := recover(); r != nil {
l.Logger.Errorf("异步发送欢迎消息时发生panic: %v", r)
}
}()
// 调用Chat服务的通知消息发送接口
_, err := l.svcCtx.ChatRpc.SendNotificationMessage(context.Background(), &chat_rpc.SendNotificationMessageReq{
ConversationId: conversationID,
MessageType: 1, // 好友添加成功欢迎消息
Content: "我们已经是好友了,开始聊天吧",
RelatedUserId: friendVerify.SendUserID, // 相关好友ID
ReadUserIds: []string{friendVerify.RevUserID}, // 只有同意方标记为已读
})
if err != nil {
l.Logger.Errorf("异步发送欢迎消息失败: %v", err)
} else {
l.Logger.Infof("异步发送欢迎消息成功: conversationID=%s", conversationID)
}
}()
case 2: // 拒绝
friendVerify.RevStatus = 2
decisionStatus = 2
case 4: // 删除
// 直接删除验证记录
err = l.svcCtx.DB.Delete(&friendVerify).Error
if err != nil {
l.Logger.Errorf("删除验证记录失败: %v", err)
return nil, errors.New("删除验证记录失败")
}
l.Logger.Infof("删除好友验证记录成功: verifyID=%s, userID=%s", req.VerifyID, req.UserID)
return &types.FriendValidStatusRes{}, nil
}
// 获取下一个版本号并更新version字段
nextVersion := l.svcCtx.VersionGen.GetNextVersion("friend_verify", "", "")
if nextVersion == -1 {
l.Logger.Errorf("获取版本号失败")
return nil, errors.New("系统错误")
}
friendVerify.Version = nextVersion
// 保存验证状态
err = l.svcCtx.DB.Save(&friendVerify).Error
if err != nil {
l.Logger.Errorf("保存验证状态失败: %v", err)
return nil, errors.New("保存验证状态失败")
}
// 异步发送WebSocket通知
go func() {
defer func() {
if r := recover(); r != nil {
l.Logger.Errorf("异步发送WebSocket消息时发生panic: %v", r)
}
}()
// 构建表更新数据 - 包含版本号和ID,让前端知道具体同步哪些数据
var tableUpdates []map[string]interface{}
// 所有处理成功的状态都发送friend_verify表的更新
verifyUpdates := map[string]interface{}{
"table": "friend_verify",
"data": []map[string]interface{}{
{
"version": nextVersion,
"verifyId": friendVerify.VerifyID,
},
},
}
tableUpdates = append(tableUpdates, verifyUpdates)
// 如果是同意添加好友,额外发送friends表版本更新
if friendVerify.RevStatus == 1 {
friendUpdates := map[string]interface{}{
"table": "friends",
"data": []map[string]interface{}{
{
"version": friendNextVersion,
"friendId": friendID, // 使用预生成的ID
},
},
}
tableUpdates = append(tableUpdates, friendUpdates)
}
ajax.SendMessageToWs(l.svcCtx.Config.Etcd, wsCommandConst.FRIEND_OPERATION, wsTypeConst.FriendVerifyReceive, friendVerify.SendUserID, friendVerify.RevUserID, map[string]interface{}{
"tableUpdates": tableUpdates,
}, conversationID)
ajax.SendMessageToWs(l.svcCtx.Config.Etcd, wsCommandConst.FRIEND_OPERATION, wsTypeConst.FriendVerifyReceive, friendVerify.RevUserID, friendVerify.SendUserID, map[string]interface{}{
"tableUpdates": tableUpdates,
}, conversationID)
l.Logger.Infof("异步发送WebSocket通知完成: verifyID=%s, status=%d", req.VerifyID, friendVerify.RevStatus)
}()
l.Logger.Infof("处理好友验证成功: verifyID=%s, userID=%s, status=%d, source=%s", req.VerifyID, req.UserID, req.Status, friendVerify.Source)
resp = &types.FriendValidStatusRes{
Version: nextVersion,
}
// 投递处理结果通知给申请人(send_user_id)
go func() {
eventType := ""
switch decisionStatus {
case 1:
eventType = notification_models.EventTypeFriendRequestAccept
case 2:
eventType = notification_models.EventTypeFriendRequestReject
default:
return
}
payload, _ := json.Marshal(map[string]interface{}{
"verifyId": req.VerifyID,
"status": decisionStatus,
})
_, err := l.svcCtx.NotifyRpc.PushEvent(l.ctx, ¬ification_rpc.PushEventReq{
EventType: eventType,
Category: notification_models.CategorySocial,
FromUserId: friendVerify.RevUserID, // 审核人
TargetId: req.VerifyID,
TargetType: notification_models.TargetTypeUser,
PayloadJson: string(payload),
ToUserIds: []string{friendVerify.SendUserID}, // 申请人
DedupHash: fmt.Sprintf("%s_%d", req.VerifyID, decisionStatus),
})
if err != nil {
l.Logger.Errorf("投递好友审核结果通知失败: %v", err)
}
}()
return resp, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/logic/noticeupdatelogic.go | app/friend/friend_api/internal/logic/noticeupdatelogic.go | package logic
import (
"context"
"errors"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/app/friend/friend_models"
"beaver/common/ajax"
"beaver/common/wsEnum/wsCommandConst"
"beaver/common/wsEnum/wsTypeConst"
"github.com/zeromicro/go-zero/core/logx"
)
type NoticeUpdateLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewNoticeUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NoticeUpdateLogic {
return &NoticeUpdateLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *NoticeUpdateLogic) NoticeUpdate(req *types.NoticeUpdateReq) (resp *types.NoticeUpdateRes, err error) {
// 参数验证
if req.UserID == "" || req.FriendID == "" {
return nil, errors.New("用户ID和好友ID不能为空")
}
// 不能修改自己的备注
if req.UserID == req.FriendID {
return nil, errors.New("不能修改自己的备注")
}
var friend friend_models.FriendModel
// 检查是否为好友关系
if !friend.IsFriend(l.svcCtx.DB, req.UserID, req.FriendID) {
l.Logger.Errorf("尝试修改非好友备注: userID=%s, friendID=%s", req.UserID, req.FriendID)
return nil, errors.New("不是好友关系")
}
// 查询好友关系详情
err = l.svcCtx.DB.Take(&friend,
"((send_user_id = ? AND rev_user_id = ?) OR (send_user_id = ? AND rev_user_id = ?)) AND is_deleted = 0",
req.UserID, req.FriendID, req.FriendID, req.UserID).Error
if err != nil {
l.Logger.Errorf("查询好友关系失败: %v", err)
return nil, errors.New("查询好友关系失败")
}
// 获取下一个版本号
nextVersion := l.svcCtx.VersionGen.GetNextVersion("friends", "", "")
if nextVersion == -1 {
l.Logger.Errorf("获取版本号失败")
return nil, errors.New("系统错误")
}
// 根据用户角色更新对应的备注字段和版本号
if friend.SendUserID == req.UserID {
// 我是发起方,更新发起方备注
if friend.SendUserNotice == req.Notice {
// 备注没有变化,直接返回
return &types.NoticeUpdateRes{}, nil
}
err = l.svcCtx.DB.Model(&friend_models.FriendModel{}).Where("friend_id = ?", friend.FriendID).Updates(map[string]interface{}{
"send_user_notice": req.Notice,
"version": nextVersion,
}).Error
} else if friend.RevUserID == req.UserID {
// 我是接收方,更新接收方备注
if friend.RevUserNotice == req.Notice {
// 备注没有变化,直接返回
return &types.NoticeUpdateRes{}, nil
}
err = l.svcCtx.DB.Model(&friend_models.FriendModel{}).Where("friend_id = ?", friend.FriendID).Updates(map[string]interface{}{
"rev_user_notice": req.Notice,
"version": nextVersion,
}).Error
} else {
// 这种情况理论上不应该发生
l.Logger.Errorf("用户角色异常: userID=%s, friendID=%s", req.UserID, req.FriendID)
return nil, errors.New("用户角色异常")
}
if err != nil {
l.Logger.Errorf("更新好友备注失败: %v", err)
return nil, errors.New("更新好友备注失败")
}
// 异步发送WebSocket通知给自己(备注是个人设置)
go func() {
defer func() {
if r := recover(); r != nil {
l.Logger.Errorf("异步发送WebSocket消息时发生panic: %v", r)
}
}()
// 构建好友表更新数据 - 包含版本号和ID,让前端知道具体同步哪些数据
friendUpdates := map[string]interface{}{
"table": "friends",
"data": []map[string]interface{}{
{
"version": nextVersion,
"friendId": friend.FriendID,
},
},
}
ajax.SendMessageToWs(l.svcCtx.Config.Etcd, wsCommandConst.FRIEND_OPERATION, wsTypeConst.FriendReceive, req.UserID, req.UserID, map[string]interface{}{
"tableUpdates": []map[string]interface{}{friendUpdates},
}, "")
l.Logger.Infof("异步发送好友备注更新通知完成: userId=%s, friendId=%s, version=%d", req.UserID, friend.FriendID, nextVersion)
}()
l.Logger.Infof("更新好友备注成功: userID=%s, friendID=%s, notice=%s", req.UserID, req.FriendID, req.Notice)
return &types.NoticeUpdateRes{
Version: nextVersion,
}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/logic/getfriendverifieslistbyidslogic.go | app/friend/friend_api/internal/logic/getfriendverifieslistbyidslogic.go | package logic
import (
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/app/friend/friend_models"
"context"
"time"
"github.com/zeromicro/go-zero/core/logx"
)
type GetFriendVerifiesListByIdsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 批量获取好友验证数据(通过ID)
func NewGetFriendVerifiesListByIdsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFriendVerifiesListByIdsLogic {
return &GetFriendVerifiesListByIdsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetFriendVerifiesListByIdsLogic) GetFriendVerifiesListByIds(req *types.GetFriendVerifiesListByIdsReq) (resp *types.GetFriendVerifiesListByIdsRes, err error) {
if len(req.VerifyIds) == 0 {
return &types.GetFriendVerifiesListByIdsRes{
FriendVerifies: []types.FriendVerifyById{},
}, nil
}
// 查询指定ID列表中的好友验证信息
var friendVerifies []friend_models.FriendVerifyModel
err = l.svcCtx.DB.Where("verify_id IN (?)", req.VerifyIds).Find(&friendVerifies).Error
if err != nil {
l.Errorf("查询好友验证信息失败: ids=%v, error=%v", req.VerifyIds, err)
return nil, err
}
l.Infof("查询到 %d 个好友验证信息", len(friendVerifies))
// 转换为响应格式
var friendVerifiesList []types.FriendVerifyById
for _, verify := range friendVerifies {
friendVerifiesList = append(friendVerifiesList, types.FriendVerifyById{
VerifyID: verify.VerifyID,
SendUserID: verify.SendUserID,
RevUserID: verify.RevUserID,
SendStatus: int32(verify.SendStatus),
RevStatus: int32(verify.RevStatus),
Message: verify.Message,
Source: verify.Source,
Version: verify.Version,
CreatedAt: time.Time(verify.CreatedAt).UnixMilli(),
UpdatedAt: time.Time(verify.UpdatedAt).UnixMilli(),
})
}
return &types.GetFriendVerifiesListByIdsRes{
FriendVerifies: friendVerifiesList,
}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/logic/friendinfologic.go | app/friend/friend_api/internal/logic/friendinfologic.go | package logic
import (
"context"
"errors"
"fmt"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/app/friend/friend_models"
"beaver/app/user/user_rpc/types/user_rpc"
"beaver/utils/conversation"
"github.com/zeromicro/go-zero/core/logx"
)
type FriendInfoLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewFriendInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FriendInfoLogic {
return &FriendInfoLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *FriendInfoLogic) FriendInfo(req *types.FriendInfoReq) (resp *types.FriendInfoRes, err error) {
// 参数验证
if req.FriendID == "" {
return nil, errors.New("好友ID不能为空")
}
// 不能查询自己的信息
if req.UserID == req.FriendID {
return nil, errors.New("不能查询自己的信息")
}
var friend friend_models.FriendModel
// 通过RPC获取用户信息
res, err := l.svcCtx.UserRpc.UserInfo(l.ctx, &user_rpc.UserInfoReq{
UserID: req.FriendID,
})
if err != nil {
l.Logger.Errorf("获取用户信息失败: friendID=%s, error=%v", req.FriendID, err)
return nil, errors.New("用户不存在")
}
friendUser := res.UserInfo
// 生成会话Id
conversationID, err := conversation.GenerateConversation([]string{req.UserID, req.FriendID})
if err != nil {
l.Logger.Errorf("生成会话Id失败: %v", err)
return nil, fmt.Errorf("生成会话Id失败: %v", err)
}
// 检查是否为好友
isFriend := friend.IsFriend(l.svcCtx.DB, req.UserID, req.FriendID)
// 获取好友备注和来源
var notice string
var source string
if isFriend {
var friendModel friend_models.FriendModel
err = l.svcCtx.DB.Take(&friendModel,
"(send_user_id = ? AND rev_user_id = ?) OR (send_user_id = ? AND rev_user_id = ?)",
req.UserID, req.FriendID, req.FriendID, req.UserID).Error
if err == nil {
// 根据好友关系的方向确定备注
if friendModel.SendUserID == req.UserID {
// 当前用户是发送方,使用发送方的备注
notice = friendModel.SendUserNotice
} else {
// 当前用户是接收方,使用接收方的备注
notice = friendModel.RevUserNotice
}
source = friendModel.Source
}
}
response := &types.FriendInfoRes{
ConversationID: conversationID,
UserID: friendUser.UserId,
NickName: friendUser.NickName,
Avatar: friendUser.Avatar,
Abstract: friendUser.Abstract,
Notice: notice,
IsFriend: isFriend,
Email: friendUser.Email,
Source: source,
}
l.Logger.Infof("获取好友信息成功: userID=%s, friendID=%s, isFriend=%v, source=%s", req.UserID, req.FriendID, isFriend, source)
return response, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/logic/addfriendlogic.go | app/friend/friend_api/internal/logic/addfriendlogic.go | package logic
import (
"context"
"encoding/json"
"errors"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/app/friend/friend_models"
"beaver/app/notification/notification_models"
"beaver/app/notification/notification_rpc/types/notification_rpc"
"beaver/app/user/user_rpc/types/user_rpc"
"beaver/common/ajax"
"beaver/common/wsEnum/wsCommandConst"
"beaver/common/wsEnum/wsTypeConst"
"github.com/google/uuid"
"github.com/zeromicro/go-zero/core/logx"
)
type AddFriendLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAddFriendLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddFriendLogic {
return &AddFriendLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AddFriendLogic) AddFriend(req *types.AddFriendReq) (resp *types.AddFriendRes, err error) {
var friend friend_models.FriendModel
// 检查是否已经是好友
if friend.IsFriend(l.svcCtx.DB, req.UserID, req.FriendID) {
return nil, errors.New("已经是好友了")
}
// 检查目标用户是否存在(通过RPC)
_, err = l.svcCtx.UserRpc.UserInfo(l.ctx, &user_rpc.UserInfoReq{
UserID: req.FriendID,
})
if err != nil {
l.Logger.Errorf("目标用户不存在: friendID=%s, error=%v", req.FriendID, err)
return nil, errors.New("用户不存在")
}
// 检查是否已经有待处理的好友请求
var existingVerify friend_models.FriendVerifyModel
err = l.svcCtx.DB.Take(&existingVerify,
"(send_user_id = ? AND rev_user_id = ? AND rev_status = 0) OR (send_user_id = ? AND rev_user_id = ? AND rev_status = 0)",
req.UserID, req.FriendID, req.FriendID, req.UserID).Error
if err == nil {
l.Logger.Infof("已存在待处理的好友请求: userID=%s, friendID=%s", req.UserID, req.FriendID)
return &types.AddFriendRes{}, nil
}
// 获取下一个版本号
nextVersion := l.svcCtx.VersionGen.GetNextVersion("friend_verify", "", "")
if nextVersion == -1 {
l.Logger.Errorf("获取版本号失败")
return nil, errors.New("系统错误")
}
// 创建好友验证请求
verifyModel := friend_models.FriendVerifyModel{
SendUserID: req.UserID,
RevUserID: req.FriendID,
Message: req.Verify,
Source: req.Source, // 添加来源字段
Version: nextVersion,
VerifyID: uuid.New().String(),
}
err = l.svcCtx.DB.Create(&verifyModel).Error
if err != nil {
l.Logger.Errorf("创建好友验证请求失败: %v", err)
return nil, errors.New("添加好友请求失败")
}
// 异步发送WebSocket通知给发送方和接收方
go func() {
defer func() {
if r := recover(); r != nil {
l.Logger.Errorf("异步发送WebSocket消息时发生panic: %v", r)
}
}()
payload, _ := json.Marshal(map[string]interface{}{
"verifyId": verifyModel.VerifyID,
"message": verifyModel.Message,
"source": verifyModel.Source,
})
_, err := l.svcCtx.NotifyRpc.PushEvent(context.Background(), ¬ification_rpc.PushEventReq{
EventType: notification_models.EventTypeFriendRequest,
Category: notification_models.CategorySocial,
FromUserId: req.UserID,
TargetId: verifyModel.VerifyID,
TargetType: notification_models.TargetTypeUser,
PayloadJson: string(payload),
ToUserIds: []string{req.FriendID},
DedupHash: verifyModel.VerifyID,
})
if err != nil {
l.Logger.Errorf("投递好友申请通知失败: %v", err)
}
// 获取发送者和接收者的用户信息
senderInfo, senderErr := l.svcCtx.UserRpc.UserInfo(context.Background(), &user_rpc.UserInfoReq{
UserID: req.UserID,
})
if senderErr != nil {
l.Logger.Errorf("获取发送者用户信息失败: %v", senderErr)
}
receiverInfo, receiverErr := l.svcCtx.UserRpc.UserInfo(context.Background(), &user_rpc.UserInfoReq{
UserID: req.FriendID,
})
if receiverErr != nil {
l.Logger.Errorf("获取接收者用户信息失败: %v", receiverErr)
}
// 构建好友验证表更新数据
verifyUpdates := map[string]interface{}{
"table": "friend_verify",
"data": []map[string]interface{}{
{
"version": nextVersion,
"verifyId": verifyModel.VerifyID,
},
},
}
// 构建用户表更新数据数组
var userUpdates []map[string]interface{}
if senderInfo != nil {
userUpdates = append(userUpdates, map[string]interface{}{
"table": "users",
"data": []map[string]interface{}{
{
"userId": senderInfo.UserInfo.UserId,
"version": senderInfo.UserInfo.Version,
},
},
})
}
if receiverInfo != nil {
userUpdates = append(userUpdates, map[string]interface{}{
"table": "users",
"data": []map[string]interface{}{
{
"userId": senderInfo.UserInfo.UserId,
"version": senderInfo.UserInfo.Version,
},
},
})
}
// 合并所有表更新
tableUpdates := append([]map[string]interface{}{verifyUpdates}, userUpdates...)
// 通知接收方
ajax.SendMessageToWs(l.svcCtx.Config.Etcd, wsCommandConst.FRIEND_OPERATION, wsTypeConst.FriendVerifyReceive, req.UserID, req.FriendID, map[string]interface{}{
"tableUpdates": tableUpdates,
}, "")
// 通知发送方
ajax.SendMessageToWs(l.svcCtx.Config.Etcd, wsCommandConst.FRIEND_OPERATION, wsTypeConst.FriendVerifyReceive, req.FriendID, req.UserID, map[string]interface{}{
"tableUpdates": tableUpdates,
}, "")
l.Logger.Infof("异步发送好友验证请求通知完成: sender=%s, receiver=%s, version=%d, verifyId=%s", req.UserID, req.FriendID, nextVersion, verifyModel.VerifyID)
}()
l.Logger.Infof("好友请求发送成功: userID=%s, friendID=%s, source=%s", req.UserID, req.FriendID, req.Source)
resp = &types.AddFriendRes{
Version: nextVersion,
}
return resp, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/logic/validlistlogic.go | app/friend/friend_api/internal/logic/validlistlogic.go | package logic
import (
"context"
"errors"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/app/friend/friend_models"
"beaver/app/user/user_rpc/types/user_rpc"
"beaver/common/list_query"
"beaver/common/models"
"github.com/zeromicro/go-zero/core/logx"
)
type ValidListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewValidListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ValidListLogic {
return &ValidListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ValidListLogic) ValidList(req *types.ValidListReq) (resp *types.ValidListRes, err error) {
// 参数验证
if req.UserID == "" {
return nil, errors.New("用户ID不能为空")
}
// 设置默认分页参数
if req.Page <= 0 {
req.Page = 1
}
if req.Limit <= 0 {
req.Limit = 20
}
// 查询好友验证列表
fvs, count, _ := list_query.ListQuery(l.svcCtx.DB, friend_models.FriendVerifyModel{}, list_query.Option{
PageInfo: models.PageInfo{
Page: req.Page,
Limit: req.Limit,
Sort: "created_at desc",
},
Where: l.svcCtx.DB.Where("send_user_id = ? or rev_user_id = ?", req.UserID, req.UserID),
// 移除Preload,微服务架构中通过RPC获取用户信息
})
// 收集需要获取用户信息的UserID列表
var userIds []string
userIdSet := make(map[string]bool)
for _, fv := range fvs {
if fv.SendUserID != "" && !userIdSet[fv.SendUserID] {
userIds = append(userIds, fv.SendUserID)
userIdSet[fv.SendUserID] = true
}
if fv.RevUserID != "" && !userIdSet[fv.RevUserID] {
userIds = append(userIds, fv.RevUserID)
userIdSet[fv.RevUserID] = true
}
}
// 批量获取用户信息
userInfoMap := make(map[string]*user_rpc.UserInfo)
if len(userIds) > 0 {
userListResp, err := l.svcCtx.UserRpc.UserListInfo(l.ctx, &user_rpc.UserListInfoReq{
UserIdList: userIds,
})
if err != nil {
l.Logger.Errorf("批量获取用户信息失败: %v", err)
// 不返回错误,继续处理,为没有用户信息的设置默认值
} else {
userInfoMap = userListResp.UserInfo
}
}
var list []types.FriendValidInfo
for _, fv := range fvs {
info := types.FriendValidInfo{
Message: fv.Message,
Id: fv.VerifyID,
Source: fv.Source,
CreatedAt: fv.CreatedAt.String(),
}
if fv.SendUserID == req.UserID {
// 我是发起方
info.UserID = fv.RevUserID
if userInfo, exists := userInfoMap[fv.RevUserID]; exists && userInfo != nil {
info.NickName = userInfo.NickName
info.Avatar = userInfo.Avatar
} else {
info.NickName = "未知用户"
info.Avatar = ""
}
info.Flag = "send"
info.Status = fv.RevStatus
} else if fv.RevUserID == req.UserID {
// 我是接收方
info.UserID = fv.SendUserID
if userInfo, exists := userInfoMap[fv.SendUserID]; exists && userInfo != nil {
info.NickName = userInfo.NickName
info.Avatar = userInfo.Avatar
} else {
info.NickName = "未知用户"
info.Avatar = ""
}
info.Flag = "receive"
info.Status = fv.RevStatus
} else {
// 这种情况理论上不应该发生,跳过
continue
}
list = append(list, info)
}
l.Logger.Infof("获取好友验证列表成功: userID=%s, count=%d", req.UserID, len(list))
return &types.ValidListRes{
Count: count,
List: list,
}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/logic/searchlogic.go | app/friend/friend_api/internal/logic/searchlogic.go | package logic
import (
"context"
"errors"
"fmt"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/app/friend/friend_models"
"beaver/app/user/user_rpc/types/user_rpc"
"beaver/utils/conversation"
"github.com/zeromicro/go-zero/core/logx"
)
type SearchLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchLogic {
return &SearchLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SearchLogic) Search(req *types.SearchReq) (resp *types.SearchRes, err error) {
// 参数验证
if req.Keyword == "" {
return nil, errors.New("搜索关键词不能为空")
}
var userInfo *user_rpc.UserInfo
var userId string
// 根据搜索类型查询用户信息
switch req.Type {
case "email":
// 根据邮箱查询
searchResp, err := l.svcCtx.UserRpc.SearchUser(l.ctx, &user_rpc.SearchUserReq{
Keyword: req.Keyword,
Type: "email",
})
if err != nil {
l.Logger.Errorf("根据邮箱查询用户失败: email=%s, error=%v", req.Keyword, err)
return nil, errors.New("用户不存在")
}
if searchResp.UserInfo == nil {
l.Logger.Errorf("根据邮箱查询用户失败: email=%s, 未找到用户", req.Keyword)
return nil, errors.New("用户不存在")
}
userInfo = searchResp.UserInfo
userId = userInfo.UserId
case "userId":
// 根据用户ID查询
searchResp, err := l.svcCtx.UserRpc.SearchUser(l.ctx, &user_rpc.SearchUserReq{
Keyword: req.Keyword,
Type: "userId",
})
if err != nil {
l.Logger.Errorf("根据用户ID查询用户失败: userId=%s, error=%v", req.Keyword, err)
return nil, errors.New("用户不存在")
}
if searchResp.UserInfo == nil {
l.Logger.Errorf("根据用户ID查询用户失败: userId=%s, 未找到用户", req.Keyword)
return nil, errors.New("用户不存在")
}
userInfo = searchResp.UserInfo
userId = userInfo.UserId
default:
// 默认按邮箱搜索
searchResp, err := l.svcCtx.UserRpc.SearchUser(l.ctx, &user_rpc.SearchUserReq{
Keyword: req.Keyword,
Type: "email",
})
if err != nil {
l.Logger.Errorf("根据邮箱查询用户失败: email=%s, error=%v", req.Keyword, err)
return nil, errors.New("用户不存在")
}
if searchResp.UserInfo == nil {
l.Logger.Errorf("根据邮箱查询用户失败: email=%s, 未找到用户", req.Keyword)
return nil, errors.New("用户不存在")
}
userInfo = searchResp.UserInfo
userId = userInfo.UserId
}
// 获取完整的用户信息(包括Abstract字段)
userInfoResp, err := l.svcCtx.UserRpc.UserInfo(l.ctx, &user_rpc.UserInfoReq{
UserID: userId,
})
if err != nil {
l.Logger.Errorf("获取用户详细信息失败: userID=%s, error=%v", userId, err)
return nil, errors.New("获取用户详细信息失败")
}
userDetail := userInfoResp.UserInfo
// 不能搜索自己
if req.UserID == userInfo.UserId {
return nil, errors.New("不能搜索自己")
}
// 获取好友关系
var friend friend_models.FriendModel
isFriend := friend.IsFriend(l.svcCtx.DB, req.UserID, userInfo.UserId)
// 生成会话Id
conversationID, err := conversation.GenerateConversation([]string{req.UserID, userInfo.UserId})
if err != nil {
l.Logger.Errorf("生成会话Id失败: %v", err)
return nil, fmt.Errorf("生成会话Id失败: %v", err)
}
// 构造返回值
resp = &types.SearchRes{
UserID: userInfo.UserId,
NickName: userInfo.NickName,
Avatar: userInfo.Avatar,
Abstract: userDetail.Abstract,
IsFriend: isFriend,
ConversationID: conversationID,
Email: userDetail.Email,
}
l.Logger.Infof("搜索用户成功: userID=%s, keyword=%s, type=%s, isFriend=%v", req.UserID, req.Keyword, req.Type, isFriend)
return resp, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/logic/friendlistlogic.go | app/friend/friend_api/internal/logic/friendlistlogic.go | package logic
import (
"context"
"errors"
"fmt"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/app/friend/friend_models"
"beaver/app/user/user_rpc/types/user_rpc"
"beaver/common/list_query"
"beaver/common/models"
"beaver/utils/conversation"
"github.com/zeromicro/go-zero/core/logx"
)
type FriendListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewFriendListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FriendListLogic {
return &FriendListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *FriendListLogic) FriendList(req *types.FriendListReq) (resp *types.FriendListRes, err error) {
// 参数验证
if req.UserID == "" {
return nil, errors.New("用户ID不能为空")
}
// 设置默认分页参数
if req.Page <= 0 {
req.Page = 1
}
if req.Limit <= 0 {
req.Limit = 20
}
// 查询好友列表
friends, _, _ := list_query.ListQuery(l.svcCtx.DB, friend_models.FriendModel{}, list_query.Option{
PageInfo: models.PageInfo{
Page: req.Page,
Limit: req.Limit,
},
Where: l.svcCtx.DB.Where("(send_user_id = ? OR rev_user_id = ?) AND is_deleted = ?", req.UserID, req.UserID, false),
// 移除Preload,微服务架构中通过RPC获取用户信息
})
// 收集需要获取用户信息的UserID列表
var userIds []string
userIdSet := make(map[string]bool)
for _, friendUser := range friends {
if friendUser.SendUserID != "" && !userIdSet[friendUser.SendUserID] {
userIds = append(userIds, friendUser.SendUserID)
userIdSet[friendUser.SendUserID] = true
}
if friendUser.RevUserID != "" && !userIdSet[friendUser.RevUserID] {
userIds = append(userIds, friendUser.RevUserID)
userIdSet[friendUser.RevUserID] = true
}
}
// 批量获取用户信息
userInfoMap := make(map[string]*user_rpc.UserInfo)
if len(userIds) > 0 {
userListResp, err := l.svcCtx.UserRpc.UserListInfo(l.ctx, &user_rpc.UserListInfoReq{
UserIdList: userIds,
})
if err != nil {
l.Logger.Errorf("批量获取用户信息失败: %v", err)
// 不返回错误,继续处理,为没有用户信息的设置默认值
} else {
userInfoMap = userListResp.UserInfo
}
}
var list []types.FriendInfoRes
for _, friendUser := range friends {
var targetUserID string
var notice string
// 确定目标用户ID和备注信息
if friendUser.SendUserID == req.UserID {
// 我是发起方,目标用户是接收方
targetUserID = friendUser.RevUserID
notice = friendUser.SendUserNotice
} else if friendUser.RevUserID == req.UserID {
// 我是接收方,目标用户是发起方
targetUserID = friendUser.SendUserID
notice = friendUser.RevUserNotice
} else {
// 这种情况理论上不应该发生,跳过
continue
}
// 获取用户信息
var nickName, avatar, abstract, email string
if userInfo, exists := userInfoMap[targetUserID]; exists && userInfo != nil {
nickName = userInfo.NickName
avatar = userInfo.Avatar
email = userInfo.Email
// 获取完整的用户信息(包括Abstract字段)
userDetailResp, err := l.svcCtx.UserRpc.UserInfo(l.ctx, &user_rpc.UserInfoReq{
UserID: targetUserID,
})
if err == nil {
abstract = userDetailResp.UserInfo.Abstract
} else {
abstract = ""
}
} else {
nickName = "未知用户"
avatar = ""
abstract = ""
email = ""
}
// 生成会话Id
conversationID, err := conversation.GenerateConversation([]string{req.UserID, targetUserID})
if err != nil {
l.Logger.Errorf("生成会话Id失败: userID=%s, targetID=%s, error=%v", req.UserID, targetUserID, err)
return nil, fmt.Errorf("生成会话Id失败: %v", err)
}
// 构造好友信息
info := types.FriendInfoRes{
UserID: targetUserID,
NickName: nickName,
Avatar: avatar,
Abstract: abstract,
Notice: notice,
ConversationID: conversationID,
Email: email,
}
list = append(list, info)
}
l.Logger.Infof("获取好友列表成功: userID=%s, count=%d", req.UserID, len(list))
return &types.FriendListRes{
List: list,
}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/logic/searchvalidinfologic.go | app/friend/friend_api/internal/logic/searchvalidinfologic.go | package logic
import (
"context"
"errors"
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/app/friend/friend_models"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
)
type SearchValidInfoLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSearchValidInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchValidInfoLogic {
return &SearchValidInfoLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SearchValidInfoLogic) SearchValidInfo(req *types.SearchValidInfoReq) (resp *types.SearchValidInfoRes, err error) {
// 参数验证
if req.UserID == "" || req.FriendID == "" {
return nil, errors.New("用户ID和好友ID不能为空")
}
// 不能查询自己
if req.UserID == req.FriendID {
return nil, errors.New("不能查询自己")
}
var friendVerify friend_models.FriendVerifyModel
// 查询好友验证记录
err = l.svcCtx.DB.Where(
"(rev_user_id = ? and send_user_id = ?) or (rev_user_id = ? and send_user_id = ?)",
req.UserID, req.FriendID, req.FriendID, req.UserID,
).First(&friendVerify).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
l.Logger.Infof("好友验证记录不存在: userID=%s, friendID=%s", req.UserID, req.FriendID)
return nil, errors.New("好友验证不存在")
}
l.Logger.Errorf("查询好友验证记录失败: %v", err)
return nil, errors.New("查询好友验证记录失败")
}
// 检查验证状态
if friendVerify.RevStatus != 0 {
l.Logger.Errorf("好友验证已处理: verifyID=%s, status=%d", friendVerify.VerifyID, friendVerify.RevStatus)
return nil, errors.New("该验证已处理,无法重复操作")
}
// 填充返回结果
resp = &types.SearchValidInfoRes{
ValidID: friendVerify.VerifyID, // 返回验证记录ID
}
l.Logger.Infof("查询好友验证信息成功: userID=%s, friendID=%s, validID=%s", req.UserID, req.FriendID, friendVerify.VerifyID)
return resp, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/app/friend/friend_api/internal/logic/getfriendslistbyuuidslogic.go | app/friend/friend_api/internal/logic/getfriendslistbyuuidslogic.go | package logic
import (
"beaver/app/friend/friend_api/internal/svc"
"beaver/app/friend/friend_api/internal/types"
"beaver/app/friend/friend_models"
"context"
"time"
"github.com/zeromicro/go-zero/core/logx"
)
type GetFriendsListByUuidsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 批量获取好友数据(通过ID)
func NewGetFriendsListByUuidsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFriendsListByUuidsLogic {
return &GetFriendsListByUuidsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetFriendsListByUuidsLogic) GetFriendsListByUuids(req *types.GetFriendsListByUuidsReq) (resp *types.GetFriendsListByUuidsRes, err error) {
if len(req.FriendIds) == 0 {
return &types.GetFriendsListByUuidsRes{
Friends: []types.FriendByUuid{},
}, nil
}
// 查询指定ID列表中的好友信息
var friends []friend_models.FriendModel
err = l.svcCtx.DB.Where("friend_id IN (?)", req.FriendIds).Find(&friends).Error
if err != nil {
l.Errorf("查询好友信息失败: ids=%v, error=%v", req.FriendIds, err)
return nil, err
}
l.Infof("查询到 %d 个好友信息", len(friends))
// 转换为响应格式
var friendsList []types.FriendByUuid
for _, friend := range friends {
l.Infof("处理好友: ID=%s, SendUserID=%s, RevUserID=%s", friend.FriendID, friend.SendUserID, friend.RevUserID)
friendsList = append(friendsList, types.FriendByUuid{
FriendID: friend.FriendID,
SendUserID: friend.SendUserID,
RevUserID: friend.RevUserID,
SendUserNotice: friend.SendUserNotice,
RevUserNotice: friend.RevUserNotice,
Source: friend.Source,
IsDeleted: friend.IsDeleted,
Version: friend.Version,
CreatedAt: time.Time(friend.CreatedAt).UnixMilli(),
UpdatedAt: time.Time(friend.UpdatedAt).UnixMilli(),
})
}
return &types.GetFriendsListByUuidsRes{
Friends: friendsList,
}, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/array.go | utils/array.go | package utils
import (
"fmt"
"regexp"
"github.com/zeromicro/go-zero/core/logx"
)
func InListByRegex(list []string, key string) (ok bool) {
for _, s := range list {
regex, err := regexp.Compile(s)
if err != nil {
logx.Errorf("compile regex error: %v", err)
return
}
fmt.Println(key, s)
if regex.MatchString(key) {
return true
}
}
return false
}
func InList(list []string, key string) bool {
for _, i := range list {
if i == key {
return true
}
}
return false
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/md5/enter.go | utils/md5/enter.go | package md5
import (
"crypto/md5"
"encoding/hex"
)
func MD5(data []byte) string {
h := md5.New()
h.Write(data)
cipherStr := h.Sum(nil)
return hex.EncodeToString(cipherStr)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/device/device.go | utils/device/device.go | package device
import (
"strings"
)
// 根据User-Agent识别设备类型
func GetDeviceType(userAgent string) string {
userAgent = strings.ToLower(userAgent)
// 识别桌面端
if strings.Contains(userAgent, "beaver_desktop_windows") {
return "desktop"
} else if strings.Contains(userAgent, "beaver_desktop_macos") {
return "desktop"
} else if strings.Contains(userAgent, "beaver_desktop_linux") {
return "desktop"
}
// 识别移动端
if strings.Contains(userAgent, "beaver_mobile_android") {
return "mobile"
} else if strings.Contains(userAgent, "beaver_mobile_ios") {
return "mobile"
} else if strings.Contains(userAgent, "beaver_mobile_harmonyos") {
return "mobile"
}
// 不是桌面端和移动端的,剩下的都是web端
return "web"
}
// 验证设备ID格式
func IsValidDeviceID(deviceID string) bool {
if deviceID == "" || len(deviceID) < 8 || len(deviceID) > 64 {
return false
}
return true
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/pwd/enter.go | utils/pwd/enter.go | package pwd
import (
"fmt"
"log"
"golang.org/x/crypto/bcrypt"
)
func HahPwd(pwd string) string {
hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
if err != nil {
log.Println(err)
}
return string(hash)
}
func CheckPad(hashPad string, pwd string) bool {
byteHash := []byte(hashPad)
err := bcrypt.CompareHashAndPassword(byteHash, []byte(pwd))
if err != nil {
fmt.Println("11111111111111111111111111111111", hashPad, pwd)
log.Println(err)
return false
}
return true
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/uuid/uuid.go | utils/uuid/uuid.go | // Copyright (C) 2013-2015 by Maxim Bublis <b@codemonkey.ru>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package uuid provides implementation of Universally Unique Identifier (UUID).
// Supported versions are 1, 3, 4 and 5 (as specified in RFC 4122) and
// version 2 (as specified in DCE 1.1).
package util
import (
"bytes"
"crypto/md5"
"crypto/rand"
"crypto/sha1"
"database/sql/driver"
"encoding/binary"
"encoding/hex"
"fmt"
"hash"
"net"
"os"
"sync"
"time"
)
// UUID layout variants.
const (
VariantNCS = iota
VariantRFC4122
VariantMicrosoft
VariantFuture
)
// UUID DCE domains.
const (
DomainPerson = iota
DomainGroup
DomainOrg
)
// Difference in 100-nanosecond intervals between
// UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).
const epochStart = 122192928000000000
// Used in string method conversion
const dash byte = '-'
// UUID v1/v2 storage.
var (
storageMutex sync.Mutex
storageOnce sync.Once
epochFunc = unixTimeFunc
clockSequence uint16
lastTime uint64
hardwareAddr [6]byte
posixUID = uint32(os.Getuid())
posixGID = uint32(os.Getgid())
)
// String parse helpers.
var (
urnPrefix = []byte("urn:uuid:")
byteGroups = []int{8, 4, 4, 4, 12}
)
func initClockSequence() {
buf := make([]byte, 2)
safeRandom(buf)
clockSequence = binary.BigEndian.Uint16(buf)
}
func initHardwareAddr() {
interfaces, err := net.Interfaces()
if err == nil {
for _, iface := range interfaces {
if len(iface.HardwareAddr) >= 6 {
copy(hardwareAddr[:], iface.HardwareAddr)
return
}
}
}
// Initialize hardwareAddr randomly in case
// of real network interfaces absence
safeRandom(hardwareAddr[:])
// Set multicast bit as recommended in RFC 4122
hardwareAddr[0] |= 0x01
}
func initStorage() {
initClockSequence()
initHardwareAddr()
}
func safeRandom(dest []byte) {
if _, err := rand.Read(dest); err != nil {
panic(err)
}
}
// Returns difference in 100-nanosecond intervals between
// UUID epoch (October 15, 1582) and current time.
// This is default epoch calculation function.
func unixTimeFunc() uint64 {
return epochStart + uint64(time.Now().UnixNano()/100)
}
// UUID representation compliant with specification
// described in RFC 4122.
type UUID [16]byte
// NullUUID can be used with the standard sql package to represent a
// UUID value that can be NULL in the database
type NullUUID struct {
UUID UUID
Valid bool
}
// The nil UUID is special form of UUID that is specified to have all
// 128 bits set to zero.
var Nil = UUID{}
// Predefined namespace UUIDs.
var (
NamespaceDNS, _ = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
NamespaceURL, _ = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
NamespaceOID, _ = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
)
// And returns result of binary AND of two UUIDs.
func And(u1 UUID, u2 UUID) UUID {
u := UUID{}
for i := 0; i < 16; i++ {
u[i] = u1[i] & u2[i]
}
return u
}
// Or returns result of binary OR of two UUIDs.
func Or(u1 UUID, u2 UUID) UUID {
u := UUID{}
for i := 0; i < 16; i++ {
u[i] = u1[i] | u2[i]
}
return u
}
// Equal returns true if u1 and u2 equals, otherwise returns false.
func Equal(u1 UUID, u2 UUID) bool {
return bytes.Equal(u1[:], u2[:])
}
// Version returns algorithm version used to generate UUID.
func (u UUID) Version() uint {
return uint(u[6] >> 4)
}
// Variant returns UUID layout variant.
func (u UUID) Variant() uint {
switch {
case (u[8] & 0x80) == 0x00:
return VariantNCS
case (u[8]&0xc0)|0x80 == 0x80:
return VariantRFC4122
case (u[8]&0xe0)|0xc0 == 0xc0:
return VariantMicrosoft
}
return VariantFuture
}
// Bytes returns bytes slice representation of UUID.
func (u UUID) Bytes() []byte {
return u[:]
}
// Returns canonical string representation of UUID:
// 上海信必达网络科技有限公司-xxxx-xxxx-xxxx-上海信必达网络科技有限公司xxxx.
func (u UUID) String() string {
buf := make([]byte, 36)
hex.Encode(buf[0:8], u[0:4])
buf[8] = dash
hex.Encode(buf[9:13], u[4:6])
buf[13] = dash
hex.Encode(buf[14:18], u[6:8])
buf[18] = dash
hex.Encode(buf[19:23], u[8:10])
buf[23] = dash
hex.Encode(buf[24:], u[10:])
return string(buf)
}
// SetVersion sets version bits.
func (u *UUID) SetVersion(v byte) {
u[6] = (u[6] & 0x0f) | (v << 4)
}
// SetVariant sets variant bits as described in RFC 4122.
func (u *UUID) SetVariant() {
u[8] = (u[8] & 0xbf) | 0x80
}
// MarshalText implements the encoding.TextMarshaler interface.
// The encoding is the same as returned by String.
func (u UUID) MarshalText() (text []byte, err error) {
text = []byte(u.String())
return
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
// Following formats are supported:
// "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
// "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
// "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
func (u *UUID) UnmarshalText(text []byte) (err error) {
if len(text) < 32 {
err = fmt.Errorf("uuid: UUID string too short: %s", text)
return
}
t := text[:]
braced := false
if bytes.Equal(t[:9], urnPrefix) {
t = t[9:]
} else if t[0] == '{' {
braced = true
t = t[1:]
}
b := u[:]
for i, byteGroup := range byteGroups {
if i > 0 {
if t[0] != '-' {
err = fmt.Errorf("uuid: invalid string format")
return
}
t = t[1:]
}
if len(t) < byteGroup {
err = fmt.Errorf("uuid: UUID string too short: %s", text)
return
}
if i == 4 && len(t) > byteGroup &&
((braced && t[byteGroup] != '}') || len(t[byteGroup:]) > 1 || !braced) {
err = fmt.Errorf("uuid: UUID string too long: %s", text)
return
}
_, err = hex.Decode(b[:byteGroup/2], t[:byteGroup])
if err != nil {
return
}
t = t[byteGroup:]
b = b[byteGroup/2:]
}
return
}
// MarshalBinary implements the encoding.BinaryMarshaler interface.
func (u UUID) MarshalBinary() (data []byte, err error) {
data = u.Bytes()
return
}
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
// It will return error if the slice isn't 16 bytes long.
func (u *UUID) UnmarshalBinary(data []byte) (err error) {
if len(data) != 16 {
err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))
return
}
copy(u[:], data)
return
}
// Value implements the driver.Valuer interface.
func (u UUID) Value() (driver.Value, error) {
return u.String(), nil
}
// Scan implements the sql.Scanner interface.
// A 16-byte slice is handled by UnmarshalBinary, while
// a longer byte slice or a string is handled by UnmarshalText.
func (u *UUID) Scan(src interface{}) error {
switch src := src.(type) {
case []byte:
if len(src) == 16 {
return u.UnmarshalBinary(src)
}
return u.UnmarshalText(src)
case string:
return u.UnmarshalText([]byte(src))
}
return fmt.Errorf("uuid: cannot convert %T to UUID", src)
}
// Value implements the driver.Valuer interface.
func (u NullUUID) Value() (driver.Value, error) {
if !u.Valid {
return nil, nil
}
// Delegate to UUID Value function
return u.UUID.Value()
}
// Scan implements the sql.Scanner interface.
func (u *NullUUID) Scan(src interface{}) error {
if src == nil {
u.UUID, u.Valid = Nil, false
return nil
}
// Delegate to UUID Scan function
u.Valid = true
return u.UUID.Scan(src)
}
// FromBytes returns UUID converted from raw byte slice input.
// It will return error if the slice isn't 16 bytes long.
func FromBytes(input []byte) (u UUID, err error) {
err = u.UnmarshalBinary(input)
return
}
// FromBytesOrNil returns UUID converted from raw byte slice input.
// Same behavior as FromBytes, but returns a Nil UUID on error.
func FromBytesOrNil(input []byte) UUID {
uuid, err := FromBytes(input)
if err != nil {
return Nil
}
return uuid
}
// FromString returns UUID parsed from string input.
// Input is expected in a form accepted by UnmarshalText.
func FromString(input string) (u UUID, err error) {
err = u.UnmarshalText([]byte(input))
return
}
// FromStringOrNil returns UUID parsed from string input.
// Same behavior as FromString, but returns a Nil UUID on error.
func FromStringOrNil(input string) UUID {
uuid, err := FromString(input)
if err != nil {
return Nil
}
return uuid
}
// Returns UUID v1/v2 storage state.
// Returns epoch timestamp, clock sequence, and hardware address.
func getStorage() (uint64, uint16, []byte) {
storageOnce.Do(initStorage)
storageMutex.Lock()
defer storageMutex.Unlock()
timeNow := epochFunc()
// Clock changed backwards since last UUID generation.
// Should increase clock sequence.
if timeNow <= lastTime {
clockSequence++
}
lastTime = timeNow
return timeNow, clockSequence, hardwareAddr[:]
}
// NewV1 returns UUID based on current timestamp and MAC address.
func NewV1() UUID {
u := UUID{}
timeNow, clockSeq, hardwareAddr := getStorage()
binary.BigEndian.PutUint32(u[0:], uint32(timeNow))
binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
binary.BigEndian.PutUint16(u[8:], clockSeq)
copy(u[10:], hardwareAddr)
u.SetVersion(1)
u.SetVariant()
return u
}
// NewV2 returns DCE Security UUID based on POSIX UID/GID.
func NewV2(domain byte) UUID {
u := UUID{}
timeNow, clockSeq, hardwareAddr := getStorage()
switch domain {
case DomainPerson:
binary.BigEndian.PutUint32(u[0:], posixUID)
case DomainGroup:
binary.BigEndian.PutUint32(u[0:], posixGID)
}
binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
binary.BigEndian.PutUint16(u[8:], clockSeq)
u[9] = domain
copy(u[10:], hardwareAddr)
u.SetVersion(2)
u.SetVariant()
return u
}
// NewV3 returns UUID based on MD5 hash of namespace UUID and name.
func NewV3(ns UUID, name string) UUID {
u := newFromHash(md5.New(), ns, name)
u.SetVersion(3)
u.SetVariant()
return u
}
// NewV4 returns random generated UUID.
func NewV4() UUID {
u := UUID{}
safeRandom(u[:])
u.SetVersion(4)
u.SetVariant()
return u
}
// NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.
func NewV5(ns UUID, name string) UUID {
u := newFromHash(sha1.New(), ns, name)
u.SetVersion(5)
u.SetVariant()
return u
}
// Returns UUID based on hashing of namespace UUID and name.
func newFromHash(h hash.Hash, ns UUID, name string) UUID {
u := UUID{}
h.Write(ns[:])
h.Write([]byte(name))
copy(u[:], h.Sum(nil))
return u
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/maps/ref_to_map.go | utils/maps/ref_to_map.go | package maps
import "reflect"
func RefToMap(data any, tag string) map[string]any {
maps := map[string]any{}
t := reflect.TypeOf(data)
v := reflect.ValueOf(data)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
getTag, ok := field.Tag.Lookup(tag)
if !ok {
continue
}
val := v.Field(i)
if val.IsZero() {
continue
}
if field.Type.Kind() == reflect.Ptr {
if field.Type.Elem().Kind() == reflect.Struct {
newMaps := RefToMap(val.Elem().Interface(), tag)
maps[getTag] = newMaps
} else {
maps[getTag] = val.Elem().Interface()
}
} else {
maps[getTag] = val.Interface()
}
}
return maps
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/jwts/enter.go | utils/jwts/enter.go | package jwts
import (
"time"
"github.com/golang-jwt/jwt/v4"
)
type JwtPayLoad struct {
NickName string `json:"nickName"`
UserID string `json:"userId"`
}
type CustomClaims struct {
JwtPayLoad
jwt.RegisteredClaims
}
func GenToken(payload JwtPayLoad, accessSecret string, expires int) (string, error) {
claims := CustomClaims{
JwtPayLoad: payload,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * time.Duration(expires))),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(accessSecret))
}
func ParseToken(tokenStr string, accessSecret string) (*CustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenStr, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(accessSecret), nil
})
if err != nil {
return nil, err
}
if clains, ok := token.Claims.(*CustomClaims); ok && token.Valid {
return clains, nil
}
return nil, err
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/email/email.go | utils/email/email.go | package email
import (
"fmt"
"regexp"
"strings"
utils "beaver/utils/rand"
)
// 验证邮箱格式
func IsValidEmail(email string) bool {
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
matched, _ := regexp.MatchString(pattern, email)
return matched
}
// 验证验证码类型
func IsValidCodeType(codeType string) bool {
validTypes := []string{"register", "login", "reset_password", "update_email"}
for _, t := range validTypes {
if t == codeType {
return true
}
}
return false
}
// 验证验证码格式(6位纯数字)
func IsValidVerificationCode(code string) bool {
if len(code) != 6 {
return false
}
matched, _ := regexp.MatchString(`^\d{6}$`, code)
return matched
}
// 生成6位数字验证码
func GenerateCode() string {
return utils.GenerateNumericCode(6)
}
// 根据邮箱域名获取邮箱服务商
func GetEmailProvider(email string) string {
parts := strings.Split(email, "@")
if len(parts) != 2 {
return ""
}
domain := strings.ToLower(parts[1])
switch domain {
case "qq.com":
return "QQ"
default:
return ""
}
}
// 获取邮件主题
func GetEmailSubject(codeType string) string {
switch codeType {
case "register":
return "海狸IM - 注册验证码"
case "login":
return "海狸IM - 登录验证码"
case "reset_password":
return "海狸IM - 找回密码验证码"
case "update_email":
return "海狸IM - 修改邮箱验证码"
default:
return "海狸IM - 验证码"
}
}
// 获取邮件内容
func GetEmailBody(code, codeType string) string {
action := ""
switch codeType {
case "register":
action = "注册"
case "login":
action = "登录"
case "reset_password":
action = "找回密码"
case "update_email":
action = "修改邮箱"
default:
action = "验证"
}
return fmt.Sprintf(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>海狸IM验证码</title>
</head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
<div style="max-width: 600px; margin: 0 auto; padding: 20px;">
<h2 style="color: #2c3e50;">海狸IM - %s验证码</h2>
<p>您好!</p>
<p>您正在进行%s操作,验证码如下:</p>
<div style="background-color: #f8f9fa; padding: 15px; border-radius: 5px; text-align: center; margin: 20px 0;">
<h1 style="color: #e74c3c; font-size: 32px; margin: 0; letter-spacing: 5px;">%s</h1>
</div>
<p><strong>验证码有效期:5分钟</strong></p>
<p>如果这不是您的操作,请忽略此邮件。</p>
<hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">
<p style="color: #7f8c8d; font-size: 12px;">
此邮件由海狸IM系统自动发送,请勿回复。<br>
如有疑问,请联系客服。
</p>
</div>
</body>
</html>
`, action, action, code)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/conversation/cities.go | utils/conversation/cities.go | package conversation
// CityData 城市数据
type CityData struct {
Code string `json:"code"`
Name string `json:"name"`
}
// GetDefaultCities 获取默认城市列表
func GetDefaultCities() []CityData {
return []CityData{
{Code: "ALL", Name: "全国"},
{Code: "010", Name: "北京"},
{Code: "021", Name: "上海"},
{Code: "020", Name: "广州"},
{Code: "0755", Name: "深圳"},
{Code: "0571", Name: "杭州"},
{Code: "028", Name: "成都"},
{Code: "027", Name: "武汉"},
{Code: "029", Name: "西安"},
{Code: "025", Name: "南京"},
{Code: "023", Name: "重庆"},
{Code: "022", Name: "天津"},
{Code: "0512", Name: "苏州"},
{Code: "0731", Name: "长沙"},
{Code: "0532", Name: "青岛"},
{Code: "0510", Name: "无锡"},
{Code: "0574", Name: "宁波"},
{Code: "0371", Name: "郑州"},
{Code: "0757", Name: "佛山"},
{Code: "0769", Name: "东莞"},
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/conversation/enter.go | utils/conversation/enter.go | package conversation
import (
"errors"
"sort"
"strings"
)
/**
* @description: 生成会话Id
*/
func GenerateConversation(userIds []string) (string, error) {
if len(userIds) == 1 {
return "private_" + userIds[0], nil
} else if len(userIds) == 2 {
sort.Strings(userIds)
return "private_" + strings.Join(userIds, "_"), nil
} else {
return "", errors.New("userIds must have a length of 1 or 2")
}
}
/**
* @description: 解析会话Id
*/
func ParseConversation(conversationID string) []string {
if strings.Contains(conversationID, "_") {
return strings.Split(conversationID, "_")
}
return []string{conversationID}
}
/**
* @description: 获取会话类型
* @return: 1: 私聊 2: 群聊
*/
func GetConversationType(conversationID string) int {
// 优先检查前缀:group_ 表示群聊,private_ 表示私聊
if strings.HasPrefix(conversationID, "group_") {
return 2
}
if strings.HasPrefix(conversationID, "private_") {
return 1
}
// 如果没有前缀,则根据是否包含下划线判断
// 包含下划线且不是 group_ 或 private_ 前缀的,通常是私聊(userId1_userId2格式)
if strings.Contains(conversationID, "_") {
return 1
}
// 不包含下划线的,通常是群聊(直接是group的UUID)
return 2
}
/**
* @description: 解析会话ID并返回类型和用户IDs
* @return: conversationType (1:私聊 2:群聊), userIds ([]string)
*/
func ParseConversationWithType(conversationID string) (int, []string) {
conversationType := GetConversationType(conversationID)
userIds := ParseConversation(conversationID)
// 对于私聊,如果是带前缀的格式 (private_userId1_userId2),移除前缀
if conversationType == 1 && len(userIds) >= 3 && userIds[0] == "private" {
userIds = userIds[1:]
}
// 对于群聊,如果是带前缀的格式 (group_uuid),移除前缀
if conversationType == 2 && len(userIds) >= 2 && userIds[0] == "group" {
userIds = userIds[1:]
}
return conversationType, userIds
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/utils/rand/rand.go | utils/rand/rand.go | package utils
import (
"math/rand"
"strings"
"github.com/google/uuid"
)
// 生成指定长度的随机字符串
func GenerateUUId() string {
return uuid.New().String()
}
// 随机生成器中的字符集合
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// 生成指定长度的随机字符串
func GenerateRandomString(length int) string {
sb := strings.Builder{}
for i := 0; i < length; i++ {
sb.WriteByte(charset[rand.Intn(len(charset))])
}
return sb.String()
}
// 生成指定长度的数字验证码
func GenerateNumericCode(length int) string {
digits := "0123456789"
sb := strings.Builder{}
for i := 0; i < length; i++ {
sb.WriteByte(digits[rand.Intn(len(digits))])
}
return sb.String()
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/ajax/enter.go | common/ajax/enter.go | package ajax
import (
"beaver/common/etcd"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"beaver/common/wsEnum/wsCommandConst" // Import the wsCommandConst package
"beaver/common/wsEnum/wsTypeConst" // Import the wsCommandConst package
"github.com/zeromicro/go-zero/core/logx"
)
type ForwardRequest struct {
ApiEndpoint string
Method string
Token string
UserID string
Body *bytes.Buffer
}
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Result json.RawMessage `json:"result"`
}
type WsProxyReq struct {
UserID string `header:"Beaver-User-Id"`
Command wsCommandConst.Command `json:"command"`
TargetID string `json:"targetId"`
Type wsTypeConst.Type `json:"type"`
Body map[string]interface{} `json:"body"`
ConversationId string `json:"conversationId"`
}
func SendMessageToWs(etcdUrl string, command wsCommandConst.Command, types wsTypeConst.Type, senderID string, targetID string, requestBody map[string]interface{}, conversationId string) error {
addr := etcd.GetServiceAddr(etcdUrl, "ws_api")
if addr == "" {
return fmt.Errorf("未匹配到服务")
}
apiEndpoint := fmt.Sprintf("http://%s/api/ws/proxySendMsg", addr)
wsProxyReq := WsProxyReq{
UserID: senderID,
Command: command,
TargetID: targetID,
Type: types,
Body: requestBody,
ConversationId: conversationId,
}
fmt.Println("会话id是:", conversationId)
body, _ := json.Marshal(wsProxyReq)
_, err := ForwardMessage(ForwardRequest{
ApiEndpoint: apiEndpoint,
Method: "POST",
Token: "",
UserID: senderID,
Body: bytes.NewBuffer(body),
})
return err
}
func ForwardMessage(forwardReq ForwardRequest) (json.RawMessage, error) {
client := &http.Client{}
var req *http.Request
var err error
// 根据请求方法生成对应的HTTP请求
if forwardReq.Method == "GET" {
req, err = http.NewRequest("GET", forwardReq.ApiEndpoint, nil)
} else if forwardReq.Method == "POST" {
req, err = http.NewRequest("POST", forwardReq.ApiEndpoint, forwardReq.Body)
} else {
return nil, fmt.Errorf("不支持的请求方法: %s", forwardReq.Method)
}
if err != nil {
return nil, fmt.Errorf("API请求创建错误: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Token", forwardReq.Token) // 使用Token进行鉴权
req.Header.Set("Beaver-User-Id", forwardReq.UserID) // 使用Token进行鉴权
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("API请求错误: %v", err)
}
defer resp.Body.Close()
// 检查API响应
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("消息转发未成功: %v", resp.Status)
}
// 读取API响应
byteData, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("消息转发错误: %v", err)
}
// 解析API响应
var authResponse Response
authErr := json.Unmarshal(byteData, &authResponse)
if authErr != nil {
return nil, fmt.Errorf("消息转发错误: %v", authErr)
}
if authResponse.Code != 0 {
return nil, fmt.Errorf("消息转发失败: %v", authResponse.Msg)
}
sendAjaxJSON, _ := json.Marshal(authResponse.Result)
logx.Infof("消息转发成功: %s", string(sendAjaxJSON))
return authResponse.Result, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/ajax/ip_location.go | common/ajax/ip_location.go | package ajax
import (
"encoding/json"
"fmt"
"net/http"
)
// GetCityByIP 根据IP获取城市名称
func GetCityByIP(ip string) (string, error) {
// 调用IP-API.com免费服务
url := fmt.Sprintf("http://ip-api.com/json/%s?lang=en", ip)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
var result struct {
Status string `json:"status"`
City string `json:"city"`
Message string `json:"message"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", err
}
if result.Status != "success" {
return "", fmt.Errorf("IP定位失败: %s", result.Message)
}
return result.City, nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/list_query/enter.go | common/list_query/enter.go | package list_query
import (
"beaver/common/models"
"fmt"
"gorm.io/gorm"
)
type Option struct {
PageInfo models.PageInfo
Where *gorm.DB //高级查询
Likes []string //模糊查询
Joins string
Debug bool
Preload []string //预加载
Table func() (string, any) //子查询
Groups []string //分组查询
}
func ListQuery[T any](db *gorm.DB, model T, option Option) (list []T, count int64, err error) {
if option.Debug {
db = db.Debug()
}
query := db.Where(model) //把结构体自己的查询条件查了
// 模糊查询
if option.PageInfo.Key != "" && len(option.Likes) > 0 {
likeQuery := db.Where("")
for index, column := range option.Likes {
if index == 0 {
likeQuery = likeQuery.Where(fmt.Sprintf("%s like '%%?%%'", column), option.PageInfo.Key)
} else {
likeQuery = likeQuery.Or(fmt.Sprintf("%s like '%%?%%'", column), option.PageInfo.Key)
}
}
query.Where(likeQuery)
}
if option.Table != nil {
table, data := option.Table()
query = query.Table(table, data)
}
if len(option.Groups) > 0 {
for _, group := range option.Groups {
query = query.Group(group)
}
}
if option.Joins != "" {
query = query.Joins(option.Joins)
}
if option.Where != nil {
query = query.Where(option.Where)
}
// 求总数
query.Model(model).Count(&count)
// 预加载
for _, s := range option.Preload {
query = query.Preload(s)
}
//分页查询
if option.PageInfo.Page <= 0 {
option.PageInfo.Page = 1
}
if option.PageInfo.Limit <= 0 && option.PageInfo.Limit != -1 {
option.PageInfo.Limit = 10
}
fmt.Println(option.PageInfo, option.PageInfo.Limit)
offset := (option.PageInfo.Page - 1) * option.PageInfo.Limit
if option.PageInfo.Sort != "" {
query.Order(option.PageInfo.Sort)
}
err = query.Limit(option.PageInfo.Limit).Offset(offset).Find(&list).Error
return
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/middleware/middleware.go | common/middleware/middleware.go | package middleware
import (
"beaver/common/ajax"
"context"
"fmt"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
// LogMiddleware 自定义的中间件
func LogMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ClientIP := httpx.GetRemoteAddr(r)
ctx := context.WithValue(r.Context(), "ClientIP", ClientIP)
// 获取请求中的原始域名信息
originalHost := r.Host
ctx = context.WithValue(ctx, "ClientHost", originalHost)
// 判断请求协议是否为 HTTPS 并记录 "http" 或 "https"
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
ctx = context.WithValue(ctx, "Scheme", scheme)
// 获取城市信息并添加到header
cityName, err := ajax.GetCityByIP(ClientIP)
if err != nil {
cityName = "" // 默认返回"未知"
}
r.Header.Set("X-City-Name", cityName)
fmt.Println("scheme:", scheme, "ClientIP:", ClientIP, "ClientHost:", originalHost, "CityName:", cityName)
next(w, r.WithContext(ctx))
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/middleware/requestlog.go | common/middleware/requestlog.go | package middleware
import (
"bytes"
"io"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
)
// RequestLogMiddleware 请求日志中间件
func RequestLogMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 读取请求体
body, err := io.ReadAll(r.Body)
if err != nil {
logx.Errorf("读取请求体失败: %v", err)
}
// 恢复请求体
r.Body = io.NopCloser(bytes.NewBuffer(body))
// 记录请求信息
logx.Infof("请求路径: %s, 方法: %s, 请求体: %s", r.URL.Path, r.Method, string(body))
next(w, r)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/middleware/userAgent.go | common/middleware/userAgent.go | package middleware
import (
"context"
"net/http"
)
func UserAgentMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "user-agent", r.Header.Get("User-Agent"))
next(w, r.WithContext(ctx))
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/middleware/utils/log.go | common/middleware/utils/log.go | package utils
import (
"time"
"github.com/zeromicro/go-zero/core/logx"
)
// LogRequest 记录请求日志
func LogRequest(method, path string, req, resp interface{}, err error, startTime time.Time) {
duration := time.Since(startTime)
if err != nil {
logx.Errorf("请求失败: %s %s, 耗时: %v, 请求: %v, 错误: %v",
method, path, duration, req, err)
return
}
logx.Infof("请求成功: %s %s, 耗时: %v, 请求: %v, 响应: %v",
method, path, duration, req, resp)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/middleware/grpc/requestlog.go | common/middleware/grpc/requestlog.go | package grpcMiddleware
import (
"beaver/common/middleware/utils"
"context"
"time"
"google.golang.org/grpc"
)
// RequestLogInterceptor gRPC 请求日志拦截器
func RequestLogInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
startTime := time.Now()
// 调用下一个处理器
resp, err := handler(ctx, req)
// 记录请求信息
utils.LogRequest("gRPC", info.FullMethod, req, resp, err, startTime)
return resp, err
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/middleware/http/requestlog.go | common/middleware/http/requestlog.go | package httpMiddleware
import (
"beaver/common/middleware/utils"
"bytes"
"io"
"net/http"
"time"
)
// RequestLogMiddleware 请求日志中间件
func RequestLogMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
// 读取请求体
body, err := io.ReadAll(r.Body)
if err != nil {
utils.LogRequest(r.Method, r.URL.Path, string(body), nil, err, startTime)
return
}
// 恢复请求体
r.Body = io.NopCloser(bytes.NewBuffer(body))
next(w, r)
// 记录请求信息
utils.LogRequest(r.Method, r.URL.Path, string(body), nil, nil, startTime)
}
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/models/enter.go | common/models/enter.go | package models
import (
"database/sql/driver"
"fmt"
"strings"
"time"
)
type Model struct {
Id uint `gorm:"primaryKey;autoIncrement" json:"id"` // 自增主键
CreatedAt CustomTime `json:"createdAt"`
UpdatedAt CustomTime `json:"updatedAt"`
}
type CustomTime time.Time
const layout = "2006-01-02 15:04:05"
func (ct *CustomTime) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), `"`)
// 先尝试RFC3339格式(兼容带T和时区的数据)
t, err := time.Parse(time.RFC3339Nano, s)
if err == nil {
*ct = CustomTime(t)
return nil
}
// 可选:保留对旧格式的兼容
t, err = time.Parse("2006-01-02 15:04:05", s)
if err == nil {
*ct = CustomTime(t)
return nil
}
return fmt.Errorf("invalid time format: %s", s)
}
func (ct CustomTime) MarshalJSON() ([]byte, error) {
return []byte(`"` + time.Time(ct).Format(layout) + `"`), nil
}
func (ct CustomTime) String() string {
return time.Time(ct).Format(layout)
}
// 添加这两个方法到 CustomTime 类型
func (ct CustomTime) Value() (driver.Value, error) {
return time.Time(ct), nil
}
func (ct *CustomTime) Scan(value interface{}) error {
if value == nil {
return nil
}
if v, ok := value.(time.Time); ok {
*ct = CustomTime(v)
return nil
}
return fmt.Errorf("无法扫描 %T 到 CustomTime", value)
}
type PageInfo struct {
Page int `json:"page"`
Limit int `json:"limit"`
Sort string `json:"sort"`
Key string `json:"key"`
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/models/ctype/msg.go | common/models/ctype/msg.go | package ctype
import (
"database/sql/driver"
"encoding/json"
)
type MsgType uint32
// UnmarshalJSON 自定义JSON反序列化,支持字符串和数字格式
func (m *MsgType) UnmarshalJSON(data []byte) error {
// 尝试作为数字解析
var num uint32
if err := json.Unmarshal(data, &num); err == nil {
*m = MsgType(num)
return nil
}
// 尝试作为字符串解析
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
// 将字符串转换为数字
switch str {
case "1":
*m = TextMsgType
case "2":
*m = ImageMsgType
case "3":
*m = VideoMsgType
case "4":
*m = FileMsgType
case "5":
*m = VoiceMsgType
case "6":
*m = EmojiMsgType
case "7":
*m = NotificationMsgType
case "8":
*m = AudioFileMsgType
default:
*m = ImageMsgType
}
return nil
}
const (
/***
* @description: 文本消息类型
*/
TextMsgType MsgType = iota + 1
/**
* @description: 图片消息类型
*/
ImageMsgType
/**
* @description: 视频消息类型
*/
VideoMsgType
/**
* @description: 文件消息类型
*/
FileMsgType
/**
* @description: 语音消息类型(移动端录制的短语音)
*/
VoiceMsgType
/**
* @description: 表情消息类型
*/
EmojiMsgType
/**
* @description: 通知消息类型(会话内的通知,如:xxx加入了群聊、xxx创建了群等)
*/
NotificationMsgType
/**
* @description: 音频文件消息类型(用户上传的音频文件)
*/
AudioFileMsgType
)
type Msg struct {
Type MsgType `json:"type"` //消息类型 1:文本 2:图片 3:视频 4:文件 5:语音 6:表情 7:通知消息 8:音频文件
TextMsg *TextMsg `json:"textMsg,omitempty"` //文本消息
ImageMsg *ImageMsg `json:"imageMsg,omitempty"` //图片消息
VideoMsg *VideoMsg `json:"videoMsg,omitempty"` //视频消息
FileMsg *FileMsg `json:"fileMsg,omitempty"` //文件消息
VoiceMsg *VoiceMsg `json:"voiceMsg,omitempty"` //语音消息(移动端录制的短语音)
EmojiMsg *EmojiMsg `json:"emojiMsg,omitempty"` //表情消息
NotificationMsg *NotificationMsg `json:"notificationMsg,omitempty"` //通知消息(会话内的通知,如:xxx加入了群聊、xxx创建了群等)
AudioFileMsg *AudioFileMsg `json:"audioFileMsg,omitempty"` //音频文件消息(用户上传的音频文件)
ReplyMsg *ReplyMsg `json:"replyMsg,omitempty"` //回复消息
}
/**
* @description: 取出来的时候的数据
*/
func (c *Msg) Scan(val interface{}) error {
err := json.Unmarshal(val.([]byte), c)
if err != nil {
return err
}
return nil
}
/**
* @description: 入库的数据
*/
func (c *Msg) Value() (driver.Value, error) {
b, err := json.Marshal(c)
return string(b), err
}
type TextMsg struct {
Content string `json:"content"` //文本消息内容
}
// NotificationMsg 通知消息结构(会话内的通知,如:xxx加入了群聊、xxx创建了群、添加好友成功等)
type NotificationMsg struct {
Type int `json:"type"` // 通知类型:1=好友欢迎 2=创建群 3=加入群 4=退出群 5=踢出成员 6=转让群主等
Actors []string `json:"actors"` // 相关用户ID列表
}
type ImageMsg struct {
FileKey string `json:"fileKey"` //图片文件ID
Width int `json:"width,omitempty"` //图片宽度(可选)
Height int `json:"height,omitempty"` //图片高度(可选)
Size int64 `json:"size,omitempty"` //文件大小(字节,可选)
}
type VideoMsg struct {
FileKey string `json:"fileKey"` //视频文件ID
Width int `json:"width,omitempty"` //视频宽度(可选)
Height int `json:"height,omitempty"` //视频高度(可选)
Duration int `json:"duration,omitempty"` //视频时长(秒,可选)
ThumbnailKey string `json:"thumbnailKey,omitempty"` //视频封面图文件ID(可选)
Size int64 `json:"size,omitempty"` //文件大小(字节,可选)
}
type FileMsg struct {
FileKey string `json:"fileKey"` //文件ID
FileName string `json:"fileName,omitempty"` //原始文件名(可选,用于显示)
Size int64 `json:"size,omitempty"` //文件大小(字节,可选)
MimeType string `json:"mimeType,omitempty"` //MIME类型(可选,如 application/pdf)
}
type VoiceMsg struct {
FileKey string `json:"fileKey"` //语音文件ID
Duration int `json:"duration,omitempty"` //语音时长(秒,可选)
Size int64 `json:"size,omitempty"` //文件大小(字节,可选)
}
// AudioFileMsg 音频文件消息结构
type AudioFileMsg struct {
FileKey string `json:"fileKey"` //音频文件ID
FileName string `json:"fileName,omitempty"` //原始文件名(可选,用于显示)
Duration int `json:"duration,omitempty"` //音频时长(秒,可选)
Size int64 `json:"size,omitempty"` //文件大小(字节,可选)
}
// 表情消息结构
type EmojiMsg struct {
FileKey string `json:"fileKey"` // 表情图片文件ID(Emoji.FileName)
EmojiID string `json:"emojiId"` // 表情ID(Emoji.ID,单个表情时使用)
PackageID string `json:"packageId"` // 表情包ID(EmojiPackage.ID,表情包分享时使用)
Width int64 `json:"width,omitempty"` // 表情图片宽度(可选)
Height int64 `json:"height,omitempty"` // 表情图片高度(可选)
}
// 回复消息结构
type ReplyMsg struct {
ReplyToMessageID string `json:"replyToMessageId"` // 被回复的消息ID
ReplyToContent string `json:"replyToContent"` // 被回复的消息内容预览
ReplyToSender string `json:"replyToSender"` // 被回复消息的发送者昵称
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/models/ctype/user_info.go | common/models/ctype/user_info.go | package ctype
type UserInfo struct {
ID uint `json:"id"`
FileName string `json:"fileName"`
NickName string `json:"nickName"`
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/models/ctype/verification_question.go | common/models/ctype/verification_question.go | package ctype
import (
"database/sql/driver"
"encoding/json"
)
type VerificationQuestion struct {
Problem1 *string `json:"problem1"`
Problem2 *string `json:"problem2"`
Problem3 *string `json:"problem3"`
Answer1 *string `json:"answer1"`
Answer2 *string `json:"answer2"`
Answer3 *string `json:"answer3"`
}
/**
* @description: 取出来的时候的数据
*/
func (c *VerificationQuestion) Scan(val interface{}) error {
return json.Unmarshal(val.([]byte), c)
}
/**
* @description: 入库的数据
*/
func (c *VerificationQuestion) Value() (driver.Value, error) {
b, err := json.Marshal(c)
return string(b), err
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/zrpc_interceptor/clientInfoInterceptor.go | common/zrpc_interceptor/clientInfoInterceptor.go | package zrpc_interceptor
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
func ClientInfoInterceptor(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
var clientIP, userID string
cl := ctx.Value("clientIP")
if cl != nil {
clientIP = cl.(string)
}
uid := ctx.Value("userId")
if uid != nil {
userID = uid.(string)
}
md := metadata.New(map[string]string{"clientIP": clientIP, "userId": userID})
ctx = metadata.NewOutgoingContext(context.Background(), md)
err := invoker(ctx, method, req, reply, cc, opts...)
return err
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/validator/validator.go | common/validator/validator.go | package validator
import (
"regexp"
"errors"
)
// 验证手机号格式
func IsValidPhone(phone string) bool {
pattern := `^1[3-9]\d{9}$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(phone)
}
// 验证密码强度
func IsValidPassword(password string) bool {
// 密码长度至少8位
if len(password) < 8 {
return false
}
// 必须包含数字和字母
hasNumber := regexp.MustCompile(`[0-9]`).MatchString(password)
hasLetter := regexp.MustCompile(`[a-zA-Z]`).MatchString(password)
return hasNumber && hasLetter
}
// 验证登录参数
func ValidateLoginParams(phone, password string) error {
if !IsValidPhone(phone) {
return errors.New("手机号格式不正确")
}
if password == "" {
return errors.New("密码不能为空")
}
return nil
} | go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/response/enter.go | common/response/enter.go | package response
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
type Body struct {
Code int `json:"code"`
Msg string `json:"msg"`
Result interface{} `json:"result"`
}
// Response allows for a custom message to be passed in case of success
func Response(r *http.Request, w http.ResponseWriter, resp interface{}, err error, successMsg ...string) {
msg := ""
if len(successMsg) > 0 {
msg = successMsg[0]
}
if err == nil {
r := &Body{
Code: 0,
Msg: msg,
Result: resp,
}
httpx.WriteJson(w, http.StatusOK, r)
return
}
httpx.WriteJson(w, http.StatusOK, &Body{
Code: 1,
Msg: err.Error(),
Result: nil,
})
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/etcd/etcd.go | common/etcd/etcd.go | package etcd
import (
"context"
"fmt"
"math/rand"
"strings"
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/netx"
clientv3 "go.etcd.io/etcd/client/v3"
)
// 获取服务地址
func GetServiceAddr(etcdAddr string, serviceName string) string {
client, err := initEtcd(etcdAddr)
if err != nil {
logx.Errorf("初始化etcd客户端失败: %v", err)
return ""
}
defer client.Close()
// 拼接获取键的前缀
keyPrefix := fmt.Sprintf("/services/%s", serviceName)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := client.Get(ctx, keyPrefix, clientv3.WithPrefix())
if err != nil {
logx.Errorf("获取etcd地址失败: %v", err)
return ""
}
if len(resp.Kvs) == 0 {
logx.Errorf("获取etcd地址失败,没有找到服务: %s", serviceName)
return ""
}
// for _, kv := range resp.Kvs {
// logx.Infof("键: %s, 值: %s", kv.Key, kv.Value)
// }
r := rand.New(rand.NewSource(time.Now().UnixNano()))
selectedInstance := resp.Kvs[r.Intn(len(resp.Kvs))]
return string(selectedInstance.Value)
}
// 初始化etcd客户端
func initEtcd(etcdAddr string) (*clientv3.Client, error) {
client, err := clientv3.New(clientv3.Config{
Endpoints: []string{etcdAddr},
DialTimeout: 5 * time.Second,
})
if err != nil {
return nil, err
}
return client, nil
}
// 注册服务地址到etcd,并设置租约
func DeliveryAddress(etcdAddr string, serviceName string, addr string) {
list := strings.Split(addr, ":")
if len(list) != 2 {
logx.Error("addr格式错误")
return
}
ip := list[0]
if ip == "0.0.0.0" {
ip = netx.InternalIp()
addr = strings.ReplaceAll(addr, "0.0.0.0", ip)
}
client, err := initEtcd(etcdAddr)
if err != nil {
logx.Error("初始化etcd客户端失败", err)
return
}
defer client.Close()
err = registerServiceWithRetry(client, etcdAddr, serviceName, addr)
if err != nil {
logx.Error("服务注册失败", err)
}
}
// 注册服务,并在失败时自动重试
func registerServiceWithRetry(client *clientv3.Client, etcdAddr, serviceName, addr string) error {
for {
err := registerService(client, etcdAddr, serviceName, addr)
if err == nil {
return nil
}
logx.Error("注册服务失败,重试中...", err)
time.Sleep(2 * time.Second)
}
}
// 注册服务到etcd,并设置租约
func registerService(client *clientv3.Client, etcdAddr, serviceName, addr string) error {
// 创建租约,TTL为10秒
resp, err := client.Grant(context.Background(), 10)
if err != nil {
return fmt.Errorf("创建租约失败: %w", err)
}
// 使用服务名作为前缀,实例唯一标示作为键值
key := fmt.Sprintf("/services/%s/%s", serviceName, addr)
fmt.Println("key:", key)
// 写入键值并附加租约
_, err = client.Put(context.Background(), key, addr, clientv3.WithLease(resp.ID))
if err != nil {
return fmt.Errorf("上送etcd地址失败: %w", err)
}
logx.Info("上送etcd地址成功", addr)
fmt.Println("resp.ID:", resp.ID)
// 自动续约
ch, kaerr := client.KeepAlive(context.Background(), resp.ID)
if kaerr != nil {
return fmt.Errorf("设置租约续约失败: %w", kaerr)
}
fmt.Println("续约通道:", ch)
go keepAliveService(client, etcdAddr, serviceName, addr, ch)
return nil
}
// 处理服务续约
func keepAliveService(client *clientv3.Client, etcdAddr, serviceName, addr string, ch <-chan *clientv3.LeaseKeepAliveResponse) {
for {
select {
case ka, ok := <-ch:
if !ok {
logx.Error("续约频道关闭")
reconnectEtcd(client, etcdAddr, serviceName, addr)
return
}
if ka == nil {
logx.Error("租约失效")
reconnectEtcd(client, etcdAddr, serviceName, addr)
return
} else {
// logx.Infof("续约成功: lease ID=%d", ka.ID)
}
}
}
}
// 重新建立连接并注册服务
func reconnectEtcd(client *clientv3.Client, etcdAddr, serviceName, addr string) {
logx.Info("尝试重新连接etcd并注册服务")
client.Close()
for {
newClient, err := initEtcd(etcdAddr)
if err == nil {
client = newClient
break
}
logx.Error("重新初始化etcd客户端失败", err)
time.Sleep(2 * time.Second)
}
registerServiceWithRetry(client, etcdAddr, serviceName, addr)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/wsEnum/wsCommandConst/wsCommandConst.go | common/wsEnum/wsCommandConst/wsCommandConst.go | package wsCommandConst
// 定义消息命令和类型
type Command string
// 消息主类型
const (
// 聊天消息类
CHAT_MESSAGE Command = "CHAT_MESSAGE"
// 好友关系类
FRIEND_OPERATION Command = "FRIEND_OPERATION"
// 群组操作类
GROUP_OPERATION Command = "GROUP_OPERATION"
// 用户信息类
USER_PROFILE Command = "USER_PROFILE"
// 通知中心类
NOTIFICATION Command = "NOTIFICATION"
// 表情中心类
EMOJI Command = "EMOJI"
// 心跳消息类(应用级心跳)
HEARTBEAT Command = "HEARTBEAT"
)
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/common/wsEnum/wsTypeConst/wsTypeConst.go | common/wsEnum/wsTypeConst/wsTypeConst.go | package wsTypeConst
type Type string
// send(发起消息给服务端)
// receive(发给对方设备)
// sync(发给自己其他设备进行记录同步)
const (
PrivateMessageSend Type = "private_message_send" // 客户端->服务端 私聊消息发送
GroupMessageSend Type = "group_message_send" // 客户端->服务端 群聊消息发送
// --------------------------------------------------------
// --------------------------------------------------------
// 会话信息同步
ChatConversationMetaReceive Type = "chat_conversation_meta_receive" // 服务端->客户端 会话信息同步
ChatUserConversationReceive Type = "chat_user_conversation_receive" // 服务端->客户端 用户会话信息同步
ChatConversationMessageReceive Type = "chat_conversation_message_receive" // 服务端->客户端 会话消息同步
)
const (
// -------------------------------------------------------------------------------------
FriendReceive Type = "friend_receive" // 服务端->客户端 好友信息同步
FriendVerifyReceive Type = "friend_verify_receive" // 服务端->客户端 好友验证信息同步
)
// -------------------------------------------------------------------------------------
const (
GroupReceive Type = "group_receive" // 服务端->客户端 群组信息同步
GroupJoinRequestReceive Type = "group_join_request_receive" // 服务端->客户端 群成员添加请求
GroupMemberReceive Type = "group_member_receive" // 服务端->客户端 群成员变动(加入,离开、被踢出等)
)
const (
// --------------------------------------------------------
UserReceive Type = "user_receive" // 服务端->客户端 用户信息同步
)
const (
// 通知中心
NotificationReceive Type = "notification_receive" // 服务端->客户端 通知推送
NotificationMarkReadReceive Type = "notification_mark_read_receive" // 服务端->客户端 标记已读同步
)
const (
// 表情中心
EmojiReceive Type = "emoji_receive" // 服务端->客户端 表情数据同步
)
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/core/etcd.go | core/etcd.go | package core
import (
"time"
clientv3 "go.etcd.io/etcd/client/v3"
"github.com/zeromicro/go-zero/core/logx"
)
/**
* @description: 初始化etcd
*/
func InitEtcd(add string) *clientv3.Client {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{add},
DialTimeout: 5 * time.Second,
})
if err != nil {
logx.Error("etcd连接失败", err)
panic(err)
}
return cli
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/core/redis.go | core/redis.go | package core
import (
"context"
"fmt"
"time"
"github.com/go-redis/redis"
"github.com/zeromicro/go-zero/core/logx"
)
func InitRedis(addr string, password string, db int) (client *redis.Client) {
rdb := redis.NewClient(&redis.Options{
Addr: addr,
Password: password, // no password set
DB: db,
PoolSize: 100,
})
_, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
_, err := rdb.Ping().Result()
if err != nil {
logx.Error(err)
panic(err)
}
fmt.Println("redis链接成功")
return rdb
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/core/InitSFU.go | core/InitSFU.go | package core
import (
"github.com/BurntSushi/toml" // 用于解析 toml 配置文件
"github.com/pion/ion-sfu/pkg/sfu" // 导入 ion-sfu 包
)
func InitSFU(configFile string) *sfu.SFU {
var cfg sfu.Config
if _, err := toml.DecodeFile(configFile, &cfg); err != nil {
panic(err) // 处理配置文件解析错误
}
return sfu.NewSFU(cfg)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/core/gorm.go | core/gorm.go | package core
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func InitGorm(mysqlDataSource string) *gorm.DB {
db, err := gorm.Open(mysql.Open(mysqlDataSource), &gorm.Config{})
if err != nil {
panic("链接数据库失败 error: " + err.Error())
}
fmt.Println("mysql链接成功")
return db
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/core/version/version.go | core/version/version.go | package core
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/go-redis/redis"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
)
// VersionGenerator 版本号生成器(Redis缓存 + MySQL主存储)
type VersionGenerator struct {
redisClient *redis.Client
db *gorm.DB
}
// NewVersionGenerator 创建版本号生成器
func NewVersionGenerator(redisClient *redis.Client, db *gorm.DB) *VersionGenerator {
return &VersionGenerator{
redisClient: redisClient,
db: db,
}
}
// GetNextVersion 获取下一个版本号(Redis缓存 + MySQL主存储)
// 参数:
// - table: 表名或业务标识符 (必传)
// - field: 条件字段名;为空表示全局版本。若包含下划线,表示多字段组合键(如 user_id_category),会按下划线拆分为多列。
// - value: 条件字段值;为空表示全局版本。若 field 为组合键,value 也需用下划线分段(如 uid_cat),与 field 拆分后的段数一致。
//
// 返回: 版本号,失败时返回-1
func (vg *VersionGenerator) GetNextVersion(table string, field string, value string) int64 {
var key string
isConditional := field != "" && value != ""
if isConditional {
key = fmt.Sprintf("version:%s:%s:%s", table, field, value)
} else {
key = fmt.Sprintf("version:%s", table)
}
// 默认从1开始
initValue := int64(1)
// 1. 先尝试从Redis获取
version, err := vg.redisClient.Incr(key).Result()
if err != nil {
logx.Errorf("Redis获取版本号失败: table=%s, field=%s, value=%s, error=%v", table, field, value, err)
// Redis失败,初始化Redis并返回初始值
vg.redisClient.Set(key, initValue, 7*24*time.Hour) // 7天过期
logx.Infof("初始化版本号: table=%s, field=%s, value=%s, initValue=%d", table, field, value, initValue)
return initValue
}
// 2. 检查Redis版本号是否合理(防止Redis重启或过期后从0开始)
if version == 1 {
// Redis返回1表示key不存在或刚创建,需要从MySQL同步历史版本
mysqlVersion := vg.getMaxVersionFromMySQL(table, field, value)
if mysqlVersion < 0 {
logx.Errorf("MySQL获取版本号失败: table=%s", table)
// MySQL查询失败,继续使用Redis的版本号1
return version
}
if mysqlVersion > 0 {
// MySQL有数据,更新Redis为MySQL版本号+1
newVersion := mysqlVersion + 1
vg.redisClient.Set(key, newVersion, 7*24*time.Hour) // 7天过期
logx.Infof("从MySQL同步版本号: table=%s, mysqlVersion=%d, newVersion=%d", table, mysqlVersion, newVersion)
return newVersion
}
// MySQL没有数据,使用初始值
if initValue > 1 {
vg.redisClient.Set(key, initValue, 7*24*time.Hour) // 7天过期
logx.Infof("使用自定义初始值: table=%s, initValue=%d", table, initValue)
return initValue
}
// MySQL没有数据,继续使用Redis的版本号1
logx.Infof("MySQL没有数据,Redis从1开始: table=%s, version=%d", table, version)
}
logx.Infof("生成版本号: table=%s, field=%s, value=%s, version=%d", table, field, value, version)
return version
}
// getMaxVersionFromMySQL 从MySQL获取最大版本号
// 对于条件版本,查询该条件下的最大版本号,失败时返回-1
func (vg *VersionGenerator) getMaxVersionFromMySQL(table string, field string, value string) int64 {
isConditional := field != "" && value != ""
tableName := vg.getTableName(table)
var maxVersion int64
var err error
if isConditional {
if strings.Contains(field, "_") && strings.Contains(value, "_") {
fields := strings.Split(field, "_")
values := strings.Split(value, "_")
if len(fields) != len(values) {
logx.Errorf("组合键字段和值数量不匹配: fields=%v, values=%v", fields, values)
return -1
}
conds := make([]string, 0, len(fields))
args := make([]interface{}, 0, len(fields))
for i := range fields {
if !isSafeIdentifier(fields[i]) {
logx.Errorf("非法字段名: %s", fields[i])
return -1
}
conds = append(conds, fmt.Sprintf("%s = ?", fields[i]))
args = append(args, values[i])
}
query := fmt.Sprintf("SELECT COALESCE(MAX(version), 0) FROM %s WHERE %s", tableName, strings.Join(conds, " AND "))
err = vg.db.Raw(query, args...).Scan(&maxVersion).Error
logx.Infof("查询组合条件版本历史: table=%s, fields=%v, values=%v, maxVersion=%d", table, fields, values, maxVersion)
} else {
// 单字段条件
if !isSafeIdentifier(field) {
logx.Errorf("非法字段名: %s", field)
return -1
}
query := fmt.Sprintf("SELECT COALESCE(MAX(version), 0) FROM %s WHERE %s = ?", tableName, field)
err = vg.db.Raw(query, value).Scan(&maxVersion).Error
logx.Infof("查询条件版本历史: table=%s, field=%s, value=%s, maxVersion=%d", table, field, value, maxVersion)
}
} else {
// 全局版本:查询表中的最大版本号
err = vg.db.Raw("SELECT COALESCE(MAX(version), 0) FROM " + tableName).Scan(&maxVersion).Error
logx.Infof("查询全局版本历史: table=%s, maxVersion=%d", table, maxVersion)
}
if err != nil {
logx.Errorf("MySQL获取最大版本号失败: table=%s, field=%s, value=%s, error=%v", table, field, value, err)
return -1
}
return maxVersion
}
// getTableName 根据数据类型获取表名
// 注意:条件版本不应该调用此方法,因为条件版本不从MySQL查询
func (vg *VersionGenerator) getTableName(dataType string) string {
switch dataType {
case "users":
return "user_models"
case "friends":
return "friend_models"
case "groups":
return "group_models"
case "group_members":
return "group_member_models"
case "group_member_logs":
return "group_member_change_log_models"
case "chats":
return "chat_models"
case "notification_events":
return "notification_events"
case "notification_inboxes":
return "notification_inboxes"
case "notification_reads":
return "notification_reads"
default:
return dataType
}
}
var safeIdentRegexp = regexp.MustCompile(`^[a-zA-Z0-9_]+$`)
func isSafeIdentifier(s string) bool {
return safeIdentRegexp.MatchString(s)
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/database/InitFileData.go | database/InitFileData.go | package database
import (
"beaver/app/file/file_models"
"log"
"gorm.io/gorm"
)
func InitFileData(db *gorm.DB) error {
// 初始化默认文件数据
defaultFiles := []file_models.FileModel{
{
OriginalName: "defaultUserFileName",
Size: 60317,
Path: "image/user.png",
Md5: "a9de5548bef8c10b92428fff61275c72",
Type: "image",
FileKey: "a9de5548bef8c10b92428fff61275c72.png",
Source: file_models.LocalSource,
},
{
OriginalName: "defaultGroupFileName",
Size: 90310,
Path: "image/group.png",
Md5: "a8ba5d19ea54a91aec17dec0ad5000e6.png",
Type: "image",
FileKey: "a8ba5d19ea54a91aec17dec0ad5000e6.png",
Source: file_models.LocalSource,
},
}
for _, file := range defaultFiles {
var count int64
if err := db.Model(&file_models.FileModel{}).Where("file_key = ?", file.FileKey).Count(&count).Error; err != nil {
return err
}
if count == 0 {
if err := db.Create(&file).Error; err != nil {
log.Printf("创建默认文件失败: %v", err)
return err
} else {
log.Printf("创建默认文件成功: %s", file.FileKey)
}
}
}
return nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/database/database.go | database/database.go | package database
import (
"fmt"
"gorm.io/gorm"
)
// 主初始化函数 - 在main.go中调用
func InitAllData(db *gorm.DB) error {
fmt.Println("=== 开始初始化所有表的默认数据 ===")
// 按顺序初始化各表数据
initializers := []struct {
name string
fn func(*gorm.DB) error
}{
{"文件表", InitFileData},
}
// 逐个执行初始化
for _, init := range initializers {
fmt.Printf("正在初始化%s...\n", init.name)
if err := init.fn(db); err != nil {
fmt.Printf("%s初始化失败: %v\n", init.name, err)
// 继续执行其他表初始化,不中断流程
} else {
fmt.Printf("%s初始化成功\n", init.name)
}
}
fmt.Println("=== 所有表初始化完成 ===")
return nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
wsrh8888/beaver-server | https://github.com/wsrh8888/beaver-server/blob/71409b80d00457511f57d8fec96e7366a8520b60/database/InitUpdateData.go | database/InitUpdateData.go | package database
import (
"beaver/app/update/update_models"
"beaver/utils/conversation"
"fmt"
"gorm.io/gorm"
)
// 初始化城市策略数据
func InitUpdateData(db *gorm.DB) error {
fmt.Println("=== 开始初始化城市策略数据 ===")
// 从数据库读取所有应用,为每个应用创建城市策略
if err := initCityStrategyData(db); err != nil {
return fmt.Errorf("初始化城市策略数据失败: %v", err)
}
fmt.Println("=== 城市策略数据初始化完成 ===")
return nil
}
// 初始化城市策略数据
func initCityStrategyData(db *gorm.DB) error {
fmt.Println("正在初始化城市策略数据...")
// 从数据库读取所有应用
var apps []update_models.UpdateApp
if err := db.Where("is_active = ?", true).Find(&apps).Error; err != nil {
return fmt.Errorf("读取应用数据失败: %v", err)
}
if len(apps) == 0 {
fmt.Println("警告: 数据库中没有找到活跃的应用")
return nil
}
cities := conversation.GetDefaultCities()
// 为每个应用创建所有城市的默认策略
for _, app := range apps {
for _, city := range cities {
var count int64
// 检查城市策略是否存在
db.Model(&update_models.UpdateStrategy{}).
Where("app_id = ? AND city_id = ?", app.AppID, city.Code).
Count(&count)
if count == 0 {
// 城市策略不存在,创建默认策略
defaultStrategy := &update_models.Strategy{}
newStrategy := update_models.UpdateStrategy{
AppID: app.AppID,
CityID: city.Code,
Strategy: defaultStrategy,
IsActive: true,
}
if err := db.Create(&newStrategy).Error; err != nil {
return fmt.Errorf("创建城市策略失败 (App: %s, City: %s): %v", app.AppID, city.Code, err)
}
fmt.Printf("已创建城市策略: %s - %s (%s)\n", app.Name, city.Name, city.Code)
} else {
fmt.Printf("城市策略已存在,跳过: %s - %s (%s)\n", app.Name, city.Name, city.Code)
}
}
}
fmt.Printf("成功处理 %d 个应用,%d 个城市的策略数据\n", len(apps), len(cities))
return nil
}
| go | MIT | 71409b80d00457511f57d8fec96e7366a8520b60 | 2026-01-07T09:45:42.639179Z | false |
awesee/books | https://github.com/awesee/books/blob/520759085a442f1c352d8926ad9196ef8172a436/main.go | main.go | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/url"
"path"
"sort"
"strings"
)
func main() {
var buf bytes.Buffer
buf.WriteString(strings.TrimLeft(authInfo, "\n"))
buf.WriteString("\n# 目录\n")
readDir(".", root, &buf)
buf.WriteString(footer)
err := ioutil.WriteFile("README.md", buf.Bytes(), 0644)
checkErr(err)
}
func readDir(dirname string, level int, buf *bytes.Buffer) {
fileList, err := ioutil.ReadDir(dirname)
checkErr(err)
sort.Slice(fileList, func(i, j int) bool {
if fileList[i].IsDir() == fileList[j].IsDir() {
return strings.ToLower(fileList[i].Name()) < strings.ToLower(fileList[j].Name())
}
return fileList[j].IsDir()
})
for _, fi := range fileList {
if validName(fi.Name()) {
if level == root {
buf.WriteString("\n")
if fi.IsDir() {
buf.WriteString("## ")
}
} else {
buf.WriteString(strings.Repeat(" ", level))
buf.WriteString("- ")
}
buf.WriteString(fmt.Sprintf("[%s](%s)\n",
fi.Name(),
url.PathEscape(path.Join(dirname, fi.Name())),
))
if fi.IsDir() {
readDir(path.Join(dirname, fi.Name()), level+1, buf)
}
}
}
}
func validName(name string) bool {
name = strings.ToLower(name)
excludeFile := map[string]bool{
"license": true,
"go.mod": true,
"go.sum": true,
}
return !(excludeFile[name] ||
strings.HasPrefix(name, ".") ||
strings.HasSuffix(name, ".md") ||
strings.HasSuffix(name, ".go"))
}
func checkErr(err error) {
if err != nil {
log.Fatalln(err)
}
}
const root = 0
const authInfo = `
<!--|This file generated by command; DO NOT EDIT. |-->
<!--+----------------------------------------------------------------------+-->
<!--|@author openset <openset.wang@gmail.com> |-->
<!--|@link https://github.com/openset |-->
<!--|@home https://github.com/openset/books |-->
<!--+----------------------------------------------------------------------+-->
`
const footer = `
## ©2018 Shuo. All rights reserved.
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fopenset%2Fbooks?ref=badge_shield)
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fopenset%2Fbooks?ref=badge_large)
`
| go | MIT | 520759085a442f1c352d8926ad9196ef8172a436 | 2026-01-07T09:41:57.278025Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/provider/resources.go | provider/resources.go | // Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//nolint:misspell
package provider
import (
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"unicode"
// Allow embedding the metadata file
_ "embed"
"github.com/Azure/go-autorest/autorest/azure/cli"
"github.com/hashicorp/go-azure-helpers/resourcemanager/location"
"github.com/hashicorp/go-azure-sdk/sdk/auth"
"github.com/hashicorp/go-azure-sdk/sdk/environments"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-azurerm/shim"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge/info"
tks "github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge/tokens"
tfshim "github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim"
shimv2 "github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim/sdk-v2"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi-azure/provider/v6/pkg/version"
)
const (
azureName = "name"
azureLocation = "location"
)
// all of the Azure token components used below.
const (
// packages:
azurePkg = "azure"
// modules; in general, we took naming inspiration from the Azure SDK for Go:
// https://godoc.org/github.com/Azure/azure-sdk-for-go
aadb2c = "AadB2C" // Advisor
advisor = "Advisor" // Advisor
aiFoundry = "AIFoundry" // AI Foundry
azureAnalysisServices = "AnalysisServices" // Analysis Services
azureAPIManagement = "ApiManagement" // API Management
azureAppConfiguration = "AppConfiguration" // App Configuration
azureAppInsights = "AppInsights" // AppInsights
azureAppPlatform = "AppPlatform" // AppPlatform
azureAppService = "AppService" // App Service
azureArcKubernetes = "ArcKubernetes" // Arc Kubernetes
azureArcMachine = "ArcMachine" // Arc Machine
armMsi = "ArmMsi" // ARM MSI (managed service identity)
azureAttestation = "Attestation" // Attestation
azureAutomation = "Automation" // Automation
// Automanage: See (https://learn.microsoft.com/en-us/azure/governance/machine-configuration/)
azureAutomanage = "Automanage"
azureAuthorization = "Authorization" // Authorization
azureAvs = "Avs" // Avs
azureBackup = "Backup" // Backup
azureBatch = "Batch" // Batch
azureBilling = "Billing" // Billing
azureBlueprint = "Blueprint" // Blueprint
azureBot = "Bot" // Bot
azureCDN = "Cdn" // CDN
azureChaosStudio = "ChaosStudio" // Chaos Studio
azureCognitive = "Cognitive" // Cognitive
azureCommunication = "Communication" // Communication
azureCompute = "Compute" // Virtual Machines
azureConfidentialLedger = "ConfidentialLedger" // Confidential Ledger
azureConnections = "Connections" // Connection
azureConsumption = "Consumption" // Consumption
azureContainerApp = "ContainerApp" // Container App
azureContainerService = "ContainerService" // Azure Container Service
azureCore = "Core" // Base Resources
azureCosmosDB = "CosmosDB" // Cosmos DB
azureCostManagement = "CostManagement" // Cost Management
azureDashboard = "Dashboard" // Dashboard
azureDatabaseMigration = "DatabaseMigration" // Database Migration
azureDataboxEdge = "DataboxEdge" // Databox Edge
azureDatadog = "Datadog" // Datadog
azureDataFactory = "DataFactory" // Data Factory
azureDataProtection = "DataProtection" // Data Protection
azureDataShare = "DataShare" // DataShare
azureDataBricks = "DataBricks" // DataBricks
azureDesktopVirtualization = "DesktopVirtualization" // Desktop Virtualization
azureDevTest = "DevTest" // Dev Test Labs
azureDevCenter = "DevCenter" // Dev Center
azureDigitalTwins = "DigitalTwins" // Digital Twins
azureDNS = "Dns" // DNS
azureDomainServices = "DomainServices" // DomainServices
azureDynatrace = "Dynatrace" // Dynatrace
azureElasticCloud = "ElasticCloud" // Elastic Cloud
azureExpressRoute = "ExpressRoute" // ExpressRoute
azureExtendedLocation = "ExtendedLocation" // Extended Location
azureFluidRelay = "FluidRelay" // Fluid Relay
azureFrontdoor = "FrontDoor" // Frontdoor
azureGraph = "Graph" // Graph
azureHdInsight = "HDInsight" // nolint:misspell // HDInsight
azureHealthcare = "Healthcare" // HealthCare
azureHpc = "Hpc" // High-performance Compute
azureHsm = "Hsm" // Hardware Security Module
azureHybrid = "Hybrid" // Hybrid Compute
azureIot = "Iot" // IoT resource
azureIotCentral = "IotCentral" // IoT central
azureKeyVault = "KeyVault" // Key Vault
azureKusto = "Kusto" // Kusto
azureLab = "Lab" // Lab
azureLighthouse = "Lighthouse" // Lighthouse
azureLogAnalytics = "LogAnalytics" // Log Analytics
azureLogicApps = "LogicApps" // Logic Apps
azureLB = "Lb" // Load Balancer
azureLoadTest = "LoadTest" // Load Test
azureMariaDB = "MariaDB" // MariaDB
azureEventGrid = "EventGrid" // Event Grid
azureEventHub = "EventHub" // Event Hub
azureMachineLearning = "MachineLearning" // Machine Learning Resources
azureMaintenance = "Maintenance" // Maintenance Resources
azureManagedApplication = "ManagedApplication" // ManagedApplication
azureManagedLustre = "ManagedLustre" // ManagedLustre
azureManagement = "Management" // Management Resources
azureMaps = "Maps" // Maps
azureMarketPlace = "Marketplace" // Marketplace
azureMediaServices = "MediaServices" // Media Services
azureMixedReality = "MixedReality" // Mixed Reality
azureMonitoring = "Monitoring" // Metrics/monitoring resources
azureMobile = "Mobile" // Mobile
azureMSSQL = "MSSql" // MS Sql
azureMySQL = "MySql" // MySql
azureNetapp = "NetApp" // NetApp
azureNetwork = "Network" // Networking
azureNetworkFunction = "NetworkFunction" // Network Function
azureNginx = "Nginx" // Nginx
azureNotificationHub = "NotificationHub" // Notification Hub
azureOperationalInsights = "OperationalInsights" // Operational Insights
azureOracle = "Oracle" // Oracle
azureOrbital = "Orbital" // Orbital
azurePaloAlto = "PaloAlto" // PaloAlto
azurePim = "Pim" // Privileged Identity Management
azurePostgresql = "PostgreSql" // Postgres SQL
azurePolicy = "Policy" // Policy
azurePortal = "Portal" // Portal
azurePowerBi = "PowerBI" // PowerBI
azureProximity = "Proximity" // Proximity
azurePrivateDNS = "PrivateDns" // Private DNS
azurePrivateLink = "PrivateLink" // PrivateLink
azurePurview = "Purview" // Purview
azureQumulo = "Qumulo" // Qumulo
azureRecoveryServices = "RecoveryServices" // Recovery Services
azureRedis = "Redis" // RedisCache
azureRedHatOpenShift = "RedHatOpenShift" // RedHat OpenShift
azureRelay = "Relay" // Relay
azureSecurityCenter = "SecurityCenter" // Security Center
azureSentinel = "Sentinel" // Sentinel
azureServiceBus = "ServiceBus" // ServiceBus
azureServiceFabric = "ServiceFabric" // Service Fabric
azureSearch = "Search" // Search
azureSignalr = "SignalR" // SignalR
azureSiteRecovery = "SiteRecovery" // SiteRecovery
azureSQL = "Sql" // SQL
azureStack = "Stack" // Stack
azureStorage = "Storage" // Storage
azureStreamAnalytics = "StreamAnalytics" // StreamAnalytics
azureSynapse = "Synapse" // Synapse
azureSystemCenter = "SystemCenter" // SystemCenter
azureTrustedSigning = "TrustedSigning" // TrustedSigning
azureVideoAnalyzer = "VideoAnalyzer" // Video Analyzer
azureVideoIndexer = "VideoIndexer" // Video Indexer
azureVoice = "Voice" // Voice
azureWaf = "Waf" // WAF
azureWebPubSub = "WebPubSub" // Web PubSub
azureWorkloadsSAP = "WorkloadsSAP" // Workloads SAP
// Legacy Module Names
azureLegacyRole = "Role" // Azure Role (Legacy)
azureLegacyMSI = "Msi" // Managed Service Identity / MSI (Legacy)
azureLegacyManagementGroups = "ManagementGroups" // Management Groups (Legacy)
azureLegacyMgmtResource = "ManagementResource" // Management Resource (Legacy)
azureLegacyTrafficManager = "TrafficManager" // Traffic Manager (Legacy)
)
var moduleMap = map[string]string{
"aadb2c": aadb2c,
"advisor": advisor,
"ai_foundry": aiFoundry,
"analysis_services": azureAnalysisServices,
"api_management": azureAPIManagement,
"app": azureAppConfiguration,
"application_insights": azureAppInsights,
// Resources and datasources with this prefix are mapped from
// azurerm_spring_${rest} to ${pkg}:AppPlatform:camel(spring_${rest}).
"spring": azureAppPlatform + "~Spring",
"app_service": azureAppService,
"arc_kubernetes": azureArcKubernetes,
"arc_machine": azureArcMachine,
"arc": "Arc",
// Ignored: armMsi. Only used for the token "azurerm_federated_identity_credential".
"attestation": azureAttestation,
"automation": azureAutomation,
"automanage": azureAutomanage,
// Ignored: azureAuthorization. Only used with RenameResourceWithAlias
"vmware": azureAvs,
"backup": azureBackup,
"batch": azureBatch,
"billing": azureBilling,
"blueprint": azureBlueprint,
"bot": azureBot,
"cdn": azureCDN,
"cognitive": azureCognitive,
"ai_services": azureCognitive,
"communication": azureCommunication,
"virtual_machine": azureCompute,
// Ignored: azureCompute. No clear token pattern. Tokens that map to azureCompute include:
//
// "azurerm_disk_encryption_set
// "azurerm_dedicated_host"
// "azurerm_image"
// and many more
// Ignored: azureConfidentialLedger.
// The only token is "azurerm_confidential_ledger".
// Ignored: azureConnections. The only token is "azurerm_api_connection" and
// "azurerm_managed_api". Note that `_api` is involved in many modules.
"consumption": azureConsumption,
"container_app": azureContainerApp,
"container": azureContainerService,
// Ignored: azureCore. Includes tokens such as "azurerm_resource_group".
// While every entry that starts with resource_group is azureCore,
// they still include ResourceGroup in Pulumi name.
"cosmosdb": azureCosmosDB,
// cost_management is truncated as if it didn't exit.
"cost_management": azureCostManagement,
"cost": azureCostManagement,
"custom_ip": "CustomIp",
"dashboard": azureDashboard,
"database_migration": azureDatabaseMigration,
"databox_edge": azureDataboxEdge,
"datadog": azureDatadog,
"data_factory": azureDataFactory,
"data_protection": azureDataProtection,
"data_share": azureDataShare,
"databricks": azureDataBricks,
"virtual_desktop": azureDesktopVirtualization,
"dev_test": azureDevTest,
"dev_center": azureDevCenter,
"digital_twins": azureDigitalTwins,
"dns": azureDNS,
"active_directory_domain": azureDomainServices,
"dynatrace": azureDynatrace,
"elastic_cloud": azureElasticCloud,
"elastic_san": "ElasticSan",
"fabric": "Fabric",
"fluid_relay": azureFluidRelay,
"frontdoor": azureFrontdoor,
"function": azureAppService,
"graph": azureGraph,
"hdinsight": azureHdInsight,
"healthcare": azureHealthcare,
"hpc": azureHpc,
// Ignored: azureHsm. The only token is "azurerm_dedicated_hardware_security_module".
"hybrid": azureHybrid,
"iothub": azureIot,
"iotcentral": azureIotCentral,
"key_vault": azureKeyVault,
"kusto": azureKusto,
"kubernetes": azureContainerService,
"lab_service": azureLab,
"lighthouse": azureLighthouse,
"load_test": azureLoadTest,
"log_analytics": azureLogAnalytics,
"logic_app": azureLogicApps,
"lb": azureLB,
"new_relic": "NewRelic",
"mariadb": azureMariaDB,
"eventgrid": azureEventGrid,
"eventhub": azureEventHub,
"machine_learning": azureMachineLearning,
"maintenance": azureMaintenance,
"managed_application": azureManagedApplication,
"managed_lustre": azureManagedLustre,
"managed_redis": "ManagedRedis",
"management": azureManagement,
"resource_management": azureManagement,
"maps": azureMaps,
"marketplace": azureMarketPlace,
"media_services": azureMediaServices,
// Ignored: azureMixedReality. The only token is "azurerm_spatial_anchors_account".
"monitor": azureMonitoring,
"mobile": azureMobile,
"mongo_cluster": "MongoCluster",
"mssql": azureMSSQL,
"mysql": azureMySQL,
"netapp": azureNetapp,
"network": azureNetwork + "~Network",
"nginx": azureNginx,
"notification_hub": azureNotificationHub,
// Ignored: azureOperationalInsights. The token prefix log_ maps into either
// azureOperationalInsights or azureLogInsights. Its not clear which from the
// token.
"oracle": azureOracle,
"orbital": azureOrbital,
"palo_alto": azurePaloAlto,
"pim": "Pim",
"postgresql": azurePostgresql,
"policy": azurePolicy,
"portal": azurePortal,
"powerbi": azurePowerBi,
"proximity": azureProximity,
"private_dns": azurePrivateDNS,
// Both map to private link
"private_link": azurePrivateLink,
"private_endpoint": azurePrivateLink,
"purview": azurePurview,
"qumulo": azureQumulo,
"recovery_services": azureRecoveryServices,
"redis": azureRedis,
"relay": azureRelay,
"security_center": azureSecurityCenter,
"sentinel": azureSentinel,
"servicebus": azureServiceBus,
"service_fabric": azureServiceFabric,
"search": azureSearch,
"signalr": azureSignalr,
"site_recovery": azureSiteRecovery,
"sql": azureSQL,
"stack": azureStack,
"storage": azureStorage,
"stream_analytics": azureStreamAnalytics,
"synapse": azureSynapse,
"video_analyzer": azureVideoAnalyzer,
"virtual_hub": azureNetwork,
"voice": azureVoice,
"web_application_firewall": azureWaf,
"web_pubsub": azureWebPubSub,
"workloads_sap": azureWorkloadsSAP,
"network_function": azureNetworkFunction,
"chaos_studio": azureChaosStudio,
"redhat_openshift": azureRedHatOpenShift,
"system_center": azureSystemCenter,
"trusted_signing": azureTrustedSigning,
"express_route": azureExpressRoute,
"custom_extended_location": azureExtendedLocation,
"video_indexer": azureVideoIndexer,
// We don't apply mappings to legacy roles, so they are omitted here.
}
var namespaceMap = map[string]string{
"azure": "Azure",
}
// azureMember manufactures a member for the Azure package and the given module and type. It automatically
// names the file by simply lower casing the member's first character.
func azureMember(moduleTitle, mem string) tokens.ModuleMember {
moduleName := strings.ToLower(moduleTitle)
namespaceMap[moduleName] = moduleTitle
fn := string(unicode.ToLower(rune(mem[0]))) + mem[1:]
token := moduleName + "/" + fn
return tokens.ModuleMember(azurePkg + ":" + token + ":" + mem)
}
// azureType manufactures a type token for the Azure package and the given module and type.
func azureType(mod string, typ string) tokens.Type {
return tokens.Type(azureMember(mod, typ))
}
// azureDataSource manufactures a standard member given a module and data source name.
func azureDataSource(mod string, res string) tokens.ModuleMember {
return azureMember(mod, res)
}
// azureResource manufactures a standard resource token given a module and resource name.
func azureResource(mod string, res string) tokens.Type {
return azureType(mod, res)
}
func ref[T any](value T) *T {
return &value
}
type cloudShellProfile struct {
useMSI bool
msiEndpoint string
subscriptionID string
tenantID string
}
// Azure Cloud Shell is a special case in terms of config: it provides authentication via
// an MSI endpoint, but it also has Azure CLI installed. Therefore, to make Pulumi CLI work
// out of the box with no actions required from a user, we combine the MSI endpoint authentication
// with retrieving the subscription information from the current profile. If both are found,
// we switch the provider to the endpoint/subscriptoin by default.
func detectCloudShell() cloudShellProfile {
negative := cloudShellProfile{
useMSI: false,
}
msiEndpoint := os.Getenv("MSI_ENDPOINT")
if msiEndpoint == "" {
return negative
}
profilePath, err := cli.ProfilePath()
if err != nil {
return negative
}
profile, err := cli.LoadProfile(profilePath)
if err != nil {
return negative
}
for _, subscription := range profile.Subscriptions {
if subscription.IsDefault {
return cloudShellProfile{
useMSI: true,
msiEndpoint: msiEndpoint,
subscriptionID: subscription.ID,
tenantID: subscription.TenantID,
}
}
}
return negative
}
// preConfigureCallback returns an error when cloud provider setup is misconfigured
func preConfigureCallback(vars resource.PropertyMap, _ tfshim.ResourceConfig) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
metadataHost := tfbridge.ConfigStringValue(vars, "metadataHost", []string{"ARM_METADATA_HOSTNAME"})
var env *environments.Environment
var err error
if metadataHost != "" {
env, err = environments.FromEndpoint(ctx, fmt.Sprintf("https://%s", metadataHost))
if err != nil {
return fmt.Errorf("failed to read Azure environment from metadata host \"%s\": %v", metadataHost, err)
}
} else {
envName := tfbridge.ConfigStringValue(vars, "environment", []string{"ARM_ENVIRONMENT"})
if envName == "" {
envName = "public"
}
env, err = environments.FromName(envName)
if err != nil {
return fmt.Errorf("failed to read Azure environment \"%s\": %v", envName, err)
}
}
// check for auxiliary tenants
auxTenants := tfbridge.ConfigArrayValue(vars, "auxiliaryTenantIDs", []string{"ARM_AUXILIARY_TENANT_IDS"})
// validate the azure config
useOIDC := tfbridge.ConfigBoolValue(vars, "useOidc", []string{"ARM_USE_OIDC"})
authConfig := auth.Credentials{
// SubscriptionID: tfbridge.ConfigStringValue(vars, "subscriptionId", []string{"ARM_SUBSCRIPTION_ID"}),
ClientID: tfbridge.ConfigStringValue(vars, "clientId", []string{"ARM_CLIENT_ID"}),
ClientSecret: tfbridge.ConfigStringValue(vars, "clientSecret", []string{"ARM_CLIENT_SECRET"}),
TenantID: tfbridge.ConfigStringValue(vars, "tenantId", []string{"ARM_TENANT_ID"}),
Environment: *env,
ClientCertificatePath: tfbridge.ConfigStringValue(vars, "clientCertificatePath", []string{
"ARM_CLIENT_CERTIFICATE_PATH",
}),
ClientCertificatePassword: tfbridge.ConfigStringValue(vars, "clientCertificatePassword", []string{
"ARM_CLIENT_CERTIFICATE_PASSWORD",
}),
CustomManagedIdentityEndpoint: tfbridge.ConfigStringValue(vars, "msiEndpoint", []string{"ARM_MSI_ENDPOINT"}),
AuxiliaryTenantIDs: auxTenants,
// OIDC section. The ACTIONS_ variables are set by GitHub.
OIDCTokenRequestToken: tfbridge.ConfigStringValue(vars, "oidcRequestToken", []string{
"ARM_OIDC_REQUEST_TOKEN", "ACTIONS_ID_TOKEN_REQUEST_TOKEN",
}),
OIDCTokenRequestURL: tfbridge.ConfigStringValue(vars, "oidcRequestUrl", []string{
"ARM_OIDC_REQUEST_URL", "ACTIONS_ID_TOKEN_REQUEST_URL",
}),
OIDCAssertionToken: tfbridge.ConfigStringValue(vars, "oidcToken", []string{"ARM_OIDC_TOKEN"}),
// Feature Toggles
EnableAuthenticatingUsingClientCertificate: true,
EnableAuthenticatingUsingClientSecret: true,
EnableAuthenticatingUsingManagedIdentity: tfbridge.ConfigBoolValue(vars, "useMsi", []string{"ARM_USE_MSI"}),
EnableAuthenticatingUsingAzureCLI: true,
EnableAuthenticationUsingOIDC: useOIDC,
EnableAuthenticationUsingGitHubOIDC: useOIDC,
}
_, err = auth.NewAuthorizerFromCredentials(context.Background(), authConfig, env.MicrosoftGraph)
if err != nil {
//nolint:staticcheck
return fmt.Errorf("failed to load application credentials:\n"+
"Details: %v\n\n"+
"\tPlease make sure you have signed in via 'az login' or configured another authentication method.\n\n"+
"\tSee https://www.pulumi.com/registry/packages/azure/installation-configuration/ for more information.", err)
}
return nil
}
//go:embed cmd/pulumi-resource-azure/bridge-metadata.json
var metadata []byte
// Provider returns additional overlaid schema and metadata associated with the azure package.
//
// nolint: lll
func Provider() tfbridge.ProviderInfo {
innerProvider := shim.NewProvider()
// TF renamed azurerm_extended_custom_location to azurerm_extended_location_custom_location in
// https://github.com/hashicorp/terraform-provider-azurerm/pull/28066. To avoid the "duplicate module member" error,
// we drop the old resource here. The Pulumi token is the same for old and new resource.
delete(innerProvider.ResourcesMap, "azurerm_extended_custom_location")
p := shimv2.NewProvider(innerProvider)
// Adjust the defaults if running in Azure Cloud Shell.
// Environment variables still take preference, e.g. USE_MSI=false disables the MSI endpoint.
cloudShell := detectCloudShell()
yes := true
prov := tfbridge.ProviderInfo{
P: p,
Name: "azurerm",
DisplayName: "Azure",
Description: "A Pulumi package for creating and managing Microsoft Azure cloud resources, based on the Terraform azurerm provider. We recommend using the [Azure Native provider](https://github.com/pulumi/pulumi-azure-native) to provision Azure infrastructure. Azure Native provides complete coverage of Azure resources and same-day access to new resources and resource updates.",
Keywords: []string{"pulumi", "azure"},
Homepage: "https://pulumi.io",
License: "Apache-2.0",
GitHubOrg: "hashicorp",
Repository: "https://github.com/pulumi/pulumi-azure",
Version: version.Version,
UpstreamRepoPath: "./upstream",
MetadataInfo: tfbridge.NewProviderMetadata(metadata),
Config: map[string]*tfbridge.SchemaInfo{
"subscription_id": {
Default: &tfbridge.DefaultInfo{
Value: cloudShell.subscriptionID,
EnvVars: []string{"ARM_SUBSCRIPTION_ID"},
},
Secret: &yes,
},
"environment": {
Default: &tfbridge.DefaultInfo{
Value: "public",
EnvVars: []string{"AZURE_ENVIRONMENT", "ARM_ENVIRONMENT"},
},
},
"skip_provider_registration": {
Default: &tfbridge.DefaultInfo{
Value: false,
EnvVars: []string{"ARM_SKIP_PROVIDER_REGISTRATION"},
},
},
"storage_use_azuread": {
Default: &tfbridge.DefaultInfo{
Value: false,
EnvVars: []string{"ARM_STORAGE_USE_AZUREAD"},
},
},
"metadata_host": {
Default: &tfbridge.DefaultInfo{
EnvVars: []string{"ARM_METADATA_HOSTNAME"},
},
},
"auxiliary_tenant_ids": {Secret: &yes},
"client_certificate": {Secret: &yes},
"client_certificate_password": {Secret: &yes},
"client_certificate_path": {Secret: &yes},
"client_id": {Secret: &yes},
"client_id_file_path": {Secret: &yes},
"client_secret": {Secret: &yes},
"client_secret_file_path": {Secret: &yes},
"oidc_request_token": {Secret: &yes},
"oidc_token": {Secret: &yes},
"oidc_token_file_path": {Secret: &yes},
"tenant_id": {Secret: &yes},
},
ExtraConfig: map[string]*tfbridge.ConfigInfo{
azureLocation: {
Schema: shimv2.NewSchema(&schema.Schema{
Type: schema.TypeString,
Optional: true,
}),
Info: &tfbridge.SchemaInfo{
Default: &tfbridge.DefaultInfo{
EnvVars: []string{"ARM_LOCATION"},
},
},
},
},
IgnoreMappings: []string{
"azurerm_network_packet_capture",
// was replaced by azurerm_virtual_machine_restore_point_collection which is identical
// except for the name, see https://github.com/hashicorp/terraform-provider-azurerm/pull/26526
"azurerm_restore_point_collection",
},
PreConfigureCallback: preConfigureCallback,
DocRules: &info.DocRule{
EditRules: func(defaults []info.DocsEdit) []info.DocsEdit {
return append(defaults, info.DocsEdit{
Path: "*",
Edit: func(_ string, content []byte) ([]byte, error) {
return []byte(strings.ReplaceAll(string(content), "imported into Terraform using", "imported into Pulumi using")), nil
},
})
},
},
Resources: map[string]*tfbridge.ResourceInfo{
// ActiveDirectoryDomainService
"azurerm_active_directory_domain_service": {
Tok: azureResource(azureDomainServices, "Service"),
},
"azurerm_active_directory_domain_service_replica_set": {
Tok: azureResource(azureDomainServices, "ReplicaSet"),
},
"azurerm_active_directory_domain_service_trust": {Tok: azureResource(azureDomainServices, "ServiceTrust")},
"azurerm_advisor_suppression": {Tok: azureResource(advisor, "Suppression"), Docs: &tfbridge.DocInfo{Source: "advisor_suppresion.html.markdown"}},
"azurerm_ai_foundry": {Tok: azureResource(aiFoundry, "Hub")},
// API Mannagement
"azurerm_api_management": {
Tok: azureResource(azureAPIManagement, "Service"),
Fields: map[string]*tfbridge.SchemaInfo{
// Max length of an API Management name is 50.
// Source: https://docs.microsoft.com/en-us/azure/architecture/best-practices/naming-conventions#general
// azureName: (azureName, 50),
azureName: tfbridge.AutoNameWithCustomOptions(azureName, tfbridge.AutoNameOptions{
Separator: "",
Maxlen: 50,
Randlen: 8,
Transform: strings.ToLower,
}),
},
},
"azurerm_api_management_api": {
Tok: azureResource(azureAPIManagement, "Api"),
Fields: map[string]*tfbridge.SchemaInfo{
// Max length of an API Management API name is 256.
// Source: https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/resource-name-rules#microsoftapimanagement
azureName: tfbridge.AutoNameWithCustomOptions(azureName, tfbridge.AutoNameOptions{
Separator: "",
Maxlen: 256,
Randlen: 8,
}),
},
},
"azurerm_api_management_api_operation": {Tok: azureResource(azureAPIManagement, "ApiOperation")},
"azurerm_api_management_api_operation_policy": {Tok: azureResource(azureAPIManagement, "ApiOperationPolicy")},
"azurerm_api_management_api_policy": {Tok: azureResource(azureAPIManagement, "ApiPolicy")},
"azurerm_api_management_api_schema": {Tok: azureResource(azureAPIManagement, "ApiSchema")},
"azurerm_api_management_api_version_set": {Tok: azureResource(azureAPIManagement, "ApiVersionSet")},
"azurerm_api_management_authorization_server": {Tok: azureResource(azureAPIManagement, "AuthorizationServer")},
"azurerm_api_management_backend": {Tok: azureResource(azureAPIManagement, "Backend")},
"azurerm_api_management_certificate": {Tok: azureResource(azureAPIManagement, "Certificate")},
"azurerm_api_management_openid_connect_provider": {Tok: azureResource(azureAPIManagement, "OpenIdConnectProvider")},
"azurerm_api_management_product": {Tok: azureResource(azureAPIManagement, "Product")},
"azurerm_api_management_product_api": {Tok: azureResource(azureAPIManagement, "ProductApi")},
"azurerm_api_management_product_group": {Tok: azureResource(azureAPIManagement, "ProductGroup")},
"azurerm_api_management_product_policy": {Tok: azureResource(azureAPIManagement, "ProductPolicy")},
"azurerm_api_management_subscription": {Tok: azureResource(azureAPIManagement, "Subscription")},
"azurerm_api_management_user": {Tok: azureResource(azureAPIManagement, "User")},
"azurerm_api_management_diagnostic": {Tok: azureResource(azureAPIManagement, "Diagnostic")},
"azurerm_api_management_identity_provider_aad": {Tok: azureResource(azureAPIManagement, "IdentityProviderAad")},
"azurerm_api_management_identity_provider_google": {Tok: azureResource(azureAPIManagement, "IdentityProviderGoogle")},
"azurerm_api_management_identity_provider_facebook": {Tok: azureResource(azureAPIManagement, "IdentityProviderFacebook")},
"azurerm_api_management_identity_provider_twitter": {Tok: azureResource(azureAPIManagement, "IdentityProviderTwitter")},
"azurerm_api_management_identity_provider_microsoft": {Tok: azureResource(azureAPIManagement, "IdentityProviderMicrosoft")},
"azurerm_api_management_named_value": {Tok: azureResource(azureAPIManagement, "NamedValue")},
"azurerm_api_management_api_diagnostic": {Tok: azureResource(azureAPIManagement, "ApiDiagnostic")},
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | true |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/provider/provider_yaml_test.go | provider/provider_yaml_test.go | // Copyright 2016-2024, Pulumi Corporation. All rights reserved.
//go:build !go && !nodejs && !python && !dotnet
// +build !go,!nodejs,!python,!dotnet
package provider
import (
"path/filepath"
"testing"
"github.com/pulumi/providertest/optproviderupgrade"
)
func Test_appinsights(t *testing.T) {
test(t, filepath.Join("test-programs", "appinsights"))
}
func Test_appservice(t *testing.T) {
test(t, filepath.Join("test-programs", "appservice"))
}
func Test_dns(t *testing.T) {
test(t, filepath.Join("test-programs", "dns"))
}
func Test_keyvault(t *testing.T) {
test(t, filepath.Join("test-programs", "keyvault"))
}
func Test_management(t *testing.T) {
test(t, filepath.Join("test-programs", "management"))
}
func Test_monitoring(t *testing.T) {
test(t, filepath.Join("test-programs", "monitoring"))
}
func Test_network(t *testing.T) {
test(t, filepath.Join("test-programs", "network"),
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "network", "v6")))
}
func Test_servicebus(t *testing.T) {
test(t, filepath.Join("test-programs", "servicebus"))
}
func Test_sql(t *testing.T) {
test(t, filepath.Join("test-programs", "sql"),
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "sql", "v6")))
}
func Test_sql_managed(t *testing.T) {
t.Skip("Waiting for more quota, Azure support request 2409140020000074")
test(t, filepath.Join("test-programs", "sql_managed"),
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "sql_managed", "v6")),
)
}
func Test_storage(t *testing.T) {
test(t, filepath.Join("test-programs", "storage"),
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "storage", "v6")))
}
func Test_automation_runbook(t *testing.T) {
test(t, filepath.Join("test-programs", "automation_runbook"))
}
func Test_cdn_profile(t *testing.T) {
test(t, filepath.Join("test-programs", "cdn_profile"),
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "cdn_profile", "v6")))
}
func Test_compute_datadiskattachment(t *testing.T) {
test(t, filepath.Join("test-programs", "compute_datadiskattachment"),
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "compute_datadiskattachment", "v6")))
}
func Test_loadbalancer(t *testing.T) {
test(t, filepath.Join("test-programs", "loadbalancer"),
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "loadbalancer", "v6")))
}
func Test_iot_iothub(t *testing.T) {
test(t, filepath.Join("test-programs", "iot_iothub"))
}
func Test_cosmosdb(t *testing.T) {
t.Skip("Can't record as all tested regions are returning 'ServiceUnavailable' error")
test(t, filepath.Join("test-programs", "cosmosdb"))
}
func Test_containerservice_k8scluster(t *testing.T) {
test(t, filepath.Join("test-programs", "containerservice_k8scluster"),
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "containerservice_k8scluster", "v6")))
}
//nolint:misspell
func Test_hdinsight(t *testing.T) {
test(t, filepath.Join("test-programs", "hdinsight"),
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "hdinsight", "v6")))
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/provider/resources_test.go | provider/resources_test.go | package provider
import (
"context"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
)
func TestLowercaseLettersAndNumbers(t *testing.T) {
cases := map[string]string{
"abc123": "abc123",
"ABC123": "abc123",
"abc-123": "abc123",
"ABC-123": "abc123",
"abc_123": "abc123",
"ABC_123": "abc123",
"abc.123": "abc123",
}
for s, expected := range cases {
assert.Equal(t, lowercaseLettersAndNumbers(s), expected)
}
}
func TestFixMssqlServerId(t *testing.T) {
t.Parallel()
const (
subscriptionID = "11111111-2222-3333-4444-555555555555"
resourceGroup = "exampleresourcegroupeb1b9585"
serverName = "superServer"
)
serverID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Sql/servers/%s",
subscriptionID, resourceGroup, serverName)
serverFirewallID := fmt.Sprintf("%s/firewallRules/exampleFwRule6fd4913", serverID)
t.Run("Happy path", func(t *testing.T) {
t.Parallel()
properties := map[string]any{
"id": serverFirewallID,
"resourceGroupName": resourceGroup,
"serverName": serverName,
}
pm := resource.NewPropertyMapFromMap(properties)
actual, err := fixMssqlServerID(context.Background(), pm)
require.NoError(t, err)
actualMap := actual.Mappable()
assert.Contains(t, actualMap, "serverId")
assert.Equal(t, serverID, actualMap["serverId"])
})
assertNoServerID := func(t *testing.T, properties map[string]any) {
pm := resource.NewPropertyMapFromMap(properties)
actual, err := fixMssqlServerID(context.Background(), pm)
require.NoError(t, err)
actualMap := actual.Mappable()
assert.NotContains(t, actualMap, "serverId")
}
t.Run("Needs serverName", func(t *testing.T) {
t.Parallel()
properties := map[string]any{
"id": serverFirewallID,
"resourceGroupName": resourceGroup,
}
assertNoServerID(t, properties)
})
t.Run("Needs id", func(t *testing.T) {
t.Parallel()
properties := map[string]any{
"resourceGroupName": resourceGroup,
"serverName": serverName,
}
assertNoServerID(t, properties)
})
t.Run("Needs resourceGroupName", func(t *testing.T) {
t.Parallel()
properties := map[string]any{
"id": serverFirewallID,
"serverName": serverName,
}
assertNoServerID(t, properties)
})
}
func TestFixMssqlManagedInstanceId(t *testing.T) {
t.Parallel()
const (
subscriptionID = "11111111-2222-3333-4444-555555555555"
resourceGroup = "exampleresourcegroupeb1b9585"
name = "myInstance"
)
instanceID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Sql/managedInstances/%s",
subscriptionID, resourceGroup, name)
failoverGroupID := fmt.Sprintf(
"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Sql/locations/eastus/instanceFailoverGroups/fail123",
subscriptionID, resourceGroup)
t.Run("Happy path", func(t *testing.T) {
t.Parallel()
properties := map[string]any{
"id": failoverGroupID,
"resourceGroupName": resourceGroup,
"managedInstanceName": name,
}
pm := resource.NewPropertyMapFromMap(properties)
actual, err := fixMssqlManagedInstanceID(context.Background(), pm)
require.NoError(t, err)
actualMap := actual.Mappable()
assert.Contains(t, actualMap, "managedInstanceId")
assert.Equal(t, instanceID, actualMap["managedInstanceId"])
})
assertNoID := func(t *testing.T, properties map[string]any) {
pm := resource.NewPropertyMapFromMap(properties)
actual, err := fixMssqlManagedInstanceID(context.Background(), pm)
require.NoError(t, err)
actualMap := actual.Mappable()
assert.NotContains(t, actualMap, "managedInstanceId")
}
t.Run("Needs managedInstanceName", func(t *testing.T) {
t.Parallel()
properties := map[string]any{
"id": failoverGroupID,
"resourceGroupName": resourceGroup,
}
assertNoID(t, properties)
})
t.Run("Needs id", func(t *testing.T) {
t.Parallel()
properties := map[string]any{
"resourceGroupName": resourceGroup,
"managedInstanceName": name,
}
assertNoID(t, properties)
})
t.Run("Needs resourceGroupName", func(t *testing.T) {
t.Parallel()
properties := map[string]any{
"id": failoverGroupID,
"managedInstanceName": name,
}
assertNoID(t, properties)
})
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/provider/provider_test.go | provider/provider_test.go | // Copyright 2016-2024, Pulumi Corporation. All rights reserved.
package provider
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
_ "embed"
"github.com/pulumi/providertest"
"github.com/pulumi/providertest/optproviderupgrade"
"github.com/pulumi/providertest/providers"
"github.com/pulumi/providertest/pulumitest"
"github.com/pulumi/providertest/pulumitest/assertpreview"
"github.com/pulumi/providertest/pulumitest/opttest"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge"
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"github.com/pulumi/pulumi-azure/provider/v6/pkg/version"
)
// Use the non-embedded schema to avoid having to run generation before running the tests.
//
//go:embed cmd/pulumi-resource-azure/schema.json
var schemaBytes []byte
func providerServer(_ providers.PulumiTest) (pulumirpc.ResourceProviderServer, error) {
ctx := context.Background()
version.Version = "0.0.1"
info := Provider()
return tfbridge.NewProvider(ctx, nil, "azure", version.Version, info.P, info, schemaBytes), nil
}
func test(t *testing.T, dir string, opts ...optproviderupgrade.PreviewProviderUpgradeOpt) {
t.Helper()
if testing.Short() {
t.Skipf("Skipping in testing.Short() mode, assuming this is a CI run without cloud credentials")
return
}
subscriptionID := getSubscriptionID(t)
rpFactory := providers.ResourceProviderFactory(providerServer)
cacheDir := providertest.GetUpgradeCacheDir(filepath.Base(dir), "5.89.0")
pt := pulumitest.NewPulumiTest(t, dir,
opttest.AttachProvider("azure",
rpFactory.ReplayInvokes(filepath.Join(cacheDir, "grpc.json"), false /* allowLiveFallback */)))
pt.SetConfig(t, "azure:subscriptionId", subscriptionID)
previewResult := providertest.PreviewProviderUpgrade(t, pt, "azure", "5.89.0", opts...)
assertpreview.HasNoReplacements(t, previewResult)
assertpreview.HasNoDeletes(t, previewResult)
}
func TestUpgradeCoverage(t *testing.T) {
providertest.ReportUpgradeCoverage(t)
}
func getSubscriptionID(t *testing.T) string {
// Prefer the environment variable, but fall back to the Azure CLI if it's not set.
// This should always be set in CI, but is useful for local testing.
subscriptionID := os.Getenv("ARM_SUBSCRIPTION_ID")
if subscriptionID == "" {
// Fetch from default Azure CLI profile
cmd := exec.Command("az", "account", "show", "--query", "id", "-o", "tsv")
out, err := cmd.Output()
if err != nil {
t.Fatal(err)
}
if len(out) == 0 {
t.Fatal("No Azure subscription ID found")
}
subscriptionID = strings.Trim(string(out), "\n")
}
return subscriptionID
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/provider/pkg/version/version.go | provider/pkg/version/version.go | // Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package version
// Version is initialized by the Go linker to contain the semver of this build.
var Version string
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/provider/cmd/pulumi-tfgen-azure/main.go | provider/cmd/pulumi-tfgen-azure/main.go | // Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfgen"
azure "github.com/pulumi/pulumi-azure/provider/v6"
"github.com/pulumi/pulumi-azure/provider/v6/pkg/version"
)
func main() {
tfgen.Main("azure", version.Version, azure.Provider())
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/provider/cmd/pulumi-resource-azure/generate.go | provider/cmd/pulumi-resource-azure/generate.go | // Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build ignore
package main
import (
"encoding/json"
"errors"
"io/fs"
"io/ioutil"
"log"
"os"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
)
func main() {
version, found := os.LookupEnv("VERSION")
if !found {
log.Fatal("version not found")
}
schemaContents, err := ioutil.ReadFile("./schema.json")
if err != nil {
log.Fatal(err)
}
var packageSpec schema.PackageSpec
err = json.Unmarshal(schemaContents, &packageSpec)
if err != nil {
log.Fatalf("cannot deserialize schema: %v", err)
}
packageSpec.Version = version
versionedContents, err := json.Marshal(packageSpec)
if err != nil {
log.Fatalf("cannot reserialize schema: %v", err)
}
// Clean up schema.go as it may be present & gitignored and tolerate an error if the file isn't present.
err = os.Remove("./schema.go")
if err != nil && !errors.Is(err, fs.ErrNotExist) {
log.Fatal(err)
}
err = ioutil.WriteFile("./schema-embed.json", versionedContents, 0600)
if err != nil {
log.Fatal(err)
}
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/provider/cmd/pulumi-resource-azure/main.go | provider/cmd/pulumi-resource-azure/main.go | // Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:generate go run ./generate.go
package main
import (
_ "embed"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge"
azure "github.com/pulumi/pulumi-azure/provider/v6"
"github.com/pulumi/pulumi-azure/provider/v6/pkg/version"
)
//go:embed schema-embed.json
var pulumiSchema []byte
func main() {
tfbridge.Main("azure", version.Version, azure.Provider(), pulumiSchema)
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/examples/examples_py_test.go | examples/examples_py_test.go | // Copyright 2016-2017, Pulumi Corporation. All rights reserved.
//go:build python || all
// +build python all
package examples
import (
"path/filepath"
"testing"
"github.com/pulumi/pulumi/pkg/v3/testing/integration"
)
func getPythonBaseOptions(t *testing.T) integration.ProgramTestOptions {
base := getBaseOptions(t)
pythonBase := base.With(integration.ProgramTestOptions{
Dependencies: []string{
filepath.Join("..", "sdk", "python", "bin"),
},
})
return pythonBase
}
func TestAccDatasourcePy(t *testing.T) {
test := getPythonBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "datasource-py"),
RunUpdateTest: true,
})
integration.ProgramTest(t, &test)
}
func TestAccEventhubPy(t *testing.T) {
test := getPythonBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "eventhub-py"),
RunUpdateTest: true,
// work around https://github.com/terraform-providers/terraform-provider-azurerm/issues/4598
AllowEmptyPreviewChanges: true,
AllowEmptyUpdateChanges: true,
})
integration.ProgramTest(t, &test)
}
func TestAccMinimalPy(t *testing.T) {
test := getPythonBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "minimal-py"),
})
integration.ProgramTest(t, &test)
}
func TestAccWebserverPy(t *testing.T) {
t.Skip("Skipping until v2.80.0 release comes out upstream")
for _, dir := range []string{"webserver-py", "webserver-py-old"} {
t.Run(dir, func(t *testing.T) {
test := getPythonBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), dir),
RunUpdateTest: true,
ExpectRefreshChanges: true,
})
integration.ProgramTest(t, &test)
})
}
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/examples/examples_dotnet_test.go | examples/examples_dotnet_test.go | // Copyright 2016-2017, Pulumi Corporation. All rights reserved.
//go:build dotnet || all
// +build dotnet all
package examples
import (
"path/filepath"
"testing"
"github.com/pulumi/pulumi/pkg/v3/testing/integration"
"github.com/stretchr/testify/assert"
)
func getCSBaseOptions(t *testing.T) integration.ProgramTestOptions {
base := getBaseOptions(t)
baseJS := base.With(integration.ProgramTestOptions{
Dependencies: []string{
"Pulumi.Azure",
},
})
return baseJS
}
func TestAccAppServiceCs(t *testing.T) {
test := getCSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "appservice-cs"),
ExtraRuntimeValidation: validateAPITest(func(body string) {
assert.Equal(t, body, "Hello Pulumi")
}),
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/examples/examples_test.go | examples/examples_test.go | // Copyright 2016-2017, Pulumi Corporation. All rights reserved.
package examples
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/pulumi/pulumi/pkg/v3/testing/integration"
)
func skipIfShort(t *testing.T) {
if testing.Short() {
t.Skip("skipping long-running test in short mode")
}
}
func getLocation(t *testing.T) string {
azureLocation := os.Getenv("ARM_LOCATION")
if azureLocation == "" {
azureLocation = "westus"
fmt.Println("Defaulting ARM_LOCATION to 'westus'. You can override using the ARM_LOCATION variable")
}
return azureLocation
}
func getSubscriptionID(t *testing.T) string {
// Prefer the environment variable, but fall back to the Azure CLI if it's not set.
// This should always be set in CI, but is useful for local testing.
subscriptionID := os.Getenv("ARM_SUBSCRIPTION_ID")
if subscriptionID == "" {
// Fetch from default Azure CLI profile
cmd := exec.Command("az", "account", "show", "--query", "id", "-o", "tsv")
out, err := cmd.Output()
if err != nil {
t.Fatal(err)
}
if len(out) == 0 {
t.Fatal("No Azure subscription ID found")
}
subscriptionID = strings.Trim(string(out), "\n")
}
return subscriptionID
}
func getCwd(t *testing.T) string {
cwd, err := os.Getwd()
if err != nil {
t.FailNow()
}
return cwd
}
func getBaseOptions(t *testing.T) integration.ProgramTestOptions {
azureLocation := getLocation(t)
binPath, err := filepath.Abs("../bin")
if err != nil {
t.Fatal(err)
}
fmt.Printf("Using binPath %s\n", binPath)
subscriptionId := getSubscriptionID(t)
return integration.ProgramTestOptions{
Config: map[string]string{
"azure:location": azureLocation,
"azure:subscriptionId": subscriptionId,
},
LocalProviders: []integration.LocalDependency{
{
Package: "azure",
Path: binPath,
},
},
}
}
func validateAPITest(isValid func(body string)) func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
return func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
var resp *http.Response
var err error
url := stack.Outputs["url"].(string)
// Retry a couple times on 5xx
for i := 0; i < 5; i++ {
resp, err = http.Get(url)
if !assert.NoError(t, err) {
return
}
if resp.StatusCode < 500 {
break
}
time.Sleep(10 * time.Second)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
assert.NoError(t, err)
isValid(string(body))
}
}
// A lot of tests currently generate non-empty diffs upon refresh. While the work of root-causing
// each individual test has not been done yet, a few common known causes are listed here:
//
// TODO[pulumi/pulumi-terraform-bridge#1595]
// TODO[pulumi/pulumi-azure#1568]
func skipRefresh(opts *integration.ProgramTestOptions) {
opts.SkipRefresh = true
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/examples/examples_nodejs_test.go | examples/examples_nodejs_test.go | // Copyright 2016-2017, Pulumi Corporation. All rights reserved.
//go:build nodejs || all
// +build nodejs all
package examples
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/pulumi/pulumi/pkg/v3/testing/integration"
"github.com/stretchr/testify/assert"
)
func getJSBaseOptions(t *testing.T) integration.ProgramTestOptions {
base := getBaseOptions(t)
baseJS := base.With(integration.ProgramTestOptions{
Dependencies: []string{
"@pulumi/azure",
},
})
return baseJS
}
func TestAccMultiCallback(t *testing.T) {
skipIfShort(t)
t.Skip("Skipping due to Azure capacity issues")
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "multi-callback-all"),
// RunUpdateTest: true,
AllowEmptyPreviewChanges: true,
AllowEmptyUpdateChanges: true,
})
integration.ProgramTest(t, &test)
}
func TestAccLoadbalancer(t *testing.T) {
t.Skipf("Skipping due to flake: https://github.com/pulumi/pulumi-azure/issues/1703")
skipIfShort(t)
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "loadbalancer"),
// TODO[pulumi/pulumi-azure#1571] various issues with non-empty refresh.
SkipRefresh: true,
})
integration.ProgramTest(t, &test)
}
func TestAccCosmosDb(t *testing.T) {
skipIfShort(t)
t.Skip("Skipping due to Azure capacity issues")
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "cosmosdb"),
RunUpdateTest: true,
})
integration.ProgramTest(t, &test)
}
func TestAccAciVolumeMount(t *testing.T) {
skipIfShort(t)
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "aci-volume-mount"),
RunUpdateTest: false,
SkipEmptyPreviewUpdate: true,
ExpectRefreshChanges: true,
})
integration.ProgramTest(t, &test)
}
func TestAccAciMulti(t *testing.T) {
skipIfShort(t)
t.Skip("Skipping due to Azure Gateway Timeout issues")
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "aci-multi"),
RunUpdateTest: true,
})
integration.ProgramTest(t, &test)
}
func TestAccTable(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "table"),
RunUpdateTest: true,
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
func TestAccServicebusMigration(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "servicebus-migration-test"),
// RunUpdateTest: true,
EditDirs: []integration.EditDir{
{
Dir: filepath.Join("servicebus-migration-test", "step2"),
Additive: true,
ExpectNoChanges: true,
},
},
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
func TestAccMsiRenamed(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "msi-renamed-to-authorization"),
RunUpdateTest: true,
EditDirs: []integration.EditDir{
{
Dir: filepath.Join("msi-renamed-to-authorization", "step2"),
Additive: true,
ExpectNoChanges: true,
},
},
})
integration.ProgramTest(t, &test)
}
func TestAccBlob(t *testing.T) {
t.Skip("Temp skipping due to functions issues")
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "blob"),
RunUpdateTest: true,
ExtraRuntimeValidation: validateAPITest(func(body string) {
assert.Equal(t, body, "A File from Blob Storage")
}),
})
integration.ProgramTest(t, &test)
}
func TestAccHttp(t *testing.T) {
t.Skip("Skipping due to Azure Gateway Timeout issues")
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "http"),
RunUpdateTest: true,
ExtraRuntimeValidation: validateAPITest(func(body string) {
assert.Equal(t, body, "Hello World!")
}),
})
integration.ProgramTest(t, &test)
}
func TestAccNetwork(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "network"),
RunUpdateTest: true,
ExpectRefreshChanges: true,
})
integration.ProgramTest(t, &test)
}
func TestAccNetwork_OIDC(t *testing.T) {
oidcClientId := os.Getenv("OIDC_ARM_CLIENT_ID")
if oidcClientId == "" {
t.Skip("Skipping OIDC test without OIDC_ARM_CLIENT_ID")
}
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "network"),
RunUpdateTest: true,
ExpectRefreshChanges: true,
Env: []string{
"ARM_USE_OIDC=true",
"ARM_CLIENT_ID=" + oidcClientId,
// not strictly necessary but making sure we test the OIDC path
"ARM_CLIENT_SECRET=",
},
})
integration.ProgramTest(t, &test)
}
func TestAccWebserver(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "webserver"),
// RunUpdateTest: true,
ExpectRefreshChanges: true,
})
integration.ProgramTest(t, &test)
}
func TestAccTopic(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "topic"),
// RunUpdateTest: true,
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
func TestAccTimer(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "timer"),
RunUpdateTest: true,
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
func TestAccQueue(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "queue"),
RunUpdateTest: true,
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
func TestAccIot(t *testing.T) {
t.Skip(`Fails with error: TypeError: sharedAccessPolicies.find is not a function
at /home/runner/work/pulumi-azure/pulumi-azure/sdk/nodejs/iot/zMixins.ts:142:131`)
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "iot"),
RunUpdateTest: true,
})
integration.ProgramTest(t, &test)
}
func TestAccMinimal(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "minimal"),
})
integration.ProgramTest(t, &test)
}
func TestAccDurableFunctions(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "durable-functions"),
RunUpdateTest: false,
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
func TestAccEventgrid(t *testing.T) {
t.Skip(`Passes locally but fails in CI with 'Waiting for 'eventgrid_extension' key to become available' until timeout. #2222`)
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "eventgrid"),
RunUpdateTest: false,
AllowEmptyPreviewChanges: true,
AllowEmptyUpdateChanges: true,
// Getting the following diff:
// "diffs": [
// "webhookEndpoint"
// ],
// "detailedDiff": {
// "webhookEndpoint.maxEventsPerBatch": {
// "kind": "DELETE"
// },
// "webhookEndpoint.preferredBatchSizeInKilobytes": {
// "kind": "DELETE"
// }
// }
// even though the webhook is simply created as
// webhookEndpoint: { url: liveUrl }
// in eventgrid/zMixins.ts.
ExpectRefreshChanges: true,
})
integration.ProgramTest(t, &test)
}
func TestAccEventhub(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "eventhub"),
RunUpdateTest: true,
AllowEmptyPreviewChanges: true,
AllowEmptyUpdateChanges: true,
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
func TestAccHttpExternal(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "http-external"),
RunUpdateTest: true,
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
func TestAccHttpMulti(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "http-multi"),
RunUpdateTest: true,
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
func TestAccSecretCapture(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "http"),
RunUpdateTest: true,
ExtraRuntimeValidation: func(t *testing.T, info integration.RuntimeValidationStackInfo) {
byts, err := json.Marshal(info.Deployment)
assert.NoError(t, err)
assert.NotContains(t, "s3cr3t", string(byts))
},
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
func TestAccLinuxVirtualMachines(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "linux-virtual-machine"),
RunUpdateTest: true,
})
skipRefresh(&test)
integration.ProgramTest(t, &test)
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/examples/examples_go_test.go | examples/examples_go_test.go | // Copyright 2016-2017, Pulumi Corporation. All rights reserved.
//go:build go || all
// +build go all
package examples
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/pulumi/pulumi/pkg/v3/testing/integration"
"github.com/stretchr/testify/require"
)
func getGoBaseOptions(t *testing.T) integration.ProgramTestOptions {
goDepRoot := os.Getenv("PULUMI_GO_DEP_ROOT")
if goDepRoot == "" {
var err error
goDepRoot, err = filepath.Abs("../..")
require.NoError(t, err)
}
rootSdkPath, err := filepath.Abs("../sdk")
require.NoError(t, err)
base := getBaseOptions(t)
baseJS := base.With(integration.ProgramTestOptions{
Dependencies: []string{
fmt.Sprintf("github.com/pulumi/pulumi-azure/sdk/v6=%s", rootSdkPath),
},
Env: []string{
fmt.Sprintf("PULUMI_GO_DEP_ROOT=%s", goDepRoot),
},
})
return baseJS
}
func TestAccNetworkGo(t *testing.T) {
test := getGoBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "network-go"),
// TODO[pulumi/pulumi-azure#1569] refresh tries to edit subnets
SkipRefresh: true,
})
integration.ProgramTest(t, &test)
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/examples/network-go/main.go | examples/network-go/main.go | // Copyright 2016-2019, Pulumi Corporation. All rights reserved.
package main
import (
"github.com/pulumi/pulumi-azure/sdk/v6/go/azure/core"
"github.com/pulumi/pulumi-azure/sdk/v6/go/azure/network"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
func main() {
pulumi.Run(func(ctx *pulumi.Context) error {
rg, err := core.NewResourceGroup(ctx, "server-rg", &core.ResourceGroupArgs{
Location: pulumi.String("WestUS"),
})
if err != nil {
return err
}
// Create a network and subnet for all VMs.
vnet, err := network.NewVirtualNetwork(ctx, "server-network", &network.VirtualNetworkArgs{
ResourceGroupName: rg.Name,
AddressSpaces: pulumi.StringArray{pulumi.String("10.0.0.0/16")},
})
if err != nil {
return err
}
_, err = network.NewSubnet(ctx, "subnet", &network.SubnetArgs{
ResourceGroupName: rg.Name,
VirtualNetworkName: vnet.Name,
AddressPrefixes: pulumi.StringArray{pulumi.String("10.0.0.0/16")},
})
if err != nil {
return err
}
return nil
})
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/sdk/go/azure/init.go | sdk/go/azure/init.go | // Code generated by pulumi-language-go DO NOT EDIT.
// *** WARNING: Do not edit by hand unless you're certain you know what you are doing! ***
package azure
import (
"fmt"
"github.com/blang/semver"
"github.com/pulumi/pulumi-azure/sdk/v6/go/azure/internal"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
type pkg struct {
version semver.Version
}
func (p *pkg) Version() semver.Version {
return p.version
}
func (p *pkg) ConstructProvider(ctx *pulumi.Context, name, typ, urn string) (pulumi.ProviderResource, error) {
if typ != "pulumi:providers:azure" {
return nil, fmt.Errorf("unknown provider type: %s", typ)
}
r := &Provider{}
err := ctx.RegisterResource(typ, name, nil, r, pulumi.URN_(urn))
return r, err
}
func init() {
version, err := internal.PkgVersion()
if err != nil {
version = semver.Version{Major: 1}
}
pulumi.RegisterResourcePackage(
"azure",
&pkg{version},
)
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | false |
pulumi/pulumi-azure | https://github.com/pulumi/pulumi-azure/blob/b66e1472775a89cca43f5050fef806854a7c3fa3/sdk/go/azure/pulumiTypes.go | sdk/go/azure/pulumiTypes.go | // Code generated by pulumi-language-go DO NOT EDIT.
// *** WARNING: Do not edit by hand unless you're certain you know what you are doing! ***
package azure
import (
"context"
"reflect"
"github.com/pulumi/pulumi-azure/sdk/v6/go/azure/internal"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
var _ = internal.GetEnvOrDefault
type ProviderFeatures struct {
ApiManagement *ProviderFeaturesApiManagement `pulumi:"apiManagement"`
AppConfiguration *ProviderFeaturesAppConfiguration `pulumi:"appConfiguration"`
ApplicationInsights *ProviderFeaturesApplicationInsights `pulumi:"applicationInsights"`
CognitiveAccount *ProviderFeaturesCognitiveAccount `pulumi:"cognitiveAccount"`
DatabricksWorkspace *ProviderFeaturesDatabricksWorkspace `pulumi:"databricksWorkspace"`
KeyVault *ProviderFeaturesKeyVault `pulumi:"keyVault"`
LogAnalyticsWorkspace *ProviderFeaturesLogAnalyticsWorkspace `pulumi:"logAnalyticsWorkspace"`
MachineLearning *ProviderFeaturesMachineLearning `pulumi:"machineLearning"`
ManagedDisk *ProviderFeaturesManagedDisk `pulumi:"managedDisk"`
Netapp *ProviderFeaturesNetapp `pulumi:"netapp"`
PostgresqlFlexibleServer *ProviderFeaturesPostgresqlFlexibleServer `pulumi:"postgresqlFlexibleServer"`
RecoveryService *ProviderFeaturesRecoveryService `pulumi:"recoveryService"`
RecoveryServicesVaults *ProviderFeaturesRecoveryServicesVaults `pulumi:"recoveryServicesVaults"`
ResourceGroup *ProviderFeaturesResourceGroup `pulumi:"resourceGroup"`
Storage *ProviderFeaturesStorage `pulumi:"storage"`
Subscription *ProviderFeaturesSubscription `pulumi:"subscription"`
TemplateDeployment *ProviderFeaturesTemplateDeployment `pulumi:"templateDeployment"`
VirtualMachine *ProviderFeaturesVirtualMachine `pulumi:"virtualMachine"`
VirtualMachineScaleSet *ProviderFeaturesVirtualMachineScaleSet `pulumi:"virtualMachineScaleSet"`
}
// ProviderFeaturesInput is an input type that accepts ProviderFeaturesArgs and ProviderFeaturesOutput values.
// You can construct a concrete instance of `ProviderFeaturesInput` via:
//
// ProviderFeaturesArgs{...}
type ProviderFeaturesInput interface {
pulumi.Input
ToProviderFeaturesOutput() ProviderFeaturesOutput
ToProviderFeaturesOutputWithContext(context.Context) ProviderFeaturesOutput
}
type ProviderFeaturesArgs struct {
ApiManagement ProviderFeaturesApiManagementPtrInput `pulumi:"apiManagement"`
AppConfiguration ProviderFeaturesAppConfigurationPtrInput `pulumi:"appConfiguration"`
ApplicationInsights ProviderFeaturesApplicationInsightsPtrInput `pulumi:"applicationInsights"`
CognitiveAccount ProviderFeaturesCognitiveAccountPtrInput `pulumi:"cognitiveAccount"`
DatabricksWorkspace ProviderFeaturesDatabricksWorkspacePtrInput `pulumi:"databricksWorkspace"`
KeyVault ProviderFeaturesKeyVaultPtrInput `pulumi:"keyVault"`
LogAnalyticsWorkspace ProviderFeaturesLogAnalyticsWorkspacePtrInput `pulumi:"logAnalyticsWorkspace"`
MachineLearning ProviderFeaturesMachineLearningPtrInput `pulumi:"machineLearning"`
ManagedDisk ProviderFeaturesManagedDiskPtrInput `pulumi:"managedDisk"`
Netapp ProviderFeaturesNetappPtrInput `pulumi:"netapp"`
PostgresqlFlexibleServer ProviderFeaturesPostgresqlFlexibleServerPtrInput `pulumi:"postgresqlFlexibleServer"`
RecoveryService ProviderFeaturesRecoveryServicePtrInput `pulumi:"recoveryService"`
RecoveryServicesVaults ProviderFeaturesRecoveryServicesVaultsPtrInput `pulumi:"recoveryServicesVaults"`
ResourceGroup ProviderFeaturesResourceGroupPtrInput `pulumi:"resourceGroup"`
Storage ProviderFeaturesStoragePtrInput `pulumi:"storage"`
Subscription ProviderFeaturesSubscriptionPtrInput `pulumi:"subscription"`
TemplateDeployment ProviderFeaturesTemplateDeploymentPtrInput `pulumi:"templateDeployment"`
VirtualMachine ProviderFeaturesVirtualMachinePtrInput `pulumi:"virtualMachine"`
VirtualMachineScaleSet ProviderFeaturesVirtualMachineScaleSetPtrInput `pulumi:"virtualMachineScaleSet"`
}
func (ProviderFeaturesArgs) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderFeatures)(nil)).Elem()
}
func (i ProviderFeaturesArgs) ToProviderFeaturesOutput() ProviderFeaturesOutput {
return i.ToProviderFeaturesOutputWithContext(context.Background())
}
func (i ProviderFeaturesArgs) ToProviderFeaturesOutputWithContext(ctx context.Context) ProviderFeaturesOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderFeaturesOutput)
}
func (i ProviderFeaturesArgs) ToProviderFeaturesPtrOutput() ProviderFeaturesPtrOutput {
return i.ToProviderFeaturesPtrOutputWithContext(context.Background())
}
func (i ProviderFeaturesArgs) ToProviderFeaturesPtrOutputWithContext(ctx context.Context) ProviderFeaturesPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderFeaturesOutput).ToProviderFeaturesPtrOutputWithContext(ctx)
}
// ProviderFeaturesPtrInput is an input type that accepts ProviderFeaturesArgs, ProviderFeaturesPtr and ProviderFeaturesPtrOutput values.
// You can construct a concrete instance of `ProviderFeaturesPtrInput` via:
//
// ProviderFeaturesArgs{...}
//
// or:
//
// nil
type ProviderFeaturesPtrInput interface {
pulumi.Input
ToProviderFeaturesPtrOutput() ProviderFeaturesPtrOutput
ToProviderFeaturesPtrOutputWithContext(context.Context) ProviderFeaturesPtrOutput
}
type providerFeaturesPtrType ProviderFeaturesArgs
func ProviderFeaturesPtr(v *ProviderFeaturesArgs) ProviderFeaturesPtrInput {
return (*providerFeaturesPtrType)(v)
}
func (*providerFeaturesPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**ProviderFeatures)(nil)).Elem()
}
func (i *providerFeaturesPtrType) ToProviderFeaturesPtrOutput() ProviderFeaturesPtrOutput {
return i.ToProviderFeaturesPtrOutputWithContext(context.Background())
}
func (i *providerFeaturesPtrType) ToProviderFeaturesPtrOutputWithContext(ctx context.Context) ProviderFeaturesPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderFeaturesPtrOutput)
}
type ProviderFeaturesOutput struct{ *pulumi.OutputState }
func (ProviderFeaturesOutput) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderFeatures)(nil)).Elem()
}
func (o ProviderFeaturesOutput) ToProviderFeaturesOutput() ProviderFeaturesOutput {
return o
}
func (o ProviderFeaturesOutput) ToProviderFeaturesOutputWithContext(ctx context.Context) ProviderFeaturesOutput {
return o
}
func (o ProviderFeaturesOutput) ToProviderFeaturesPtrOutput() ProviderFeaturesPtrOutput {
return o.ToProviderFeaturesPtrOutputWithContext(context.Background())
}
func (o ProviderFeaturesOutput) ToProviderFeaturesPtrOutputWithContext(ctx context.Context) ProviderFeaturesPtrOutput {
return o.ApplyTWithContext(ctx, func(_ context.Context, v ProviderFeatures) *ProviderFeatures {
return &v
}).(ProviderFeaturesPtrOutput)
}
func (o ProviderFeaturesOutput) ApiManagement() ProviderFeaturesApiManagementPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesApiManagement { return v.ApiManagement }).(ProviderFeaturesApiManagementPtrOutput)
}
func (o ProviderFeaturesOutput) AppConfiguration() ProviderFeaturesAppConfigurationPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesAppConfiguration { return v.AppConfiguration }).(ProviderFeaturesAppConfigurationPtrOutput)
}
func (o ProviderFeaturesOutput) ApplicationInsights() ProviderFeaturesApplicationInsightsPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesApplicationInsights { return v.ApplicationInsights }).(ProviderFeaturesApplicationInsightsPtrOutput)
}
func (o ProviderFeaturesOutput) CognitiveAccount() ProviderFeaturesCognitiveAccountPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesCognitiveAccount { return v.CognitiveAccount }).(ProviderFeaturesCognitiveAccountPtrOutput)
}
func (o ProviderFeaturesOutput) DatabricksWorkspace() ProviderFeaturesDatabricksWorkspacePtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesDatabricksWorkspace { return v.DatabricksWorkspace }).(ProviderFeaturesDatabricksWorkspacePtrOutput)
}
func (o ProviderFeaturesOutput) KeyVault() ProviderFeaturesKeyVaultPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesKeyVault { return v.KeyVault }).(ProviderFeaturesKeyVaultPtrOutput)
}
func (o ProviderFeaturesOutput) LogAnalyticsWorkspace() ProviderFeaturesLogAnalyticsWorkspacePtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesLogAnalyticsWorkspace { return v.LogAnalyticsWorkspace }).(ProviderFeaturesLogAnalyticsWorkspacePtrOutput)
}
func (o ProviderFeaturesOutput) MachineLearning() ProviderFeaturesMachineLearningPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesMachineLearning { return v.MachineLearning }).(ProviderFeaturesMachineLearningPtrOutput)
}
func (o ProviderFeaturesOutput) ManagedDisk() ProviderFeaturesManagedDiskPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesManagedDisk { return v.ManagedDisk }).(ProviderFeaturesManagedDiskPtrOutput)
}
func (o ProviderFeaturesOutput) Netapp() ProviderFeaturesNetappPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesNetapp { return v.Netapp }).(ProviderFeaturesNetappPtrOutput)
}
func (o ProviderFeaturesOutput) PostgresqlFlexibleServer() ProviderFeaturesPostgresqlFlexibleServerPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesPostgresqlFlexibleServer { return v.PostgresqlFlexibleServer }).(ProviderFeaturesPostgresqlFlexibleServerPtrOutput)
}
func (o ProviderFeaturesOutput) RecoveryService() ProviderFeaturesRecoveryServicePtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesRecoveryService { return v.RecoveryService }).(ProviderFeaturesRecoveryServicePtrOutput)
}
func (o ProviderFeaturesOutput) RecoveryServicesVaults() ProviderFeaturesRecoveryServicesVaultsPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesRecoveryServicesVaults { return v.RecoveryServicesVaults }).(ProviderFeaturesRecoveryServicesVaultsPtrOutput)
}
func (o ProviderFeaturesOutput) ResourceGroup() ProviderFeaturesResourceGroupPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesResourceGroup { return v.ResourceGroup }).(ProviderFeaturesResourceGroupPtrOutput)
}
func (o ProviderFeaturesOutput) Storage() ProviderFeaturesStoragePtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesStorage { return v.Storage }).(ProviderFeaturesStoragePtrOutput)
}
func (o ProviderFeaturesOutput) Subscription() ProviderFeaturesSubscriptionPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesSubscription { return v.Subscription }).(ProviderFeaturesSubscriptionPtrOutput)
}
func (o ProviderFeaturesOutput) TemplateDeployment() ProviderFeaturesTemplateDeploymentPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesTemplateDeployment { return v.TemplateDeployment }).(ProviderFeaturesTemplateDeploymentPtrOutput)
}
func (o ProviderFeaturesOutput) VirtualMachine() ProviderFeaturesVirtualMachinePtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesVirtualMachine { return v.VirtualMachine }).(ProviderFeaturesVirtualMachinePtrOutput)
}
func (o ProviderFeaturesOutput) VirtualMachineScaleSet() ProviderFeaturesVirtualMachineScaleSetPtrOutput {
return o.ApplyT(func(v ProviderFeatures) *ProviderFeaturesVirtualMachineScaleSet { return v.VirtualMachineScaleSet }).(ProviderFeaturesVirtualMachineScaleSetPtrOutput)
}
type ProviderFeaturesPtrOutput struct{ *pulumi.OutputState }
func (ProviderFeaturesPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**ProviderFeatures)(nil)).Elem()
}
func (o ProviderFeaturesPtrOutput) ToProviderFeaturesPtrOutput() ProviderFeaturesPtrOutput {
return o
}
func (o ProviderFeaturesPtrOutput) ToProviderFeaturesPtrOutputWithContext(ctx context.Context) ProviderFeaturesPtrOutput {
return o
}
func (o ProviderFeaturesPtrOutput) Elem() ProviderFeaturesOutput {
return o.ApplyT(func(v *ProviderFeatures) ProviderFeatures {
if v != nil {
return *v
}
var ret ProviderFeatures
return ret
}).(ProviderFeaturesOutput)
}
func (o ProviderFeaturesPtrOutput) ApiManagement() ProviderFeaturesApiManagementPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesApiManagement {
if v == nil {
return nil
}
return v.ApiManagement
}).(ProviderFeaturesApiManagementPtrOutput)
}
func (o ProviderFeaturesPtrOutput) AppConfiguration() ProviderFeaturesAppConfigurationPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesAppConfiguration {
if v == nil {
return nil
}
return v.AppConfiguration
}).(ProviderFeaturesAppConfigurationPtrOutput)
}
func (o ProviderFeaturesPtrOutput) ApplicationInsights() ProviderFeaturesApplicationInsightsPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesApplicationInsights {
if v == nil {
return nil
}
return v.ApplicationInsights
}).(ProviderFeaturesApplicationInsightsPtrOutput)
}
func (o ProviderFeaturesPtrOutput) CognitiveAccount() ProviderFeaturesCognitiveAccountPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesCognitiveAccount {
if v == nil {
return nil
}
return v.CognitiveAccount
}).(ProviderFeaturesCognitiveAccountPtrOutput)
}
func (o ProviderFeaturesPtrOutput) DatabricksWorkspace() ProviderFeaturesDatabricksWorkspacePtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesDatabricksWorkspace {
if v == nil {
return nil
}
return v.DatabricksWorkspace
}).(ProviderFeaturesDatabricksWorkspacePtrOutput)
}
func (o ProviderFeaturesPtrOutput) KeyVault() ProviderFeaturesKeyVaultPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesKeyVault {
if v == nil {
return nil
}
return v.KeyVault
}).(ProviderFeaturesKeyVaultPtrOutput)
}
func (o ProviderFeaturesPtrOutput) LogAnalyticsWorkspace() ProviderFeaturesLogAnalyticsWorkspacePtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesLogAnalyticsWorkspace {
if v == nil {
return nil
}
return v.LogAnalyticsWorkspace
}).(ProviderFeaturesLogAnalyticsWorkspacePtrOutput)
}
func (o ProviderFeaturesPtrOutput) MachineLearning() ProviderFeaturesMachineLearningPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesMachineLearning {
if v == nil {
return nil
}
return v.MachineLearning
}).(ProviderFeaturesMachineLearningPtrOutput)
}
func (o ProviderFeaturesPtrOutput) ManagedDisk() ProviderFeaturesManagedDiskPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesManagedDisk {
if v == nil {
return nil
}
return v.ManagedDisk
}).(ProviderFeaturesManagedDiskPtrOutput)
}
func (o ProviderFeaturesPtrOutput) Netapp() ProviderFeaturesNetappPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesNetapp {
if v == nil {
return nil
}
return v.Netapp
}).(ProviderFeaturesNetappPtrOutput)
}
func (o ProviderFeaturesPtrOutput) PostgresqlFlexibleServer() ProviderFeaturesPostgresqlFlexibleServerPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesPostgresqlFlexibleServer {
if v == nil {
return nil
}
return v.PostgresqlFlexibleServer
}).(ProviderFeaturesPostgresqlFlexibleServerPtrOutput)
}
func (o ProviderFeaturesPtrOutput) RecoveryService() ProviderFeaturesRecoveryServicePtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesRecoveryService {
if v == nil {
return nil
}
return v.RecoveryService
}).(ProviderFeaturesRecoveryServicePtrOutput)
}
func (o ProviderFeaturesPtrOutput) RecoveryServicesVaults() ProviderFeaturesRecoveryServicesVaultsPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesRecoveryServicesVaults {
if v == nil {
return nil
}
return v.RecoveryServicesVaults
}).(ProviderFeaturesRecoveryServicesVaultsPtrOutput)
}
func (o ProviderFeaturesPtrOutput) ResourceGroup() ProviderFeaturesResourceGroupPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesResourceGroup {
if v == nil {
return nil
}
return v.ResourceGroup
}).(ProviderFeaturesResourceGroupPtrOutput)
}
func (o ProviderFeaturesPtrOutput) Storage() ProviderFeaturesStoragePtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesStorage {
if v == nil {
return nil
}
return v.Storage
}).(ProviderFeaturesStoragePtrOutput)
}
func (o ProviderFeaturesPtrOutput) Subscription() ProviderFeaturesSubscriptionPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesSubscription {
if v == nil {
return nil
}
return v.Subscription
}).(ProviderFeaturesSubscriptionPtrOutput)
}
func (o ProviderFeaturesPtrOutput) TemplateDeployment() ProviderFeaturesTemplateDeploymentPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesTemplateDeployment {
if v == nil {
return nil
}
return v.TemplateDeployment
}).(ProviderFeaturesTemplateDeploymentPtrOutput)
}
func (o ProviderFeaturesPtrOutput) VirtualMachine() ProviderFeaturesVirtualMachinePtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesVirtualMachine {
if v == nil {
return nil
}
return v.VirtualMachine
}).(ProviderFeaturesVirtualMachinePtrOutput)
}
func (o ProviderFeaturesPtrOutput) VirtualMachineScaleSet() ProviderFeaturesVirtualMachineScaleSetPtrOutput {
return o.ApplyT(func(v *ProviderFeatures) *ProviderFeaturesVirtualMachineScaleSet {
if v == nil {
return nil
}
return v.VirtualMachineScaleSet
}).(ProviderFeaturesVirtualMachineScaleSetPtrOutput)
}
type ProviderFeaturesApiManagement struct {
PurgeSoftDeleteOnDestroy *bool `pulumi:"purgeSoftDeleteOnDestroy"`
RecoverSoftDeleted *bool `pulumi:"recoverSoftDeleted"`
}
// ProviderFeaturesApiManagementInput is an input type that accepts ProviderFeaturesApiManagementArgs and ProviderFeaturesApiManagementOutput values.
// You can construct a concrete instance of `ProviderFeaturesApiManagementInput` via:
//
// ProviderFeaturesApiManagementArgs{...}
type ProviderFeaturesApiManagementInput interface {
pulumi.Input
ToProviderFeaturesApiManagementOutput() ProviderFeaturesApiManagementOutput
ToProviderFeaturesApiManagementOutputWithContext(context.Context) ProviderFeaturesApiManagementOutput
}
type ProviderFeaturesApiManagementArgs struct {
PurgeSoftDeleteOnDestroy pulumi.BoolPtrInput `pulumi:"purgeSoftDeleteOnDestroy"`
RecoverSoftDeleted pulumi.BoolPtrInput `pulumi:"recoverSoftDeleted"`
}
func (ProviderFeaturesApiManagementArgs) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderFeaturesApiManagement)(nil)).Elem()
}
func (i ProviderFeaturesApiManagementArgs) ToProviderFeaturesApiManagementOutput() ProviderFeaturesApiManagementOutput {
return i.ToProviderFeaturesApiManagementOutputWithContext(context.Background())
}
func (i ProviderFeaturesApiManagementArgs) ToProviderFeaturesApiManagementOutputWithContext(ctx context.Context) ProviderFeaturesApiManagementOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderFeaturesApiManagementOutput)
}
func (i ProviderFeaturesApiManagementArgs) ToProviderFeaturesApiManagementPtrOutput() ProviderFeaturesApiManagementPtrOutput {
return i.ToProviderFeaturesApiManagementPtrOutputWithContext(context.Background())
}
func (i ProviderFeaturesApiManagementArgs) ToProviderFeaturesApiManagementPtrOutputWithContext(ctx context.Context) ProviderFeaturesApiManagementPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderFeaturesApiManagementOutput).ToProviderFeaturesApiManagementPtrOutputWithContext(ctx)
}
// ProviderFeaturesApiManagementPtrInput is an input type that accepts ProviderFeaturesApiManagementArgs, ProviderFeaturesApiManagementPtr and ProviderFeaturesApiManagementPtrOutput values.
// You can construct a concrete instance of `ProviderFeaturesApiManagementPtrInput` via:
//
// ProviderFeaturesApiManagementArgs{...}
//
// or:
//
// nil
type ProviderFeaturesApiManagementPtrInput interface {
pulumi.Input
ToProviderFeaturesApiManagementPtrOutput() ProviderFeaturesApiManagementPtrOutput
ToProviderFeaturesApiManagementPtrOutputWithContext(context.Context) ProviderFeaturesApiManagementPtrOutput
}
type providerFeaturesApiManagementPtrType ProviderFeaturesApiManagementArgs
func ProviderFeaturesApiManagementPtr(v *ProviderFeaturesApiManagementArgs) ProviderFeaturesApiManagementPtrInput {
return (*providerFeaturesApiManagementPtrType)(v)
}
func (*providerFeaturesApiManagementPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**ProviderFeaturesApiManagement)(nil)).Elem()
}
func (i *providerFeaturesApiManagementPtrType) ToProviderFeaturesApiManagementPtrOutput() ProviderFeaturesApiManagementPtrOutput {
return i.ToProviderFeaturesApiManagementPtrOutputWithContext(context.Background())
}
func (i *providerFeaturesApiManagementPtrType) ToProviderFeaturesApiManagementPtrOutputWithContext(ctx context.Context) ProviderFeaturesApiManagementPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderFeaturesApiManagementPtrOutput)
}
type ProviderFeaturesApiManagementOutput struct{ *pulumi.OutputState }
func (ProviderFeaturesApiManagementOutput) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderFeaturesApiManagement)(nil)).Elem()
}
func (o ProviderFeaturesApiManagementOutput) ToProviderFeaturesApiManagementOutput() ProviderFeaturesApiManagementOutput {
return o
}
func (o ProviderFeaturesApiManagementOutput) ToProviderFeaturesApiManagementOutputWithContext(ctx context.Context) ProviderFeaturesApiManagementOutput {
return o
}
func (o ProviderFeaturesApiManagementOutput) ToProviderFeaturesApiManagementPtrOutput() ProviderFeaturesApiManagementPtrOutput {
return o.ToProviderFeaturesApiManagementPtrOutputWithContext(context.Background())
}
func (o ProviderFeaturesApiManagementOutput) ToProviderFeaturesApiManagementPtrOutputWithContext(ctx context.Context) ProviderFeaturesApiManagementPtrOutput {
return o.ApplyTWithContext(ctx, func(_ context.Context, v ProviderFeaturesApiManagement) *ProviderFeaturesApiManagement {
return &v
}).(ProviderFeaturesApiManagementPtrOutput)
}
func (o ProviderFeaturesApiManagementOutput) PurgeSoftDeleteOnDestroy() pulumi.BoolPtrOutput {
return o.ApplyT(func(v ProviderFeaturesApiManagement) *bool { return v.PurgeSoftDeleteOnDestroy }).(pulumi.BoolPtrOutput)
}
func (o ProviderFeaturesApiManagementOutput) RecoverSoftDeleted() pulumi.BoolPtrOutput {
return o.ApplyT(func(v ProviderFeaturesApiManagement) *bool { return v.RecoverSoftDeleted }).(pulumi.BoolPtrOutput)
}
type ProviderFeaturesApiManagementPtrOutput struct{ *pulumi.OutputState }
func (ProviderFeaturesApiManagementPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**ProviderFeaturesApiManagement)(nil)).Elem()
}
func (o ProviderFeaturesApiManagementPtrOutput) ToProviderFeaturesApiManagementPtrOutput() ProviderFeaturesApiManagementPtrOutput {
return o
}
func (o ProviderFeaturesApiManagementPtrOutput) ToProviderFeaturesApiManagementPtrOutputWithContext(ctx context.Context) ProviderFeaturesApiManagementPtrOutput {
return o
}
func (o ProviderFeaturesApiManagementPtrOutput) Elem() ProviderFeaturesApiManagementOutput {
return o.ApplyT(func(v *ProviderFeaturesApiManagement) ProviderFeaturesApiManagement {
if v != nil {
return *v
}
var ret ProviderFeaturesApiManagement
return ret
}).(ProviderFeaturesApiManagementOutput)
}
func (o ProviderFeaturesApiManagementPtrOutput) PurgeSoftDeleteOnDestroy() pulumi.BoolPtrOutput {
return o.ApplyT(func(v *ProviderFeaturesApiManagement) *bool {
if v == nil {
return nil
}
return v.PurgeSoftDeleteOnDestroy
}).(pulumi.BoolPtrOutput)
}
func (o ProviderFeaturesApiManagementPtrOutput) RecoverSoftDeleted() pulumi.BoolPtrOutput {
return o.ApplyT(func(v *ProviderFeaturesApiManagement) *bool {
if v == nil {
return nil
}
return v.RecoverSoftDeleted
}).(pulumi.BoolPtrOutput)
}
type ProviderFeaturesAppConfiguration struct {
PurgeSoftDeleteOnDestroy *bool `pulumi:"purgeSoftDeleteOnDestroy"`
RecoverSoftDeleted *bool `pulumi:"recoverSoftDeleted"`
}
// ProviderFeaturesAppConfigurationInput is an input type that accepts ProviderFeaturesAppConfigurationArgs and ProviderFeaturesAppConfigurationOutput values.
// You can construct a concrete instance of `ProviderFeaturesAppConfigurationInput` via:
//
// ProviderFeaturesAppConfigurationArgs{...}
type ProviderFeaturesAppConfigurationInput interface {
pulumi.Input
ToProviderFeaturesAppConfigurationOutput() ProviderFeaturesAppConfigurationOutput
ToProviderFeaturesAppConfigurationOutputWithContext(context.Context) ProviderFeaturesAppConfigurationOutput
}
type ProviderFeaturesAppConfigurationArgs struct {
PurgeSoftDeleteOnDestroy pulumi.BoolPtrInput `pulumi:"purgeSoftDeleteOnDestroy"`
RecoverSoftDeleted pulumi.BoolPtrInput `pulumi:"recoverSoftDeleted"`
}
func (ProviderFeaturesAppConfigurationArgs) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderFeaturesAppConfiguration)(nil)).Elem()
}
func (i ProviderFeaturesAppConfigurationArgs) ToProviderFeaturesAppConfigurationOutput() ProviderFeaturesAppConfigurationOutput {
return i.ToProviderFeaturesAppConfigurationOutputWithContext(context.Background())
}
func (i ProviderFeaturesAppConfigurationArgs) ToProviderFeaturesAppConfigurationOutputWithContext(ctx context.Context) ProviderFeaturesAppConfigurationOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderFeaturesAppConfigurationOutput)
}
func (i ProviderFeaturesAppConfigurationArgs) ToProviderFeaturesAppConfigurationPtrOutput() ProviderFeaturesAppConfigurationPtrOutput {
return i.ToProviderFeaturesAppConfigurationPtrOutputWithContext(context.Background())
}
func (i ProviderFeaturesAppConfigurationArgs) ToProviderFeaturesAppConfigurationPtrOutputWithContext(ctx context.Context) ProviderFeaturesAppConfigurationPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderFeaturesAppConfigurationOutput).ToProviderFeaturesAppConfigurationPtrOutputWithContext(ctx)
}
// ProviderFeaturesAppConfigurationPtrInput is an input type that accepts ProviderFeaturesAppConfigurationArgs, ProviderFeaturesAppConfigurationPtr and ProviderFeaturesAppConfigurationPtrOutput values.
// You can construct a concrete instance of `ProviderFeaturesAppConfigurationPtrInput` via:
//
// ProviderFeaturesAppConfigurationArgs{...}
//
// or:
//
// nil
type ProviderFeaturesAppConfigurationPtrInput interface {
pulumi.Input
ToProviderFeaturesAppConfigurationPtrOutput() ProviderFeaturesAppConfigurationPtrOutput
ToProviderFeaturesAppConfigurationPtrOutputWithContext(context.Context) ProviderFeaturesAppConfigurationPtrOutput
}
type providerFeaturesAppConfigurationPtrType ProviderFeaturesAppConfigurationArgs
func ProviderFeaturesAppConfigurationPtr(v *ProviderFeaturesAppConfigurationArgs) ProviderFeaturesAppConfigurationPtrInput {
return (*providerFeaturesAppConfigurationPtrType)(v)
}
func (*providerFeaturesAppConfigurationPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**ProviderFeaturesAppConfiguration)(nil)).Elem()
}
func (i *providerFeaturesAppConfigurationPtrType) ToProviderFeaturesAppConfigurationPtrOutput() ProviderFeaturesAppConfigurationPtrOutput {
return i.ToProviderFeaturesAppConfigurationPtrOutputWithContext(context.Background())
}
func (i *providerFeaturesAppConfigurationPtrType) ToProviderFeaturesAppConfigurationPtrOutputWithContext(ctx context.Context) ProviderFeaturesAppConfigurationPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderFeaturesAppConfigurationPtrOutput)
}
type ProviderFeaturesAppConfigurationOutput struct{ *pulumi.OutputState }
func (ProviderFeaturesAppConfigurationOutput) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderFeaturesAppConfiguration)(nil)).Elem()
}
func (o ProviderFeaturesAppConfigurationOutput) ToProviderFeaturesAppConfigurationOutput() ProviderFeaturesAppConfigurationOutput {
return o
}
func (o ProviderFeaturesAppConfigurationOutput) ToProviderFeaturesAppConfigurationOutputWithContext(ctx context.Context) ProviderFeaturesAppConfigurationOutput {
return o
}
func (o ProviderFeaturesAppConfigurationOutput) ToProviderFeaturesAppConfigurationPtrOutput() ProviderFeaturesAppConfigurationPtrOutput {
return o.ToProviderFeaturesAppConfigurationPtrOutputWithContext(context.Background())
}
func (o ProviderFeaturesAppConfigurationOutput) ToProviderFeaturesAppConfigurationPtrOutputWithContext(ctx context.Context) ProviderFeaturesAppConfigurationPtrOutput {
return o.ApplyTWithContext(ctx, func(_ context.Context, v ProviderFeaturesAppConfiguration) *ProviderFeaturesAppConfiguration {
return &v
}).(ProviderFeaturesAppConfigurationPtrOutput)
}
func (o ProviderFeaturesAppConfigurationOutput) PurgeSoftDeleteOnDestroy() pulumi.BoolPtrOutput {
return o.ApplyT(func(v ProviderFeaturesAppConfiguration) *bool { return v.PurgeSoftDeleteOnDestroy }).(pulumi.BoolPtrOutput)
}
func (o ProviderFeaturesAppConfigurationOutput) RecoverSoftDeleted() pulumi.BoolPtrOutput {
return o.ApplyT(func(v ProviderFeaturesAppConfiguration) *bool { return v.RecoverSoftDeleted }).(pulumi.BoolPtrOutput)
}
type ProviderFeaturesAppConfigurationPtrOutput struct{ *pulumi.OutputState }
func (ProviderFeaturesAppConfigurationPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**ProviderFeaturesAppConfiguration)(nil)).Elem()
}
func (o ProviderFeaturesAppConfigurationPtrOutput) ToProviderFeaturesAppConfigurationPtrOutput() ProviderFeaturesAppConfigurationPtrOutput {
return o
}
func (o ProviderFeaturesAppConfigurationPtrOutput) ToProviderFeaturesAppConfigurationPtrOutputWithContext(ctx context.Context) ProviderFeaturesAppConfigurationPtrOutput {
return o
}
func (o ProviderFeaturesAppConfigurationPtrOutput) Elem() ProviderFeaturesAppConfigurationOutput {
return o.ApplyT(func(v *ProviderFeaturesAppConfiguration) ProviderFeaturesAppConfiguration {
if v != nil {
return *v
}
var ret ProviderFeaturesAppConfiguration
return ret
}).(ProviderFeaturesAppConfigurationOutput)
}
func (o ProviderFeaturesAppConfigurationPtrOutput) PurgeSoftDeleteOnDestroy() pulumi.BoolPtrOutput {
return o.ApplyT(func(v *ProviderFeaturesAppConfiguration) *bool {
if v == nil {
return nil
}
return v.PurgeSoftDeleteOnDestroy
}).(pulumi.BoolPtrOutput)
}
func (o ProviderFeaturesAppConfigurationPtrOutput) RecoverSoftDeleted() pulumi.BoolPtrOutput {
return o.ApplyT(func(v *ProviderFeaturesAppConfiguration) *bool {
if v == nil {
return nil
}
return v.RecoverSoftDeleted
}).(pulumi.BoolPtrOutput)
}
type ProviderFeaturesApplicationInsights struct {
DisableGeneratedRule *bool `pulumi:"disableGeneratedRule"`
}
// ProviderFeaturesApplicationInsightsInput is an input type that accepts ProviderFeaturesApplicationInsightsArgs and ProviderFeaturesApplicationInsightsOutput values.
// You can construct a concrete instance of `ProviderFeaturesApplicationInsightsInput` via:
//
// ProviderFeaturesApplicationInsightsArgs{...}
type ProviderFeaturesApplicationInsightsInput interface {
pulumi.Input
ToProviderFeaturesApplicationInsightsOutput() ProviderFeaturesApplicationInsightsOutput
ToProviderFeaturesApplicationInsightsOutputWithContext(context.Context) ProviderFeaturesApplicationInsightsOutput
}
type ProviderFeaturesApplicationInsightsArgs struct {
DisableGeneratedRule pulumi.BoolPtrInput `pulumi:"disableGeneratedRule"`
}
func (ProviderFeaturesApplicationInsightsArgs) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderFeaturesApplicationInsights)(nil)).Elem()
}
func (i ProviderFeaturesApplicationInsightsArgs) ToProviderFeaturesApplicationInsightsOutput() ProviderFeaturesApplicationInsightsOutput {
return i.ToProviderFeaturesApplicationInsightsOutputWithContext(context.Background())
}
func (i ProviderFeaturesApplicationInsightsArgs) ToProviderFeaturesApplicationInsightsOutputWithContext(ctx context.Context) ProviderFeaturesApplicationInsightsOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderFeaturesApplicationInsightsOutput)
}
| go | Apache-2.0 | b66e1472775a89cca43f5050fef806854a7c3fa3 | 2026-01-07T09:44:27.619514Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.