GO启动一个视频下载接口 前端可以边下边放

1.main.go 代码

go 复制代码
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)
type Response struct {
	Status  string
	Message string
	Data    string
}


func main() {
	// 设置路由
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/api/video/", videoHandler)

	// 启动服务器
	port := ":8080"
	fmt.Printf("🚀 服务器运行中,访问地址: http://localhost%s\n", port)
	fmt.Println("=========================================")

	err := http.ListenAndServe(port, nil)
	if err != nil {
		log.Fatalf("❌ 启动服务器失败: %v", err)
	}
}

// 主页处理器
func homeHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	response := Response{
		Status:  "success",
		Message: "欢迎使用用户API服务",
		Data:    "请访问 /api/users 获取用户数据",
	}
	sendJSON(w, http.StatusOK, response)
}





// 获取视频
func videoHandler(w http.ResponseWriter, r *http.Request) {
	const videoDir = "./videos/"

	// 提取视频文件名
	path := r.URL.Path[len("/api/video/"):]
	if path == "" {
		http.Error(w, "Missing video filename", http.StatusBadRequest)
		return
	}

	filePath := videoDir + path
	_, err := os.Stat(filePath)
	if os.IsNotExist(err) {
		http.Error(w, "Video not found", http.StatusNotFound)
		return
	}

	if err != nil {
		log.Printf("Error getting file info: %v", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	// 设置响应头
	w.Header().Set("Content-Type", "video/mp4")
	w.Header().Set("Access-Control-Allow-Origin", "*") // 允许所有来源跨域访问
	w.Header().Set("Cache-Control", "max-age=3600, public")
	w.Header().Set("Accept-Ranges", "bytes")

	http.ServeFile(w, r, filePath)
}

// 发送JSON响应
func sendJSON(w http.ResponseWriter, statusCode int, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)

	if err := json.NewEncoder(w).Encode(data); err != nil {
		log.Printf("❌ JSON编码失败: %v", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
	}
}

1.1在main.go同级建一个videos文件夹放一个 tem1.mp4

2.前端代码

这里简单使用html

html 复制代码
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Document</title>
</head>
<body>
<video controls>
    <source src="http://localhost:8080/api/video/tem1.mp4" type="video/mp4">
    您的浏览器不支持视频播放。
</video>

</body>
</html>

3.启动go服务

4.使用浏览器打开html

视频可以正常播放

可以跳转进度条

暂停等操作

相关推荐
何双新2 小时前
Odoo AI 智能查询系统
前端·人工智能·python
孤雪心殇8 小时前
如何安全,高效,优雅的提升linux的glibc版本
linux·后端·golang·glibc
秋名山大前端8 小时前
Chrome GPU 加速优化配置(前端 3D 可视化 / 数字孪生专用)
前端·chrome·3d
今天不要写bug8 小时前
antv x6实现封装拖拽流程图配置(适用于工单流程、审批流程应用场景)
前端·typescript·vue·流程图
luquinn8 小时前
实现统一门户登录跳转免登录
开发语言·前端·javascript
用户21411832636029 小时前
dify案例分享-5分钟搭建智能思维导图系统!Dify + MCP工具实战教程
前端
augenstern4169 小时前
HTML(面试)
前端
excel9 小时前
前端常见布局误区:1fr 为什么撑爆了我的容器?
前端
烛阴9 小时前
TypeScript 类型魔法:像遍历对象一样改造你的类型
前端·javascript·typescript
vayy9 小时前
uniapp中 ios端 scroll-view 组件内部子元素z-index失效问题
前端·ios·微信小程序·uni-app