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

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

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

问题

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

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

  1. package main
  2. import (
  3. "net/http"
  4. )
  5. func main() {
  6. http.Handle("/", http.FileServer(http.Dir("./static")))
  7. http.ListenAndServe(":3000", nil)
  8. }

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

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

英文:

i have this simple server writed in golang :

  1. package main
  2. import (
  3. "net/http"
  4. )
  5. func main() {
  6. http.Handle("/", http.FileServer(http.Dir("./static")))
  7. http.ListenAndServe(":3000", nil)
  8. }

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协程中运行。
  1. package main
  2. import (
  3. "flag"
  4. "net/http"
  5. "os"
  6. "path/filepath"
  7. "sync"
  8. )
  9. func main() {
  10. dir := flag.String("dir", ".", "directory of files to serve")
  11. flag.Parse()
  12. f, err := os.Open(*dir)
  13. if err != nil {
  14. panic(err)
  15. }
  16. files, err := f.Readdir(0)
  17. if err != nil {
  18. panic(err)
  19. }
  20. filenames := make([]string, 0, len(files))
  21. for _, file := range files {
  22. if !file.IsDir() {
  23. filenames = append(filenames, file.Name())
  24. }
  25. }
  26. var (
  27. idxLock sync.Mutex
  28. idx int
  29. )
  30. http.HandleFunc("/rotate", func(w http.ResponseWriter, r *http.Request) {
  31. if len(filenames) == 0 {
  32. http.NotFound(w, r)
  33. return
  34. }
  35. idxLock.Lock()
  36. i := idx
  37. idx++
  38. if idx >= len(filenames) {
  39. idx = 0
  40. }
  41. idxLock.Unlock()
  42. http.ServeFile(w, r, filepath.Join(*dir, filenames[i]))
  43. })
  44. if err := http.ListenAndServe(":3000", nil); err != nil {
  45. panic(err)
  46. }
  47. }

希望对你有帮助!

英文:

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.

<!-- -->

  1. package main
  2. import (
  3. &quot;flag&quot;
  4. &quot;net/http&quot;
  5. &quot;os&quot;
  6. &quot;path/filepath&quot;
  7. &quot;sync&quot;
  8. )
  9. func main() {
  10. dir := flag.String(&quot;dir&quot;, &quot;.&quot;, &quot;directory of files to serve&quot;)
  11. flag.Parse()
  12. f, err := os.Open(*dir)
  13. if err != nil {
  14. panic(err)
  15. }
  16. files, err := f.Readdir(0)
  17. if err != nil {
  18. panic(err)
  19. }
  20. filenames := make([]string, 0, len(files))
  21. for _, file := range files {
  22. if !file.IsDir() {
  23. filenames = append(filenames, file.Name())
  24. }
  25. }
  26. var (
  27. idxLock sync.Mutex
  28. idx int
  29. )
  30. http.HandleFunc(&quot;/rotate&quot;, func(w http.ResponseWriter, r *http.Request) {
  31. if len(filenames) == 0 {
  32. http.NotFound(w, r)
  33. return
  34. }
  35. idxLock.Lock()
  36. i := idx
  37. idx++
  38. if idx &gt;= len(filenames) {
  39. idx = 0
  40. }
  41. idxLock.Unlock()
  42. http.ServeFile(w, r, filepath.Join(*dir, filenames[i]))
  43. })
  44. if err := http.ListenAndServe(&quot;:3000&quot;, nil); err != nil {
  45. panic(err)
  46. }
  47. }

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:

确定