使用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

相关文章
相关标签/搜索