使用Golang打造本身的http服務器 1.0版本

package main

import (
	"io/ioutil"
	"net/http"
	"os"
)

func main() {
	args := os.Args //獲取輸入的參數
	/*	遍歷參數
		for i,s := range args{
			print("--",i,"--",s,"\n")
		}
	*/
	//初始化端口以及檢驗用戶輸入
	port := "8080"
	argsLength := len(args)
	if argsLength != 2 && argsLength != 1 {
		print("please enter the port\n")
		return
	}
	if argsLength == 2 {
		port = args[1]
	}
	portLength := len(port)
	if portLength != 4 {
		print("error port\n")
		return
	}
	//加載本地文件
	loadPage("", "")
	var handle http.Handler
	//綁定host 開始服務
	print("the server is starting...the port:", port, "\n")
	err := http.ListenAndServe("0.0.0.0:"+port, handle)
	print(err, "\n")
	print("please review your port")
}

func loadPage(path string, urlPath string) {
	var files []os.FileInfo
	if path == "" {
		path = "./"
	}
	if urlPath == "" {
		urlPath = "/"
	}
	//獲取當前文件夾下全部文件包括文件夾
	files, _ = ioutil.ReadDir(path)
	for _, f := range files {
		if f.IsDir() { //若是當前是一個文件夾
			loadPage(appendPath(path, f.Name()), appendUrlPath(urlPath, f.Name()))
		} else {
			//綁定文件名
			if path == "./" {
				loadHandle(path+f.Name(), urlPath+f.Name())
			} else {
				loadHandle(path+"/"+f.Name(), urlPath+"/"+f.Name())
			}
		}
	}
}

//文件名和文件綁定
func loadHandle(path string, urlPath string) {
	bytes, _ := ioutil.ReadFile(path)
	//print("\n", urlPath, "\n")
	http.HandleFunc(urlPath, func(writer http.ResponseWriter, request *http.Request) {
		writer.Write(bytes)
	})
}

//拼接路徑
func appendPath(prefixPath string, suffixPath string) string {
	if prefixPath == "./" {
		return prefixPath + suffixPath
	}
	return prefixPath + "/" + suffixPath
}

//拼接url->端口號後部分
func appendUrlPath(prefixUrlPath string, suffixUrlPath string) string {
	if prefixUrlPath == "/" {
		return prefixUrlPath + suffixUrlPath
	}
	return prefixUrlPath + "/" + suffixUrlPath
}

 

啓動方式 go run server.go 9977 端口能夠不指定,默認 8080html

go語言編譯之後直接生成可執行文件(相對於系統,若是是在windows上編譯就只能在windows上運行,Linux同理),不依賴go環境,相似gcc 編譯,編譯之後可使用 cmd 窗口運行 server.exe 9977,或編寫bat文件添加  server.exe 9977git

採用相對路徑,會先遍歷和源碼文件相同路徑下的文件。github

如同文件夾下有index.html 能夠訪問 http://127.0.0.1:9977/index.htmlwindows

github:https://github.com/crazyjay97/GoLangLearnapp

相關文章
相關標籤/搜索