go语言实现的简单web服务器

时间:2020-12-23 17:59:53

go语言让web服务器实现和部署变得异常简洁.终于可以抛开乱七八糟的项目结构和体积庞大的IDE,一窥其基本原理.
首先是一个简单的服务器实现代码,如果是GET请求,则回送一条This is a GET request消息,如果是POST请求,则解析POST请求中的info字段,将其内容回送.程序可以直接在命令行下用go run server.go启动.

//server.go
package main
import (
"fmt"
"net/http"
)
func login(w http.ResponseWriter,r *http.Request){
r.ParseForm()
fmt.Println(r.Method)
if r.Method=="GET"{
fmt.Fprintf(w,"This is a GET request")
}else{
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Println("Recived info:",r.Form)
fmt.Fprintf(w,r.Form.Get("info"))
}
}

func main(){
http.HandleFunc("/login",login)
if err:=http.ListenAndServe(":9000",nil);err!=nil{
fmt.Println("ListenAndServe err",err)
}
}

然后是浏览器端网页:

<!DOCTYPE html>  
<html>
<head>
<meta charset="UTF-8">
<title>go server测试</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
<script type="text/javascript">
function upload(){
var url = "http://localhost:9000/login";
var src ={};
src["info"]=$("input").val();
$.ajax({
url: url,
type: 'post',
data:src,
dataTypt: 'json',
success: function(data){
$("a").text(data);
},
error: function(xhr, msg){
alert(msg);
}
});
}
</script>
</head>
<body>
输入内容:<input name="info"></input>
<input type="submit" value="提交" onclick="upload()">
<div>回显内容:<a></a></div>
</body>
</html>

同样相当简单,直接在浏览器中打开,然后在input框中输入字符串,点击提交就向服务器发送POST请求.服务器将字符串回送回来,如图所示:
go语言实现的简单web服务器
如果直接在浏览器中访问http://localhost:9000/login,则相当于发送了GET请求,于是浏览器会收到消息:
go语言实现的简单web服务器

无论是客户端还是服务器端的代码结构都很简洁,无非就是服务器端注册路由和对应处理函数,然后将产生的消息写入ResponseWriter;客户端选择服务器端路由,将自身数据通过ajax发送过去,成功了再回调处理函数而已.当然一个优秀的服务器设计需要考虑安全,性能等诸多因素,这里就不详述了.