[Solved] simple static server who return static files in rotation for every request


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)
    }
}

solved simple static server who return static files in rotation for every request