gopl-zh.github.com/ch1/ch1-07.html

363 lines
36 KiB
HTML
Raw Normal View History

<!DOCTYPE HTML>
<html lang="zh" class="sidebar-visible no-js light">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Web服务 - Go语言圣经</title>
<!-- Custom HTML head -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="&lt;The Go Programming Language&gt;中文版">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff" />
<link rel="icon" href="../favicon.svg">
<link rel="shortcut icon" href="../favicon.png">
<link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/general.css">
<link rel="stylesheet" href="../css/chrome.css">
<link rel="stylesheet" href="../css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="../fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="../highlight.css">
<link rel="stylesheet" href="../tomorrow-night.css">
<link rel="stylesheet" href="../ayu-highlight.css">
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="../style.css">
</head>
<body>
<!-- Provide site root to javascript -->
<script type="text/javascript">
var path_to_root = "../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script type="text/javascript">
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded affix "><a href="../index.html">Go语言圣经</a></li><li class="chapter-item expanded affix "><a href="../preface-zh.html">译者序</a></li><li class="chapter-item expanded affix "><a href="../preface.html">前言</a></li><li class="chapter-item expanded "><a href="../ch1/ch1.html"><strong aria-hidden="true">1.</strong> 入门</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../ch1/ch1-01.html"><strong aria-hidden="true">1.1.</strong> Hello, World</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-02.html"><strong aria-hidden="true">1.2.</strong> 命令行参数</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-03.html"><strong aria-hidden="true">1.3.</strong> 查找重复的行</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-04.html"><strong aria-hidden="true">1.4.</strong> GIF动画</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-05.html"><strong aria-hidden="true">1.5.</strong> 获取URL</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-06.html"><strong aria-hidden="true">1.6.</strong> 并发获取多个URL</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-07.html" class="active"><strong aria-hidden="true">1.7.</strong> Web服务</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-08.html"><strong aria-hidden="true">1.8.</strong> 本章要点</a></li></ol></li><li class="chapter-item expanded "><a href="../ch2/ch2.html"><strong aria-hidden="true">2.</strong> 程序结构</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../ch2/ch2-01.html"><strong aria-hidden="true">2.1.</strong> 命名</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-02.html"><strong aria-hidden="true">2.2.</strong> 声明</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-03.html"><strong aria-hidden="true">2.3.</strong> 变量</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-04.html"><strong aria-hidden="true">2.4.</strong> 赋值</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-05.html"><strong aria-hidden="true">2.5.</strong> 类型</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-06.html"><strong aria-hidden="true">2.6.</strong> 包和文件</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-07.html"><strong aria-hidden="true">2.7.</strong> 作用域</a></li></ol></li><li class="chapter-item expanded "><a href="../ch3/ch3.html"><strong aria-hidden="true">3.</strong> 基础数据类型</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../ch3/ch3-01.html"><strong aria-hidden="true">3.1.</strong> 整型</a></li><li class="chapter-item expanded "><a href="../ch3/ch3-02.html"><strong aria-hidden="true">3.2.</strong> 浮点数</a></li><li class="chapter-item expanded "><a href="../ch3/ch3-03.html"><strong aria-hidden="true">3.3.</strong> 复数</a></li><li class="chapter-item expanded "><a href="../ch3/ch3-04.html"><strong aria-hidden="true">3.4.</strong> 布尔型</a></li><li class="chapter-item expanded "><a href="../ch3/ch3-05.html"><strong aria-hidden="true">3.5.</strong> 字符串</a></li><li class="chapter-item expanded "><a href="../ch3/ch3-06.html"><strong aria-hidden="true">3.6.</strong> 常量</a></li></ol></li><li class="chapter-item expanded "><a href="../ch4/ch4.html"><strong aria-hidden="true">4.</strong> 复合数据类型</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../ch4/ch4-01.html"><strong aria-hidden="true">4.1.</strong> 数组</a></li><li class="chapter-item expanded "><a href="../ch4/ch4-02.html"><strong aria-hidden="true">4.2.</strong> Slice</a></li><li class="chapter-item expanded "><a href="../ch4/ch4-03.html"><strong aria-hidden="true">4.3.</strong> Map</a></li><li class="chapter-item expanded "><a href="../ch4/ch4-04.html"><strong aria-hidden="true">4.4.</strong> 结构体</a></li><li class="chapter-item expanded "><a href="../ch4/ch4-05.html"><strong aria-hidden="true">4.5.<
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky bordered">
<div class="left-buttons">
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</button>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Go语言圣经</h1>
<div class="right-buttons">
<a href="../print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/gopl-zh/gopl-zh.github.com" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://github.com/gopl-zh/gopl-zh.github.com/edit/master/./ch1/ch1-07.md" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script type="text/javascript">
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<!-- Page table of contents -->
<div class="sidetoc"><nav class="pagetoc"></nav></div>
<main>
<!-- 头部 -->
<ul dir="auto">
<li><em>凹语言(专为 WebAssembly 设计): <a href="https://github.com/wa-lang/wa">https://github.com/wa-lang/wa</a></em></li>
<li><em>KCL 配置语言(Rust): <a href="https://github.com/kcl-lang/kcl">https://github.com/kcl-lang/kcl</a></em></li>
</ul>
<hr>
<h2 id="17-web服务"><a class="header" href="#17-web服务">1.7. Web服务</a></h2>
<p>Go语言的内置库使得写一个类似fetch的web服务器变得异常地简单。在本节中我们会展示一个微型服务器这个服务器的功能是返回当前用户正在访问的URL。比如用户访问的是 http://localhost:8000/hello 那么响应是URL.Path = &quot;hello&quot;</p>
<p><u><i>gopl.io/ch1/server1</i></u></p>
<pre><code class="language-go">// Server1 is a minimal &quot;echo&quot; server.
package main
import (
&quot;fmt&quot;
&quot;log&quot;
&quot;net/http&quot;
)
func main() {
http.HandleFunc(&quot;/&quot;, handler) // each request calls handler
log.Fatal(http.ListenAndServe(&quot;localhost:8000&quot;, nil))
}
// handler echoes the Path component of the request URL r.
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, &quot;URL.Path = %q\n&quot;, r.URL.Path)
}
</code></pre>
<p>我们只用了八九行代码就实现了一个Web服务程序这都是多亏了标准库里的方法已经帮我们完成了大量工作。main函数将所有发送到/路径下的请求和handler函数关联起来/开头的请求其实就是所有发送到当前站点上的请求服务监听8000端口。发送到这个服务的“请求”是一个http.Request类型的对象这个对象中包含了请求中的一系列相关字段其中就包括我们需要的URL。当请求到达服务器时这个请求会被传给handler函数来处理这个函数会将/hello这个路径从请求的URL中解析出来然后把其发送到响应中这里我们用的是标准输出流的fmt.Fprintf。Web服务会在第7.7节中做更详细的阐述。</p>
<p>让我们在后台运行这个服务程序。如果你的操作系统是Mac OS X或者Linux那么在运行命令的末尾加上一个&amp;符号即可让程序简单地跑在后台windows下可以在另外一个命令行窗口去运行这个程序。</p>
<pre><code>$ go run src/gopl.io/ch1/server1/main.go &amp;
</code></pre>
<p>现在可以通过命令行来发送客户端请求了:</p>
<pre><code>$ go build gopl.io/ch1/fetch
$ ./fetch http://localhost:8000
URL.Path = &quot;/&quot;
$ ./fetch http://localhost:8000/help
URL.Path = &quot;/help&quot;
</code></pre>
<p>还可以直接在浏览器里访问这个URL然后得到返回结果如图1.2</p>
<p><img src="../images/ch1-02.png" alt="" /></p>
<p>在这个服务的基础上叠加特性是很容易的。一种比较实用的修改是为访问的url添加某种状态。比如下面这个版本输出了同样的内容但是会对请求的次数进行计算对URL的请求结果会包含各种URL被访问的总次数直接对/count这个URL的访问要除外。</p>
<p><u><i>gopl.io/ch1/server2</i></u></p>
<pre><code class="language-go">// Server2 is a minimal &quot;echo&quot; and counter server.
package main
import (
&quot;fmt&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;sync&quot;
)
var mu sync.Mutex
var count int
func main() {
http.HandleFunc(&quot;/&quot;, handler)
http.HandleFunc(&quot;/count&quot;, counter)
log.Fatal(http.ListenAndServe(&quot;localhost:8000&quot;, nil))
}
// handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
count++
mu.Unlock()
fmt.Fprintf(w, &quot;URL.Path = %q\n&quot;, r.URL.Path)
}
// counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
mu.Lock()
fmt.Fprintf(w, &quot;Count %d\n&quot;, count)
mu.Unlock()
}
</code></pre>
<p>这个服务器有两个请求处理函数根据请求的url不同会调用不同的函数对/count这个url的请求会调用到counter这个函数其它的url都会调用默认的处理函数。如果你的请求pattern是以/结尾那么所有以该url为前缀的url都会被这条规则匹配。在这些代码的背后服务器每一次接收请求处理时都会另起一个goroutine这样服务器就可以同一时间处理多个请求。然而在并发情况下假如真的有两个请求同一时刻去更新count那么这个值可能并不会被正确地增加这个程序可能会引发一个严重的bug竞态条件参见9.1。为了避免这个问题我们必须保证每次修改变量的最多只能有一个goroutine这也就是代码里的mu.Lock()和mu.Unlock()调用将修改count的所有行为包在中间的目的。第九章中我们会进一步讲解共享变量。</p>
<p>下面是一个更为丰富的例子handler函数会把请求的http头和请求的form数据都打印出来这样可以使检查和调试这个服务更为方便</p>
<p><u><i>gopl.io/ch1/server3</i></u></p>
<pre><code class="language-go">// handler echoes the HTTP request.
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, &quot;%s %s %s\n&quot;, r.Method, r.URL, r.Proto)
for k, v := range r.Header {
fmt.Fprintf(w, &quot;Header[%q] = %q\n&quot;, k, v)
}
fmt.Fprintf(w, &quot;Host = %q\n&quot;, r.Host)
fmt.Fprintf(w, &quot;RemoteAddr = %q\n&quot;, r.RemoteAddr)
if err := r.ParseForm(); err != nil {
log.Print(err)
}
for k, v := range r.Form {
fmt.Fprintf(w, &quot;Form[%q] = %q\n&quot;, k, v)
}
}
</code></pre>
<p>我们用http.Request这个struct里的字段来输出下面这样的内容</p>
<pre><code>GET /?q=query HTTP/1.1
Header[&quot;Accept-Encoding&quot;] = [&quot;gzip, deflate, sdch&quot;]
Header[&quot;Accept-Language&quot;] = [&quot;en-US,en;q=0.8&quot;]
Header[&quot;Connection&quot;] = [&quot;keep-alive&quot;]
Header[&quot;Accept&quot;] = [&quot;text/html,application/xhtml+xml,application/xml;...&quot;]
Header[&quot;User-Agent&quot;] = [&quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)...&quot;]
Host = &quot;localhost:8000&quot;
RemoteAddr = &quot;127.0.0.1:59911&quot;
Form[&quot;q&quot;] = [&quot;query&quot;]
</code></pre>
<p>可以看到这里的ParseForm被嵌套在了if语句中。Go语言允许这样的一个简单的语句结果作为局部的变量声明出现在if语句的最前面这一点对错误处理很有用处。我们还可以像下面这样写当然看起来就长了一些</p>
<pre><code class="language-go">err := r.ParseForm()
if err != nil {
log.Print(err)
}
</code></pre>
<p>用if和ParseForm结合可以让代码更加简单并且可以限制err这个变量的作用域这么做是很不错的。我们会在2.7节中讲解作用域。</p>
<p>在这些程序中我们看到了很多不同的类型被输出到标准输出流中。比如前面的fetch程序把HTTP的响应数据拷贝到了os.Stdoutlissajous程序里我们输出的是一个文件。fetchall程序则完全忽略到了HTTP的响应Body只是计算了一下响应Body的大小这个程序中把响应Body拷贝到了ioutil.Discard。在本节的web服务器程序中则是用fmt.Fprintf直接写到了http.ResponseWriter中。</p>
<p>尽管三种具体的实现流程并不太一样他们都实现一个共同的接口即当它们被调用需要一个标准流输出时都可以满足。这个接口叫作io.Writer在7.1节中会详细讨论。</p>
<p>Go语言的接口机制会在第7章中讲解为了在这里简单说明接口能做什么让我们简单地将这里的web服务器和之前写的lissajous函数结合起来这样GIF动画可以被写到HTTP的客户端而不是之前的标准输出流。只要在web服务器的代码里加入下面这几行。</p>
<pre><code class="language-Go">handler := func(w http.ResponseWriter, r *http.Request) {
lissajous(w)
}
http.HandleFunc(&quot;/&quot;, handler)
</code></pre>
<p>或者另一种等价形式:</p>
<pre><code class="language-Go">http.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {
lissajous(w)
})
</code></pre>
<p>HandleFunc函数的第二个参数是一个函数的字面值也就是一个在使用时定义的匿名函数。这些内容我们会在5.6节中讲解。</p>
<p>做完这些修改之后,在浏览器里访问 http://localhost:8000 。每次你载入这个页面都可以看到一个像图1.3那样的动画。</p>
<p><img src="../images/ch1-03.png" alt="" /></p>
<p><strong>练习 1.12</strong> 修改Lissajour服务从URL读取变量比如你可以访问 http://localhost:8000/?cycles=20 这个URL这样访问可以将程序里的cycles默认的5修改为20。字符串转换为数字可以调用strconv.Atoi函数。你可以在godoc里查看strconv.Atoi的详细说明。</p>
<!-- 公众号 -->
<hr>
<table>
<tr>
<td>
<img width="222px" src="https://chai2010.cn/advanced-go-programming-book/css.png">
</td>
<td>
<img width="222px" src="https://chai2010.cn/advanced-go-programming-book/cch.png">
</td>
</tr>
</table>
<div id="giscus-container"></div>
<footer class="page-footer">
<span>© 2015-2016 | <a href="https://github.com/gopl-zh"> Go语言圣经中文版</a>, 仅学习交流使用</span>
</footer>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../ch1/ch1-06.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next" href="../ch1/ch1-08.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="../ch1/ch1-06.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next" href="../ch1/ch1-08.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script type="text/javascript">
window.playground_copyable = true;
</script>
<script src="../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../mark.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../searcher.js" type="text/javascript" charset="utf-8"></script>
<script src="../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../highlight.js" type="text/javascript" charset="utf-8"></script>
<script src="../book.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var pagePath = "ch1/ch1-07.md"
</script>
<!-- Custom JS scripts -->
<script type="text/javascript" src="../js/custom.js"></script>
<script type="text/javascript" src="../js/bigPicture.js"></script>
</body>
</html>