博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用go来玩最简单的web服务器------顺便说说Content-Type字段
阅读量:4143 次
发布时间:2019-05-25

本文共 1983 字,大约阅读时间需要 6 分钟。

      web服务端代码s.go:

package mainimport (    "io"    "log"    "net/http")func handlerHello(w http.ResponseWriter, r *http.Request) {    io.WriteString(w, "hello girls")}func main() {    http.HandleFunc("/hello", handlerHello)     // 注册       err := http.ListenAndServe("localhost:8080", nil)    if err != nil {        log.Println(err)    }}

       go run s.go一下,跑起来, 然后在浏览器执行  (或者在命令行用curl发http请求也可以), 浏览器上的结果为:

hello girls

       好简单。可以在客户端或者服务端抓包看下, 很典型的http req和rsp.

 

       我们再来看一个有趣的问题, 修改s.go为:

package mainimport (    "io"    "log"    "net/http")func handlerHello(w http.ResponseWriter, r *http.Request) {    str := `        table border="1">                row 1, cell 1        row 1, cell 2                        row 2, cell 1        row 2, cell 2                        `    io.WriteString(w, str)}func main() {    http.HandleFunc("/hello", handlerHello)     // 注册       err := http.ListenAndServe("localhost:8080", nil)    if err != nil {        log.Println(err)    }}

        再次重启服务并发请求, 浏览器上显示的内容是:

table border="1">                row 1, cell 1        row 1, cell 2                        row 2, cell 1        row 2, cell 2                

          抓包看一下, 发现有:Content-Type: text/plain; charset=utf-8       

          因此, 浏览器需要根据纯文本显示。 注意到, 上述的table左边少了一个"<". 我们加上后, s.go的代码如下:

package mainimport (    "io"    "log"    "net/http")func handlerHello(w http.ResponseWriter, r *http.Request) {    str := `        
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2
` io.WriteString(w, str)}func main() { http.HandleFunc("/hello", handlerHello) // 注册 err := http.ListenAndServe("localhost:8080", nil) if err != nil { log.Println(err) }}

          再次重启服务,发请求,浏览器端的显示是:

row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2

        抓包看, 有Content-Type: text/html; charset=utf-8

    

       可见, 服务端会判断str的格式,来确定Content-Type的类型, 从而决定了浏览器端的展示方式。服务端的自动判断行为, 有点意思。 在我看来, 这样不太好,应该让程序员来指定Content-Type.

        不多说。

 

转载地址:http://sizti.baihongyu.com/

你可能感兴趣的文章
第四章 微信飞机大战
查看>>
九度:题目1008:最短路径问题
查看>>
九度Online Judge
查看>>
九度:题目1027:欧拉回路
查看>>
九度:题目1012:畅通工程
查看>>
九度:题目1017:还是畅通工程
查看>>
九度:题目1034:寻找大富翁
查看>>
第六章 背包问题——01背包
查看>>
51nod 分类
查看>>
1136 . 欧拉函数
查看>>
面试题:强制类型转换
查看>>
Decorator模式
查看>>
Template模式
查看>>
Observer模式
查看>>
高性能服务器设计
查看>>
性能扩展问题要趁早
查看>>
MySQL-数据库、数据表结构操作(SQL)
查看>>
OpenLDAP for Windows 安装手册(2.4.26版)
查看>>
图文介绍openLDAP在windows上的安装配置
查看>>
Pentaho BI开源报表系统
查看>>