Go语言实现简单的一个静态WEB服务器
作者:junjie 时间:2024-04-28 09:12:56
学习Go语言的一些感受,不一定准确。
假如发生战争,JAVA一般都是充当航母战斗群的角色。
一旦出动,就是护卫舰、巡洋舰、航母舰载机、预警机、电子战飞机、潜艇等等
浩浩荡荡,杀将过去。
(JVM,数十个JAR包,Tomcat中间件,SSH框架,各种配置文件...天生就是重量级的,专为大规模作战)
而GO语言更像F35战斗轰炸机
单枪匹马,悄无声息,投下 * 然后走人。
专属轰炸机,空战也会一点点.
实在搞不定,就叫它大哥F22。
(GO是编译型语言,不需要依赖,不需要虚拟机,可以调用C代码并且它足够简单,却非常全面)
计划Go语言学习的知识点
1.搭建Http服务
2.连接数据库
3.本地IO
4.多线程
5.网络
6.调用本地命令
7.调用C语言代码
首先,搭建一个静态的服务器
我写程序喜欢使用HTML通过AJAX发送JSON请求到后端处理。
HttpServer.go
package main
import (
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
var realPath *string
func staticResource(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
request_type := path[strings.LastIndex(path, "."):]
switch request_type {
case ".css":
w.Header().Set("content-type", "text/css")
case ".js":
w.Header().Set("content-type", "text/javascript")
default:
}
fin, err := os.Open(*realPath + path)
defer fin.Close()
if err != nil {
log.Fatal("static resource:", err)
}
fd, _ := ioutil.ReadAll(fin)
w.Write(fd)
}
func main() {
realPath = flag.String("path", "", "static resource path")
flag.Parse()
http.HandleFunc("/", staticResource)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
网上看到一个更BT的方法:
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("/tmp/static/")))
http.ListenAndServe(":8080", nil)
}
将EasyUI前端框架解压到 /tmp/static 目录下:
在GOPATH下执行
go run HttpServer.go --path=/tmp/static
查看网页,一切正常。
这样Go语言以不到50行代码,编译之后不到7M的可执行文件,就实现了一个简易的静态服务器。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python中循环后使用list.append()数据被覆盖问题的解决
mdf文件和ldf文件导入到sql server 2005实现语句
python groupby 函数 as_index详解
用Python实现最速下降法求极值的方法
![](https://img.aspxhome.com/file/2023/7/112977_0s.jpg)
11个Python3字典内置方法大全与示例汇总
![](https://img.aspxhome.com/file/2023/2/99472_0s.jpg)
数字人整合动网论坛的方法
Python实现清理微信僵尸粉功能示例【基于itchat模块】
![](https://img.aspxhome.com/file/2023/1/90911_0s.png)
在Typescript中如何使用for...in详解
如何判断js脚本加载完成
阿里系的中国雅虎新首页浅谈
![](https://img.aspxhome.com/file/UploadPic/20087/16/2008716122345245s.png)
MySQL定时任务EVENT事件的使用方法
![](https://img.aspxhome.com/file/2023/2/65282_0s.png)
记一次Django响应超慢的解决过程
Python使用bar绘制堆积/带误差棒柱形图的实现
![](https://img.aspxhome.com/file/2023/0/97330_0s.png)
Go语言中错误处理实例分析
浅谈MySQL索引优化分析
![](https://img.aspxhome.com/file/2023/3/115543_0s.png)
python 实现单通道转3通道
python实现进程间通信简单实例
PDO::beginTransaction讲解
Mysql数据库错误代码中文详细说明
bootstrap-table+treegrid实现树形表格
![](https://img.aspxhome.com/file/2023/2/132832_0s.jpg)