简单的静态服务器,每次请求时返回轮换的静态文件。

huangapple go评论159阅读模式
英文:

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

问题

你好!以下是你要翻译的内容:

我有一个用Go语言编写的简单服务器:

package main

import (
        "net/http"
)

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

我想添加一个新的功能:
每次GET请求/rotate时,服务器从/static文件夹中返回一个旋转的文件内容。
例如,在/static文件夹中存在7个文件,对于每个请求,服务器返回:file1,file2,file3...

我该如何在Go中实现这个功能?

英文:

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

得分: 0

以下是一个简单的服务器,可以帮助你开始实现你的目标。关于实现的一些注意事项:

  1. 文件名只在程序启动时加载一次。如果文件在程序运行时消失,当它在轮换中出现时,服务器将返回404错误。
  2. 我们需要使用锁(在这种情况下是通过sync.Mutex)来确保每个请求在自己的Go协程中运行。
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)
	}
}

希望对你有帮助!

英文:

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 (
	&quot;flag&quot;
	&quot;net/http&quot;
	&quot;os&quot;
	&quot;path/filepath&quot;
	&quot;sync&quot;
)

func main() {
	dir := flag.String(&quot;dir&quot;, &quot;.&quot;, &quot;directory of files to serve&quot;)
	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(&quot;/rotate&quot;, func(w http.ResponseWriter, r *http.Request) {
		if len(filenames) == 0 {
			http.NotFound(w, r)
			return
		}

		idxLock.Lock()
		i := idx
		idx++
		if idx &gt;= len(filenames) {
			idx = 0
		}
		idxLock.Unlock()

		http.ServeFile(w, r, filepath.Join(*dir, filenames[i]))
	})

	if err := http.ListenAndServe(&quot;:3000&quot;, nil); err != nil {
		panic(err)
	}
}

huangapple
  • 本文由 发表于 2017年8月31日 01:50:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/45966825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定