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 ?
Below is a simple server that should get you started toward your goal. A couple of things to note about the implementation:
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)
}
}