go語言實現的簡單web伺服器
阿新 • • 發佈:2018-12-22
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請求.伺服器將字串回送回來,如圖所示:
如果直接在瀏覽器中訪問http://localhost:9000/login,則相當於傳送了GET請求,於是瀏覽器會收到訊息:
無論是客戶端還是伺服器端的程式碼結構都很簡潔,無非就是伺服器端註冊路由和對應處理函式,然後將產生的訊息寫入ResponseWriter;客戶端選擇伺服器端路由,將自身資料通過ajax傳送過去,成功了再回調處理函式而已.當然一個優秀的伺服器設計需要考慮安全,效能等諸多因素,這裡就不詳述了.