Created
September 1, 2014 01:30
-
-
Save sescobb27/b57932275c33ef4f2bdf to your computer and use it in GitHub Desktop.
Serve Files On Demand
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"net/http" | |
) | |
type Request struct { | |
Filename string | |
ResultChan chan string | |
} | |
// process requests on background | |
func WorkerPool(n int) chan *Request { | |
requests := make(chan *Request, n) | |
for i := 0; i < n; i++ { | |
go Worker(requests) | |
} | |
return requests | |
} | |
func Worker(requests chan *Request) { | |
for request := range requests { | |
// path := methodForFindingFiles() | |
path := request.Filename | |
request.ResultChan <- path | |
} | |
} | |
type Server struct { | |
Requests chan *Request | |
} | |
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) { | |
filename := req.URL.Query().Get("filename") | |
request := &Request{Filename: filename, ResultChan: make(chan string)} | |
s.Requests <- request | |
path := <-request.ResultChan | |
http.ServeFile(w, req, path) | |
} | |
func main() { | |
requests := WorkerPool(5) | |
server := &Server{Requests: requests} | |
log.Fatal(http.ListenAndServe(":5000", server)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment