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

相关文章
相关标签/搜索