天天看點

go 語言實作一個簡單的 web 伺服器

學習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)

                log.fatal("listenandserve:", err)

網上看到一個更bt的方法..

        http.handle("/", http.fileserver(http.dir("/tmp/static/")))

        http.listenandserve(":8080", nil)

将easyui前端架構解壓到 /tmp/static 目錄下

go 語言實作一個簡單的 web 伺服器

在gopath下執行 

go run httpserver.go

--path=/tmp/static

檢視網頁,一切正常。

go 語言實作一個簡單的 web 伺服器

這樣go語言以不到50行代碼,編譯之後不到7m的可執行檔案,就實作了一個簡易的靜态伺服器。