Go搭建第一个web服务器

这里,先上代码,进行演示,然后一一进行论述。

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")
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

历史五千年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值