GO學習次日——web服務器搭建

    前天剛剛用GO寫了個Hello,今天弄了一下GO的web服務器。 git

    其實GO的web服務器搭建很是容易。這裏就不說GO的基本語句了,推薦一個網址學習https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/preface.md。直接上代碼吧。 github


package main

import (
	"fmt"
	"net/http"
	"strings"
	"log"
)

func sayHelloGO(w http.ResponseWriter, r *http.Request) {
	r.ParseForm() //解析參數,默認是不會解析的
	fmt.Println(r.Form) //這些信息是輸出到服務器端的打印信息
	fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    for k, v := range r.Form {
        fmt.Println("key:", k)
        fmt.Println("val:", strings.Join(v, ""))
    }
    fmt.Fprintf(w, "Hello GO!") 
}

func main() {
	http.HandleFunc("/",sayHelloGO)
	err := http.ListenAndServe(":9090",nil)
	if err != nil {
		log.Fatal("ListenAndServe: ",err)
	}
}
    運行上面的代碼,而後在瀏覽器輸入 http://localhost:9090/就會看到以下結果    


在控制檯會看到這樣的結果 golang

而後若是輸入這個urlhttp://localhost:9090/?a=111&b=222,控制檯的結果以下 web

    首先導入一些包,要創建WEB服務器最重要的就是net/http這個包。 瀏覽器

    在main方法中使用http.HandleFunc("/",sayHelloGO)就是指http://localhost:9090/就觸發sayHelloGO方法。 服務器

    在sayHelloGO方法裏面就解析http.Request,輸出url的地址,參數,而後在http.ResponseWriter中輸出Hello GO! app

    就這樣,一個簡單的GO服務器就搭建好了。 學習

                                                                                                                         未完,待續 ui

相關文章
相關標籤/搜索