Go图片列表

需求

在一个页面浏览目录下所有图片

代码

Go 复制代码
package main

import (
	"net/http"
	"fmt"
	"io/ioutil"
	"sort"
	"strings"
	"strconv"
)

func handleRequest(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.Proto + " " + r.Host + " " +r.RequestURI)
	dir, err := ioutil.ReadDir("." + r.RequestURI)
	
	//排序
	sort.Slice(dir, func(i, j int) bool {
		di := dir[i]
        dj := dir[j]
        if di.IsDir() && !dj.IsDir() { // 目录在前
            return true
        } else if !di.IsDir() && dj.IsDir() { // 目录在后
            return false
        }
        //return dir[i].Name() < dir[j].Name() //和WIN7不一样
		return dir[i].ModTime().Before(dir[j].ModTime())
    })
	
	if err != nil {
		http.ServeFile(w, r, "." + r.RequestURI);		
	} else {
		path := "/"
		if (r.RequestURI != "/") {
			n := strings.LastIndex(r.RequestURI, "/");
			if (n != 0) {
				path = string(r.RequestURI[:n])
			}
		}
		ddir := ""
		if (r.RequestURI != "/") {
			ddir = " <a href=''>删除此目录</a>"
		}
		str := "<html>\n<head>\n<title>文件列表</title>\n</head>\n<style>\na, img { -webkit-user-drag:none; }\na { text-decoration:none; padding:10px; margin:10px; background:lightgray; display:inline-block; }\na:hover { background:gray; }\nimg { max-width: 100%; }\n</style>\n<body>\n<p><a href='" + path + "'>[" + path + "]</a>" + ddir + "</p>"
        path = "/"
		if (r.RequestURI != "/") {
			path = r.RequestURI + "/"
		}
		var count_dir, count_file int
		for _, file := range dir {
			if (file.IsDir()) {				
				str += "<a href='" + path + file.Name() + "'>" + file.Name() + "</a>\n"
				count_dir++
			} else {			
				str += "<img src='" + path + file.Name() +"'>\n"				
				count_file++
			}
		}	
		str += "<p>目录" + strconv.Itoa(count_dir) + "个,文件" + strconv.Itoa(count_file) + "个</p>\n</body>\n</html>"
		w.Write([]byte(str))
	}
}

func main() {	
	fmt.Println("http://localhost:8000");
	http.HandleFunc("/", handleRequest);
	http.ListenAndServe(":8000", nil);
}

问题

1.不支持非英文目录

2.删除目录没有实现

3.根据文件头判断文件类型进行不同处理没有实现

相关推荐
影灵衣丶11 小时前
Go 1.25 实战解读:绿茶 GC 与容器核心数感知(工程影响与落地)
后端·go
一直_在路上11 小时前
突发高流量应对之道:Go语言限流、熔断、降级三板斧
面试·go
程序员爱钓鱼12 小时前
Go语言100个实战案例-项目实战篇:股票行情数据爬虫
后端·go·trae
程序员爱钓鱼2 天前
Go语言实战案例 — 项目实战篇:简易博客系统(支持评论)
前端·后端·go
郭京京2 天前
go框架gin(中)
后端·go
郭京京2 天前
go框架gin(下)
后端·go
一直_在路上2 天前
Go 语言微服务演进路径:从小型项目到企业级架构
架构·go
程序员爱钓鱼3 天前
Go语言实战案例 — 项目实战篇:任务待办清单 Web 应用
后端·google·go
lypzcgf3 天前
Coze源码分析-资源库-创建知识库-后端源码-应用/领域/数据访问
后端·go·coze·coze源码分析·智能体平台·ai应用平台·agent平台
lypzcgf3 天前
Coze源码分析-资源库-创建知识库-基础设施/存储/安全
安全·go·coze·coze源码分析·智能体平台·ai应用平台·agent开发平台