golang net/http模块

golang net/http模块

搭建网站的欢迎页面

http.HandleFunc()用于给HTTP服务注册请求处理程序;它接收两个参数,一个是要匹配pattern(通常是uri),一个是用于处理的函数。

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

func (w http.ResponseWriter, r *http.Request)接收两个参数,http.ResponseWriter,可以把响应写入其中,http.Request包含请求的所有信息,比如请求uri、请求头等。

package main

import (
    "fmt"
    "net/http"
)

// 使用golang 的net/http模块创建简易的网站
func main() {
    // HandleFunc用于注册请求处理函数
    // 接收一个匿名函数作为参数,处理请求和响应
    http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
        fmt.Fprintf(writer, "Hello, welcome to access my website: %s. \n", request.URL.Path)
    })

    // 监听端口,把请求传递给请求处理程序
    http.ListenAndServe(":8080", nil)
}

上面的请求就搭建了一个网站的欢迎页面,在浏览器中访问http://localhost:8080/hello时,请求处理程序会把欢迎的语句打印到响应页面中。

图片.png

HTTP Server的基本能力

一个基本的http server需要以下几个功能:

  • 处理动态请求:用户浏览网站时发起的各种请求,如登录、下载图片

  • 静态资源服务:向浏览器提供静态的 JavaScript、 CSS 和图像服务,为用户创建动态体验

  • 接收连接:http server必须要监听在某一个端口上,接收所有发起请求的连接

处理动态请求

第一节中欢迎页面的示例其实就属于动态的请求,用户访问指定的uri,http server作出相应的相应。此外由于请求处理函数接收的`http.Requset`参数包含所有请求的所有信息,http server也可以处理请求中的相关参数。

例如我在第一节中的代码新注册一个整型数字加法的功能,通过`r.URL.Query().Get("param")`可以获取GET请求URL中的参数。
http.HandleFunc("/calc", func(w http.ResponseWriter, r *http.Request) {
        a := r.URL.Query().Get("a")
        b := r.URL.Query().Get("b")
        inta, err := strconv.Atoi(a)
        if err != nil {
            fmt.Fprintf(w, "param a is not a int number!\n")
            panic(err)
        }
        intb, err := strconv.Atoi(b)
        if err != nil {
            fmt.Fprintf(w, "param b is not a int number!\n")
            panic(err)
        }
        fmt.Fprintf(w, "plus two integer:\n")
        fmt.Fprintf(w, "a + b = %v \n", inta+intb)
    })
2022-08-13-13-53-01-image.png

静态资源服务

静态资源通常是html、css、js、图片等文件。它们通常存放在web服务的某一个目录,一般叫/public或/static。net/http模块内置的http.FileServer()方法可以指定FileSystem的路径作为请求目录的根路径并返回一个处理程序。http.Dir()把指定的路径封装成FileSytem对象并传入http.FileServer()

在main.go的同级目录下创建一个web文件夹,用于存放各类静态资源,在web目录下创建一个public文件夹存放html资源,目录结构如下:

-main.go
-web
-public
-index.html

注册静态资源服务的处理程序,并构造一个index.html页面:

    // 为js、css、html、图片等静态资源服务
    welcomepage := http.FileServer(http.Dir("path/web/public/"))
    http.Handle("/", welcomepage)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>htmlAsset</title>
</head>
<body>
    <h2>welcome to the html page.</h2>
    <p>this is a static asset.</p>
</body>
</html>

重启http server后在浏览器中访问http://localhost:8080/index.html,用户即可与静态资源交互。

2022-08-13-14-51-32-image.png

当然js等静态资源同样能访问,创建一个calculator.html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>myCalculator</title>
</head>
<style>
    .box {
        width: 400px;
        height: 100px;
        background: #00ffff;
        position: absolute;
        left: 50%;
        margin-left: -100px;
    }
</style>
<body>
<div class="box">
    <input type="text" id="inta" value=""/>
    +
    <input type="text" id="intb" value="" />
    =
    <input type="text" id="plus" value="">
    </br>
    <input type="button" name="calc-plus" value=" 计算 " onclick="calc()" >
</div>
</body>
<script type="text/javascript">
    function calc() {
        var num1 = parseInt(document.getElementById("inta").value);
        var num2 = parseInt(document.getElementById("intb").value);
        document.getElementById("plus").value = num1+num2;
    }
</script>
</html>
2022-08-13-15-24-09-image.png

接收连接

完成简易http server的最后一步就是监听端口接受所有来自互联网上的连接(请求)。当然也如前面的示例一样,通过http.ListenAndServe实现。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • http http/cgi http/cookiejar http/fcgi http/httptest http...
    DevilRoshan阅读 4,908评论 0 0
  • 输入与输出-fmt包 时间与日期-time包 命令行参数解析-flag包 日志-log包 IO操作-os包 IO操...
    思考的山羊阅读 11,612评论 0 5
  • Hello World 开始使用Go编写Web服务器的典型方法是使用标准库中的net/http模块。 如下代码是最...
    asdzxc阅读 5,675评论 0 0
  • Golang作为一门新的编程语言,它借鉴了现有语言的思想但拥有着不同寻常的特性,使得有效的Go程序在性质上不同于其...
    云时代的运维开发阅读 4,505评论 0 0
  • # 云计算实验 如果说亚马逊的AWS(Amazon Web Service)是一个IaaS平台,为用户提供计算服务...
    哟桑_6481阅读 3,848评论 0 0

友情链接更多精彩内容