上篇:GO——學習筆記(九)
下篇:GO——學習筆記(十一)
參考:
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
搭建簡單的Web服務器
web應用的helloworld
相對于java大部分情況需要將web程序打包成war包恕酸,然后通過tomact或者其他服務器來發(fā)布http服務不同。通過golang里面提供的完善的net/http包迅诬,可以很方便的就搭建起來一個可以運行的Web服務,無需第三方的web服務器,可以認為net/http包實現了web服務器的功能没陡。
package main
import (
"fmt"
"net/http"
)
func goodgoodstudy(response http.ResponseWriter, request http.Request) {
fmt.Println(request.URL.Path) //request:http請求 response.Write([]byte("day day up")) //response:http響應
}
func main() {
http.HandleFunc("/", goodgoodstudy) //設置訪問的監(jiān)聽路徑桑寨,以及處理方法
http.ListenAndServe(":9000", nil) //設置監(jiān)聽的端口
}
通過瀏覽器訪問
http://localhost:9000/
結果
訪問結果
自定義路由
查看http的源碼,發(fā)現 http.HandleFunc 是默認建了一個DefaultServeMux路由來分發(fā)http請求
// 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)
}
我們可以自己新建一個路由來分發(fā)請求咆蒿,不用DefaultServeMux,代碼如下
package main
import (
"fmt"
"net/http"
)
func goodgoodstudy(response http.ResponseWriter, request *http.Request) {
fmt.Println(request.URL.Path) //通過 request蚂子,執(zhí)行http請求的相關操作
response.Write([]byte("day day up")) //通過 response沃测,執(zhí)行http的響應相關操作
}
func nihao(response http.ResponseWriter, request *http.Request) {
fmt.Println("nihao~~~")
response.Write([]byte("ni hao"))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", goodgoodstudy) //設置訪問的監(jiān)聽路徑,以及處理方法
mux.HandleFunc("/nihao", nihao)
http.ListenAndServe(":9000", mux) //設置監(jiān)聽的端口
}
通過瀏覽器訪問
http://localhost:9000/nihao
結果
訪問結果