您的位置:首页 > 编程语言 > Go语言

Go搭建第一个web服务器

2017-03-01 16:07 736 查看
这里,先上代码,进行演示,然后一一进行论述。

package main

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

)

func main() {
http.HandleFunc("/", sayhello)

err := http.ListenAndServe(":9090", nil)

if err != nil {
log.Fatal("ListenAndServe: ", err)
}

}

func sayhello(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("value:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello Golang")

}

运行:

E:\project\go\proj\src>go run webserver.go

现在打开IE浏览器,访问URL:  http://127.0.0.1:9090/



控制台输出:



OK,一个很普通的web服务器搭建成功了。

接下来对上面的代码进行逐一分析。

package main //声明该文件属于main包

/*

使用import语句导入多个外部包

fmt :  Package fmt implements formatted I/O(格式化输入输出)

log : Package log implements a simple logging package.(日志包)

net/http : Package
http provides HTTP client and server implementations.(用户实现http客户端和服务端)

strings : Package
strings implements simple functions to manipulate UTF-8 encoded strings.(字符串操作包)

*/

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

)  

//main函数,程序的入口处

func main {

}

//HandleFunc registers the handler function for the given pattern in the DefaultServeMux

http.HandleFunc("/", sayhello)  

/*

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Accepted connections are configured to enable
TCP keep-alives. Handler is typically nil, in which case the DefaultServeMux is used.

*/

http.ListenAndServe(":9090", nil)

//Fatal is equivalent to Print() followed by a call to os.Exit(1)

log.Fatal("ListenAndServe: ", err)

/*

1、自定义函数sayhello必须满足格式func(ResponseWriter,
*Request)才能作为参数传递给http.HandleFunc函数

2、Request : A Request represents an HTTP request received by
a server or to be sent by a client.

3、ParseForm : ParseForm
populates(填充) r.Form and r.PostForm.

 
                        For all requests, ParseForm parses the raw query from the URL and updates r.Form.

 
                        For POST, PUT, and PATCH requests, it also parses the request body as a form and puts the results into both r.PostForm and r.Form. Request body parameters take precedence over URL query string values in r.Form.

*/

func sayhello(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("value:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello Golang")

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  go