duanguanzai6181 2017-08-30 17:50
浏览 16
已采纳

简单的静态服务器,为每个请求轮流返回静态文件

i have this simple server writed in golang :

package main

import (
        "net/http"
)

func main() {
        http.Handle("/", http.FileServer(http.Dir("./static")))
        http.ListenAndServe(":3000", nil)
}

I want add new function : every request GET /rotate return one file content in rotation from /static folder. for example in /static folder exist 7 file, for every request server return : file1, file2, file3 ...

How i can do this in go ?

  • 写回答

1条回答 默认 最新

  • dqx76962 2017-08-31 00:41
    关注

    Below is a simple server that should get you started toward your goal. A couple of things to note about the implementation:

    1. The file names are loaded only once during program startup. If a file disappears while the program is running, the server will return a 404 when it comes up in the rotation.
    2. We need to use locking (in this case, via sync.Mutex) as each request will run in its own go routine.
    package main
    
    import (
        "flag"
        "net/http"
        "os"
        "path/filepath"
        "sync"
    )
    
    func main() {
        dir := flag.String("dir", ".", "directory of files to serve")
        flag.Parse()
    
        f, err := os.Open(*dir)
        if err != nil {
            panic(err)
        }
        files, err := f.Readdir(0)
        if err != nil {
            panic(err)
        }
    
        filenames := make([]string, 0, len(files))
        for _, file := range files {
            if !file.IsDir() {
                filenames = append(filenames, file.Name())
            }
        }
    
        var (
            idxLock sync.Mutex
            idx     int
        )
    
        http.HandleFunc("/rotate", func(w http.ResponseWriter, r *http.Request) {
            if len(filenames) == 0 {
                http.NotFound(w, r)
                return
            }
    
            idxLock.Lock()
            i := idx
            idx++
            if idx >= len(filenames) {
                idx = 0
            }
            idxLock.Unlock()
    
            http.ServeFile(w, r, filepath.Join(*dir, filenames[i]))
        })
    
        if err := http.ListenAndServe(":3000", nil); err != nil {
            panic(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛