Skip to content

Instantly share code, notes, and snippets.

@Huong-nt
Created September 30, 2016 10:19
Show Gist options
  • Save Huong-nt/4d3513bf5e17bc1ba3f9db4d6c114580 to your computer and use it in GitHub Desktop.
Save Huong-nt/4d3513bf5e17bc1ba3f9db4d6c114580 to your computer and use it in GitHub Desktop.
Proxy Video Server
package main
import (
"fmt"
"io"
"net/http"
"os"
"path"
)
const Folder = "./example"
const ServerVideoAddr = "http://www.sample-videos.com/video/mp4/720"
func main() {
var s = http.NewServeMux()
var addr = ":3000"
// var fs = http.FileServer(http.Dir(Folder))
// s.Handle("/static/", http.StripPrefix("/static", fs))
// s.Handle("/", http.FileServer(http.Dir(Folder)))
s.HandleFunc("/", handleReadVideo)
fmt.Println("Listen on %v", addr)
if err := http.ListenAndServe(addr, s); err != nil {
fmt.Println("Listen on %v error %v", addr, err.Error())
}
}
func handleReadVideo(w http.ResponseWriter, r *http.Request) {
// 1. Read file from file system
var filename = r.URL.Path
if _, err := os.Stat(path.Join(Folder, filename)); !os.IsNotExist(err) {
fmt.Println("File ko ton tai")
err = downloadFile(path.Join(Folder, filename), ServerVideoAddr+r.URL.Path)
if err != nil {
fmt.Printf("%v", err)
http.Error(w, "Can not dowload file in server", http.StatusInternalServerError)
return
}
}
file, err := os.Open(path.Join(Folder, filename))
if err != nil {
fmt.Printf("%v", err)
http.Error(w, "Can not open file", http.StatusInternalServerError)
return
}
_, err = io.Copy(w, file)
if err != nil {
fmt.Printf("%v", err)
http.Error(w, "File not found", http.StatusInternalServerError)
return
}
}
func downloadFile(filepath string, url string) error {
fmt.Println("File path: ", filepath)
fmt.Println("Url: ", url)
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%v", resp.Status)
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment