Go語言實現簡單的一個靜態WEB伺服器_Golang

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.