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

相关推荐
Grassto3 小时前
一个 import 语句,引发的 Go 第三方包加载之旅
golang·go·go module
岁月的眸18 小时前
【科大讯飞声纹识别和语音内容识别的实时接口实现】
人工智能·go·语音识别
王中阳Go1 天前
三年前,我帮万人转Go;今天,聊聊Go/Java程序员如何抢占AI高地
人工智能·后端·go
王中阳Go1 天前
全面解析Go泛型:从1.18到最新版本的演进与实践
后端·面试·go
代码扳手1 天前
“老板,我的接口性能还能再快一倍!” — Go微服务gRPC升级实战
后端·go
码luffyliu1 天前
Go 语言并发编程:为何它能甩开 Java 等传统后端语言?
java·后端·golang·go
吴佳浩1 天前
Go 1.25.5 通关讲解
后端·面试·go
喵个咪1 天前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:分层设计的取舍之道(从 “简单粗暴” 到依赖倒置)
后端·go·领域驱动设计
王中阳Go2 天前
Golang框架封神榜!GitHub星标TOP8大比拼,选对框架少走3年弯路
后端·面试·go
王中阳Go2 天前
05 Go Eino AI应用开发实战 | Docker 部署指南
人工智能·后端·go