學習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的可執行文件,就實現了一個簡易的靜態服務器。