resty 调用 zlm api 测试

This commit is contained in:
shikong 2025-01-24 22:01:16 +08:00
parent d4de6e7752
commit db36f28237
Signed by: Shikong
GPG Key ID: BD85FF18B373C341
11 changed files with 282 additions and 3 deletions

View File

@ -4,6 +4,7 @@ import (
"git.skcks.cn/Shikong/go-gb28181/pkg/config"
"git.skcks.cn/Shikong/go-gb28181/pkg/handler/message"
"git.skcks.cn/Shikong/go-gb28181/pkg/log"
"git.skcks.cn/Shikong/go-gb28181/pkg/services/zlmediakit"
"github.com/emiago/sipgo"
"github.com/emiago/sipgo/sip"
"github.com/rs/zerolog"
@ -41,6 +42,7 @@ func main() {
}
log.SetLogger(&logger)
zlmediakit.SetupZLMediaKitService(clientConfig.ZLMediaKit)
ctx := context.Background()
addr := fmt.Sprintf("%s:%d", clientConfig.ListenIp, clientConfig.ListenPort)

1
go.mod
View File

@ -16,6 +16,7 @@ require (
require (
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/go-resty/resty/v2 v2.16.5 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect

2
go.sum
View File

@ -13,6 +13,8 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM=
github.com/go-resty/resty/v2 v2.16.5/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA=
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=

View File

@ -1,5 +1,7 @@
package config
import "git.skcks.cn/Shikong/go-gb28181/pkg/services/zlmediakit"
type ClientConfig struct {
Debug bool `json:"debug" toml:"debug" yaml:"debug" comment:"调试模式"`
@ -11,6 +13,8 @@ type ClientConfig struct {
DeviceId string `json:"deviceId" toml:"deviceId" yaml:"deviceId" comment:"设备Id"`
ListenIp string `json:"listenIp" toml:"listenIp" yaml:"listenIp" comment:"监听Ip"`
ListenPort int `json:"listenPort" toml:"listenPort" yaml:"listenPort" comment:"监听端口号"`
ZLMediaKit *zlmediakit.Config `json:"zlmediakit" toml:"zlmediakit" yaml:"zlmediakit" comment:"ZLMediaKit配置"`
}
func DefaultClientConfig() *ClientConfig {
@ -24,6 +28,12 @@ func DefaultClientConfig() *ClientConfig {
ListenIp: "0.0.0.0",
DeviceId: "44050100002000000002",
ListenPort: 8081,
ListenPort: 5099,
ZLMediaKit: &zlmediakit.Config{
Id: "zlmediakit",
Url: "http://10.10.10.200:5081",
Secret: "zlmediakit",
},
}
}

View File

@ -2,10 +2,10 @@ package config
import (
"errors"
"fmt"
"git.skcks.cn/Shikong/go-gb28181/pkg/constants"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/viper"
"log"
"os"
"path/filepath"
)
@ -45,7 +45,7 @@ func ReadClientConfig() (*ClientConfig, error) {
var configFileNotFoundError viper.ConfigFileNotFoundError
if errors.As(err, &configFileNotFoundError) {
_ = GenerateConfig()
fmt.Println("未找到配置文件, 已生成示例配置文件于运行路径下")
log.Fatal("未找到配置文件, 已生成示例配置文件于运行路径下")
}
}

View File

@ -0,0 +1,24 @@
package zlmediakit
import (
"github.com/go-resty/resty/v2"
"time"
)
type ZLMediaKit struct {
client *resty.Client
}
var zLMediaKitService *ZLMediaKit
func SetupZLMediaKitService(config *Config) {
client := resty.New()
client.EnableTrace()
client.SetBaseURL(config.Url)
client.SetQueryParam("secret", config.Secret)
client.SetTimeout(10 * time.Second)
client.SetRetryCount(3)
zLMediaKitService = &ZLMediaKit{
client: client,
}
}

View File

@ -0,0 +1,68 @@
package zlmediakit
import (
"encoding/json"
"fmt"
"git.skcks.cn/Shikong/go-gb28181/pkg/services/zlmediakit/types"
"github.com/go-resty/resty/v2"
"testing"
)
func TestZLMediaKit_API(t *testing.T) {
SetupZLMediaKitService(&Config{
Id: "amrWMKmbKqoBjRQ9",
Url: "http://10.10.10.200:5081",
Secret: "4155cca6-2f9f-11ee-85e6-8de4ce2e7333",
})
versionResp, err := zLMediaKitService.client.R().Get("/index/api/version")
printRequest(versionResp, err)
version := &types.Data[types.VersionResp]{}
_ = json.Unmarshal(versionResp.Body(), &version)
fmt.Printf("Version: %+v\n\n", version)
serverConfigResp, err := zLMediaKitService.client.R().Get("/index/api/getServerConfig")
printRequest(serverConfigResp, err)
serverConfig := &types.Data[types.ServerConfigResp]{}
_ = json.Unmarshal(serverConfigResp.Body(), &serverConfig)
fmt.Printf("ServerConfig: %+v\n\n", serverConfig)
printRequest(zLMediaKitService.client.R().Get("/index/api/getMediaList"))
}
func printRequest(resp *resty.Response, err error) {
fmt.Println("Request URL:", resp.Request.URL)
printResponse(resp, err)
printResponseTrace(resp)
}
func printResponse(resp *resty.Response, err error) {
fmt.Println("Response Info:")
fmt.Println(" Error :", err)
fmt.Println(" Status Code:", resp.StatusCode())
fmt.Println(" Status :", resp.Status())
fmt.Println(" Proto :", resp.Proto())
fmt.Println(" Time :", resp.Time())
fmt.Println(" Received At:", resp.ReceivedAt())
fmt.Println(" Body :\n", resp)
fmt.Println()
}
func printResponseTrace(resp *resty.Response) {
fmt.Println("Request Trace Info:")
ti := resp.Request.TraceInfo()
fmt.Println(" DNSLookup :", ti.DNSLookup)
fmt.Println(" ConnTime :", ti.ConnTime)
fmt.Println(" TCPConnTime :", ti.TCPConnTime)
fmt.Println(" TLSHandshake :", ti.TLSHandshake)
fmt.Println(" ServerTime :", ti.ServerTime)
fmt.Println(" ResponseTime :", ti.ResponseTime)
fmt.Println(" TotalTime :", ti.TotalTime)
fmt.Println(" IsConnReused :", ti.IsConnReused)
fmt.Println(" IsConnWasIdle :", ti.IsConnWasIdle)
fmt.Println(" ConnIdleTime :", ti.ConnIdleTime)
fmt.Println(" RequestAttempt:", ti.RequestAttempt)
fmt.Println(" RemoteAddr :", ti.RemoteAddr.String())
fmt.Println()
}

View File

@ -0,0 +1,7 @@
package zlmediakit
type Config struct {
Id string `json:"id" yaml:"id" toml:"id" comment:"ZLMediaKit服务ID"`
Url string `json:"url" yaml:"url" toml:"url" comment:"ZLMediaKit服务地址"` //...
Secret string `json:"secret" yaml:"secret" toml:"secret" comment:"ZLMediaKit服务密钥"`
}

View File

@ -0,0 +1,6 @@
package types
type Data[T any] struct {
Code int `json:"code"`
Data T `json:"data"`
}

View File

@ -0,0 +1,152 @@
package types
type ServerConfigResp = []ServerConfig
type ServerConfig struct {
ApiApiDebug string `json:"api.apiDebug"`
ApiDefaultSnap string `json:"api.defaultSnap"`
ApiDownloadRoot string `json:"api.downloadRoot"`
ApiSecret string `json:"api.secret"`
ApiSnapRoot string `json:"api.snapRoot"`
ClusterOriginUrl string `json:"cluster.origin_url"`
ClusterRetryCount string `json:"cluster.retry_count"`
ClusterTimeoutSec string `json:"cluster.timeout_sec"`
FfmpegBin string `json:"ffmpeg.bin"`
FfmpegCmd string `json:"ffmpeg.cmd"`
FfmpegDownload string `json:"ffmpeg.download"`
FfmpegLog string `json:"ffmpeg.log"`
FfmpegRestartSec string `json:"ffmpeg.restart_sec"`
FfmpegSnap string `json:"ffmpeg.snap"`
GeneralCheckNvidiaDev string `json:"general.check_nvidia_dev"`
GeneralEnableVhost string `json:"general.enableVhost"`
GeneralEnableFfmpegLog string `json:"general.enable_ffmpeg_log"`
GeneralFlowThreshold string `json:"general.flowThreshold"`
GeneralMaxStreamWaitMS string `json:"general.maxStreamWaitMS"`
GeneralMediaServerId string `json:"general.mediaServerId"`
GeneralMergeWriteMS string `json:"general.mergeWriteMS"`
GeneralResetWhenRePlay string `json:"general.resetWhenRePlay"`
GeneralStreamNoneReaderDelayMS string `json:"general.streamNoneReaderDelayMS"`
GeneralUnreadyFrameCache string `json:"general.unready_frame_cache"`
GeneralWaitAddTrackMs string `json:"general.wait_add_track_ms"`
GeneralWaitTrackReadyMs string `json:"general.wait_track_ready_ms"`
HlsBroadcastRecordTs string `json:"hls.broadcastRecordTs"`
HlsDeleteDelaySec string `json:"hls.deleteDelaySec"`
HlsFastRegister string `json:"hls.fastRegister"`
HlsFileBufSize string `json:"hls.fileBufSize"`
HlsSegDelay string `json:"hls.segDelay"`
HlsSegDur string `json:"hls.segDur"`
HlsSegKeep string `json:"hls.segKeep"`
HlsSegNum string `json:"hls.segNum"`
HlsSegRetain string `json:"hls.segRetain"`
HookAliveInterval string `json:"hook.alive_interval"`
HookEnable string `json:"hook.enable"`
HookOnFlowReport string `json:"hook.on_flow_report"`
HookOnHttpAccess string `json:"hook.on_http_access"`
HookOnPlay string `json:"hook.on_play"`
HookOnPublish string `json:"hook.on_publish"`
HookOnRecordMp4 string `json:"hook.on_record_mp4"`
HookOnRecordTs string `json:"hook.on_record_ts"`
HookOnRtpServerTimeout string `json:"hook.on_rtp_server_timeout"`
HookOnRtspAuth string `json:"hook.on_rtsp_auth"`
HookOnRtspRealm string `json:"hook.on_rtsp_realm"`
HookOnSendRtpStopped string `json:"hook.on_send_rtp_stopped"`
HookOnServerExited string `json:"hook.on_server_exited"`
HookOnServerKeepalive string `json:"hook.on_server_keepalive"`
HookOnServerStarted string `json:"hook.on_server_started"`
HookOnShellLogin string `json:"hook.on_shell_login"`
HookOnStreamChanged string `json:"hook.on_stream_changed"`
HookOnStreamNoneReader string `json:"hook.on_stream_none_reader"`
HookOnStreamNotFound string `json:"hook.on_stream_not_found"`
HookRetry string `json:"hook.retry"`
HookRetryDelay string `json:"hook.retry_delay"`
HookStreamChangedSchemas string `json:"hook.stream_changed_schemas"`
HookTimeoutSec string `json:"hook.timeoutSec"`
HttpAllowCrossDomains string `json:"http.allow_cross_domains"`
HttpAllowIpRange string `json:"http.allow_ip_range"`
HttpCharSet string `json:"http.charSet"`
HttpDirMenu string `json:"http.dirMenu"`
HttpForbidCacheSuffix string `json:"http.forbidCacheSuffix"`
HttpForwardedIpHeader string `json:"http.forwarded_ip_header"`
HttpKeepAliveSecond string `json:"http.keepAliveSecond"`
HttpMaxReqSize string `json:"http.maxReqSize"`
HttpNotFound string `json:"http.notFound"`
HttpPort string `json:"http.port"`
HttpRootPath string `json:"http.rootPath"`
HttpSendBufSize string `json:"http.sendBufSize"`
HttpSslPort string `json:"http.sslport"`
HttpVirtualPath string `json:"http.virtualPath"`
MulticastAddrMax string `json:"multicast.addrMax"`
MulticastAddrMin string `json:"multicast.addrMin"`
MulticastUdpTTL string `json:"multicast.udpTTL"`
ProtocolAddMuteAudio string `json:"protocol.add_mute_audio"`
ProtocolAutoClose string `json:"protocol.auto_close"`
ProtocolContinuePushMs string `json:"protocol.continue_push_ms"`
ProtocolEnableAudio string `json:"protocol.enable_audio"`
ProtocolEnableFmp4 string `json:"protocol.enable_fmp4"`
ProtocolEnableHls string `json:"protocol.enable_hls"`
ProtocolEnableHlsFmp4 string `json:"protocol.enable_hls_fmp4"`
ProtocolEnableMp4 string `json:"protocol.enable_mp4"`
ProtocolEnableRtmp string `json:"protocol.enable_rtmp"`
ProtocolEnableRtsp string `json:"protocol.enable_rtsp"`
ProtocolEnableTs string `json:"protocol.enable_ts"`
ProtocolFmp4Demand string `json:"protocol.fmp4_demand"`
ProtocolHlsDemand string `json:"protocol.hls_demand"`
ProtocolHlsSavePath string `json:"protocol.hls_save_path"`
ProtocolModifyStamp string `json:"protocol.modify_stamp"`
ProtocolMp4AsPlayer string `json:"protocol.mp4_as_player"`
ProtocolMp4MaxSecond string `json:"protocol.mp4_max_second"`
ProtocolMp4SavePath string `json:"protocol.mp4_save_path"`
ProtocolPacedSenderMs string `json:"protocol.paced_sender_ms"`
ProtocolRtmpDemand string `json:"protocol.rtmp_demand"`
ProtocolRtspDemand string `json:"protocol.rtsp_demand"`
ProtocolTsDemand string `json:"protocol.ts_demand"`
RecordAppName string `json:"record.appName"`
RecordFastStart string `json:"record.fastStart"`
RecordFileBufSize string `json:"record.fileBufSize"`
RecordFileRepeat string `json:"record.fileRepeat"`
RecordSampleMS string `json:"record.sampleMS"`
RtcExternIP string `json:"rtc.externIP"`
RtcMaxBitrate string `json:"rtc.max_bitrate"`
RtcMinBitrate string `json:"rtc.min_bitrate"`
RtcPort string `json:"rtc.port"`
RtcPreferredCodecA string `json:"rtc.preferredCodecA"`
RtcPreferredCodecV string `json:"rtc.preferredCodecV"`
RtcRembBitRate string `json:"rtc.rembBitRate"`
RtcStartBitrate string `json:"rtc.start_bitrate"`
RtcTcpPort string `json:"rtc.tcpPort"`
RtcTimeoutSec string `json:"rtc.timeoutSec"`
RtmpDirectProxy string `json:"rtmp.directProxy"`
RtmpEnhanced string `json:"rtmp.enhanced"`
RtmpHandshakeSecond string `json:"rtmp.handshakeSecond"`
RtmpKeepAliveSecond string `json:"rtmp.keepAliveSecond"`
RtmpPort string `json:"rtmp.port"`
RtmpSslPort string `json:"rtmp.sslport"`
RtpAudioMtuSize string `json:"rtp.audioMtuSize"`
RtpH264StapA string `json:"rtp.h264_stap_a"`
RtpLowLatency string `json:"rtp.lowLatency"`
RtpRtpMaxSize string `json:"rtp.rtpMaxSize"`
RtpVideoMtuSize string `json:"rtp.videoMtuSize"`
RtpProxyDumpDir string `json:"rtp_proxy.dumpDir"`
RtpProxyGopCache string `json:"rtp_proxy.gop_cache"`
RtpProxyH264Pt string `json:"rtp_proxy.h264_pt"`
RtpProxyH265Pt string `json:"rtp_proxy.h265_pt"`
RtpProxyOpusPt string `json:"rtp_proxy.opus_pt"`
RtpProxyPort string `json:"rtp_proxy.port"`
RtpProxyPortRange string `json:"rtp_proxy.port_range"`
RtpProxyPsPt string `json:"rtp_proxy.ps_pt"`
RtpProxyTimeoutSec string `json:"rtp_proxy.timeoutSec"`
RtspAuthBasic string `json:"rtsp.authBasic"`
RtspDirectProxy string `json:"rtsp.directProxy"`
RtspHandshakeSecond string `json:"rtsp.handshakeSecond"`
RtspKeepAliveSecond string `json:"rtsp.keepAliveSecond"`
RtspLowLatency string `json:"rtsp.lowLatency"`
RtspPort string `json:"rtsp.port"`
RtspRtpTransportType string `json:"rtsp.rtpTransportType"`
RtspSslPort string `json:"rtsp.sslport"`
ShellMaxReqSize string `json:"shell.maxReqSize"`
ShellPort string `json:"shell.port"`
SrtLatencyMul string `json:"srt.latencyMul"`
SrtPktBufSize string `json:"srt.pktBufSize"`
SrtPort string `json:"srt.port"`
SrtTimeoutSec string `json:"srt.timeoutSec"`
}

View File

@ -0,0 +1,7 @@
package types
type VersionResp struct {
BranchName string `json:"branchName"`
BuildTime string `json:"buildTime"`
CommitHash string `json:"commitHash"`
}