10 lines of code in Gox language to realize static file web server and support HTTP/HTTPS (SSL) protocol-GX37.2

It is also quite easy to implement a WEB server based on static pages and resource files in Gox language. Now we will implement a WEB server framework that supports static pages and resource files (such as pictures, audio, video, etc.), and also supports HTTPS. (SSL encrypted connection) function.

// 设置所需使用到的Go语言标准包中的http包与path/filepath的简称
http = net_http
filepath = path_filepath

// 设置http协议的服务端口为8080
portG = ":8080"

// 设置https/ssl协议的端口为8443
sslPortG = ":8443"

// 设置根路径
basePathG = `c:\web`

// muxG是用于存储Web服务器路由的全局变量
muxG = nil

// staticFS是存储静态页面处理器的全局变量
staticFS = nil

// serveStaticDirHandler函数用于处理静态页面请求
func serveStaticDirHandler(w, r) {
	// 如果staticFS没有初始化则初始化之
	// 这样页面文件的基本路径就是c:\web\pages
	if staticFS == nil {
		staticFS = http.FileServer(http.Dir(filepath.Join(basePathG, "pages")))
	}

	// 拼装一下本地路径到URL路径
	old := r.URL.Path
	name := filepath.Join(basePathG, "pages", path.Clean(old))

	// 获取本地文件的文件信息
	info, err := os.Lstat(name)

	if err == nil { // 如果文件存在
		if !info.IsDir() { // 如果不是目录,则直接在网页上显示该文件(或者提供下载)
			staticFS.ServeHTTP(w, r)
		} else { // 如果是目录
			// 如果该目录下存在index.html则显示它
			if tk.IfFileExists(filepath.Join(name, "index.html")) {
				staticFS.ServeHTTP(w, r)
			} else { // 否则网页返回404错误,表示网页未找到
				http.NotFound(w, r)
			}
		}
	} else { // 如果文件访问出错,则网页返回404错误,表示网页未找到
		http.NotFound(w, r)
	}

}

// 启动https/ssl服务
// 注意在c:\web目录下需要有与域名相匹配的的server.crt证书文件和server.key私钥文件
func startHttpsServer(portA) {
	pl("trying to start https server on %v...", portA)

	err := http.ListenAndServeTLS(portA, filepath.Join(basePathG, "server.crt"), filepath.Join(basePathG, "server.key"), muxG)
	if err != nil {
		pl("failed to start https server: %v", err)
	}

}

// 初始化Web路由器对象muxG
muxG = http.NewServeMux()

// 设置处理URL根路由的函数为静态页面处理函数
muxG.HandleFunc("/", serveStaticDirHandler)

// 在sslPortG指定的端口(本例中为8443)上启动https服务
go startHttpsServer(sslPortG)

pl("trying to start http server on %v...", portG)

// 在portG指定的端口(本例中为8080)上启动http服务
err := http.ListenAndServe(portG, muxG)

if err != nil {
	pl("failed to start http server: %v", err)
}


Then make sure to create the c:\web\pages folder and store index.html or other files in it, execute the code, and then open the browser to visit https://127.0.0.1:8080/index.html, you can get Similar to the following operation effect:

As you can see, a WEB server that supports static pages has been successfully built. If you successfully apply for the SSL certificate and place the certificate and private key file in the specified folder according to the instructions, you can access port 8443 according to the domain name specified by the certificate and use the https service.

The effective code in the entire program does not exceed a dozen lines, so can it be simplified? Let's come back to the extreme operation, take a look at the code that is close to the simplest version!

staticFS = net_http.FileServer(net_http.Dir(path_filepath.Join(`c:\web`, "pages")))

func serveStaticDirHandler(w, r) {
	name = path_filepath.Join(`c:\web`, "pages", path.Clean(r.URL.Path))

	info, err = os.Lstat(name)
	if err == nil && (!info.IsDir() || tk.IfFileExists(path_filepath.Join(name, "index.html"))) {
		staticFS.ServeHTTP(w, r)
	} else {
		net_http.NotFound(w, r)
	}
}

muxG = net_http.NewServeMux()

muxG.HandleFunc("/", serveStaticDirHandler)

go plerr(net_http.ListenAndServeTLS(":8443", path_filepath.Join(`c:\web`, "server.crt"), path_filepath.Join(`c:\web`, "server.key"), muxG))

checkErrf("failed to start http server: %v", net_http.ListenAndServe(":8080", muxG))


The function is almost the same as the previous code, and the effective code is reduced to about 10 lines.

note:

  • Gox language is an open source scripting language born out of Go language (Golang). It is interpreted and executed, but compared to Go language, it is closer to a high-level language and has fewer grammatical constraints. It is a language that is biased towards rapid application, and it can also be said to be an integration. tool;

  • There are three main advantages of Gox language:

    • First, the Gox language itself has only one executable file, which is green without configuration and can be used after downloading. It does not need to install the Go language environment and does not need to compile. It is very suitable for rapid prototype production and remote development on cloud servers;
    • Second, Gox can directly use most of the objects and method functions in the Go language standard library, and there are also many commonly used and excellent third-party libraries built-in to give full play to the resource advantages accumulated by the Go language for many years;
    • Third, unlike many other mainstream languages, Gox language focuses on solving the problem of GUI graphical interface programming. It has built-in three sets of graphical interface programming libraries based on Giu (imgui), LCL, and Sciter, which can directly perform fast and efficient graphical interface development. (LCL and Sciter only need to download a dynamic link library file separately, and attach it when executing and distributing), especially suitable for writing a demonstration prototype system.

As a scripting language, Gox language performance is certainly not as fast as a compiled language like Go language, but due to the close connection between Gox language and Go language, scripts written in Gox language can be easily rewritten into Go language code, which can be used after compilation and execution. Go has the speed advantage. Therefore, Gox language is also more suitable for initial Go language debugging, and a more direct way is to use Gotx (also available for download on Gox official website), which is an interpreter that uses the same syntax as Go language, which can be understood as integration The Go language, which is interpreted and executed by the Go language standard library and many third-party libraries, also does not need to build a Go language environment. The difference between Gotx and Gox is that Gotx still follows the grammar of the Go language, the code is relatively more complicated, and there are more restrictions, but there is basically no cost when rewriting it back to the Go language for compilation and execution.

Gox's official website is here . You can also search for "gox language" directly in the browser search engine. The Github page is here . You can see many Gox language learning guides and practical application examples here.

Guess you like

Origin blog.csdn.net/weixin_41462458/article/details/107630164