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.根据文件头判断文件类型进行不同处理没有实现

相关推荐
gopher_looklook2 小时前
Go泛型实战:打造优雅的切片工具库
后端·go
烛阴4 天前
Go 语言进阶:打造可复用的模块,导出你的专属包
后端·go
gopher_looklook5 天前
从零到一: 用Go语言搭建简易RPC框架并实践 (一)
后端·go
猫九森7 天前
go 循环处理无限极数据
数据结构·后端·go
川Princess7 天前
【后端开发】字节跳动青训营Cloudwego脚手架
go·字节跳动青训营·cwgo
Pandaconda9 天前
【Golang 面试题】每日 3 题(四十三)
开发语言·经验分享·笔记·后端·面试·golang·go
川Princess11 天前
【后端开发】字节跳动青训营之性能分析工具pprof
go·字节跳动青训营·bytedance
用户22372091177212 天前
Go微服务精讲:Go-Zero全流程实战即时通讯
go
嘿嘿12 天前
Grafana 快速搭建go-metrics 仪表盘备忘
后端·docker·go
烛阴12 天前
Go 语言进阶必学:&^ 操作符,高效清零的秘密武器!
后端·go