1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
   | package main
  import ( 	"crypto/md5" 	"encoding/json" 	"fmt" 	"io" 	"net/http" 	"os" 	"path/filepath" 	"strings" 	"time" )
  func sayHello(w http.ResponseWriter, r *http.Request) { 	w.Write([]byte("hello world")) }
  func main() {
  	fileHandler := http.FileServer(http.Dir("./video"))
  	http.Handle("/video/", http.StripPrefix("/video/", fileHandler))
  	http.HandleFunc("/api/upload", uploadHandler)
  	http.HandleFunc("/api/list", getFileListHandler)
  	http.HandleFunc("/sayHello", sayHello)
  	http.ListenAndServe(":8090", nil) }
 
 
 
  func uploadHandler(w http.ResponseWriter, r *http.Request) { 	r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024) 	err := r.ParseMultipartForm(10 * 1024 * 1024) 	if err != nil { 		http.Error(w, err.Error(), http.StatusInternalServerError) 		return 	}
  	file, fileHeader, err := r.FormFile("uploadFile") 	ret := strings.HasSuffix(fileHeader.Filename, ".mp4") 	if ret == false { 		http.Error(w, "not mp4", http.StatusInternalServerError) 		return 	}
  	md5Byte := md5.Sum([]byte(fileHeader.Filename + time.Now().String())) 	md5Str := fmt.Sprintf("%x", md5Byte) 	newFileName := md5Str + ".mp4"
  	dst, err := os.Create("./video/" + newFileName) 	defer dst.Close() 	if err != nil { 		http.Error(w, err.Error(), http.StatusInternalServerError) 		return 	} 	defer file.Close() 	if _, err := io.Copy(dst, file); err != nil { 		http.Error(w, err.Error(), http.StatusInternalServerError) 		return 	} 	return }
  func getFileListHandler(w http.ResponseWriter, r *http.Request) { 	files, _ := filepath.Glob("video/*") 	var ret []string 	for _, file := range files { 		ret = append(ret, "http://"+r.Host+filepath.Base(file)) 	} 	retJson, _ := json.Marshal(ret) 	w.Write(retJson) 	return }
 
 
  |