GO搭建简单HTPP文件下载服务器

package main

import (
	"flag"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"
)

const DEFAULTPORT = 7788

func handerGetFile(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()  //解析参数,默认是不会解析的
	log.Println("Recv:", r.RemoteAddr)
	pwd,_ := os.Getwd()
	des:= pwd + string(os.PathSeparator) + r.URL.Path[1:len(r.URL.Path)]
	desStat,err := os.Stat(des)
	if err != nil{
		log.Println("File Not Exit", des)
		http.NotFoundHandler().ServeHTTP(w, r)
	}else if(desStat.IsDir()){
		log.Println("File Is Dir", des)
		http.NotFoundHandler().ServeHTTP(w, r)
	}else{
		fileData, err := ioutil.ReadFile(des)
		if err != nil{
			log.Println("Read File Err:", err.Error())
		}else{
			log.Println("Send File:", des)
			w.Write(fileData)
		}
	}
}

func main() {
	port := flag.Int("p", DEFAULTPORT, "Set The Http Port")
	flag.Parse()
	pwd,_ := os.Getwd()
	log.Printf("Listen On Port:%d pwd:%s\n", *port, pwd)

	http.HandleFunc("/", handerGetFile)
	err := http.ListenAndServe(":" + strconv.Itoa(*port), nil)
	if nil != err{
		log.Fatalln("Get Dir Err", err.Error())
	}
}

 

你可能感兴趣的:(GO)