GO——學(xué)習(xí)筆記(十):搭建簡(jiǎn)單的Web服務(wù)器

上篇:GO——學(xué)習(xí)筆記(九)

下篇:GO——學(xué)習(xí)筆記(十一)

參考:

https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/03.2.md

示例代碼——go_9

https://github.com/jiutianbian/golang-learning/blob/master/go_9/main.go

搭建簡(jiǎn)單的Web服務(wù)器

web應(yīng)用的helloworld

相對(duì)于java大部分情況需要將web程序打包成war包,然后通過tomact或者其他服務(wù)器來(lái)發(fā)布http服務(wù)不同。通過golang里面提供的完善的net/http包,可以很方便的就搭建起來(lái)一個(gè)可以運(yùn)行的Web服務(wù),無(wú)需第三方的web服務(wù)器,可以認(rèn)為net/http包實(shí)現(xiàn)了web服務(wù)器的功能。

package main

import (
    "fmt"
    "net/http"
)

func goodgoodstudy(response http.ResponseWriter, request http.Request) {
    fmt.Println(request.URL.Path)        //request:http請(qǐng)求       response.Write([]byte("day day up")) //response:http響應(yīng)
}

func main() {

    http.HandleFunc("/", goodgoodstudy) //設(shè)置訪問的監(jiān)聽路徑,以及處理方法

    http.ListenAndServe(":9000", nil) //設(shè)置監(jiān)聽的端口
}

通過瀏覽器訪問

http://localhost:9000/

結(jié)果

訪問結(jié)果

自定義路由

查看http的源碼,發(fā)現(xiàn) http.HandleFunc 是默認(rèn)建了一個(gè)DefaultServeMux路由來(lái)分發(fā)http請(qǐng)求

// DefaultServeMux is the default ServeMux used by Serve.
var DefaultServeMux = NewServeMux()

// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    DefaultServeMux.HandleFunc(pattern, handler)
}

我們可以自己新建一個(gè)路由來(lái)分發(fā)請(qǐng)求,不用DefaultServeMux,代碼如下

package main

import (
    "fmt"
    "net/http"
)

func goodgoodstudy(response http.ResponseWriter, request *http.Request) {
    fmt.Println(request.URL.Path)        //通過 request,執(zhí)行http請(qǐng)求的相關(guān)操作
    response.Write([]byte("day day up")) //通過 response,執(zhí)行http的響應(yīng)相關(guān)操作
}

func nihao(response http.ResponseWriter, request *http.Request) {
    fmt.Println("nihao~~~")
    response.Write([]byte("ni hao"))
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", goodgoodstudy) //設(shè)置訪問的監(jiān)聽路徑,以及處理方法

    mux.HandleFunc("/nihao", nihao)

    http.ListenAndServe(":9000", mux) //設(shè)置監(jiān)聽的端口
}

通過瀏覽器訪問

http://localhost:9000/nihao

結(jié)果

訪問結(jié)果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容