golang快速入门(五)初尝web服务
2021-06-01 16:43
453 查看
提示:本系列文章适合对Go有持续冲动的读者
初探golang web服务
golang web开发是其一项重要且有竞争力的应用,本小结来看看再golang中怎么创建一个简单的web服务。
在不适用web框架的情况下,可以使用
net/http包搭建一个web服务。
- 这里我们使用
net/http
创建一个打印请求URL的web服务。
package main import ( //"log" "fmt" "net/http" ) func main() { http.HandleFunc("/", handler) http.ListenAndServe("localhost:6677", nil) } func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "url.path=%q\n", r.URL.Path) //输出到文件流 }
http.HandleFunc函数可以理解为URL路由。
http.ListenAndServe是web服务的创建核心。
handler是http请求处理函数,接受一个
http.ResponseWriter文件流 和
http.Request类型的对象。
[root@VM-0-5-centos ~]# curl localhost:6677/123 url.path="/123"
- 我们通过handler函数来对访问url做访问数计算。
引入golang
sync中的互斥锁,这样同时存在多个请求时只有一个goroutine改变count计数。互斥锁后续深入了解。
package main import ( //"log" "fmt" "net/http" "sync" ) var count int var mutex sync.Mutex //使用互斥锁 func main() { http.HandleFunc("/", handler) http.ListenAndServe("localhost:6677", nil) } func handler(w http.ResponseWriter, r *http.Request) { mutex.Lock() count++ mutex.Unlock() fmt.Fprintf(w, "request url.path:%q has %d times\n", r.URL.Path, count) }
我们来看看请求结果如下:
[root@VM-0-5-centos ~]# curl localhost:6677/golang request url.path:"/golang" has 1 times [root@VM-0-5-centos ~]# curl localhost:6677/golang request url.path:"/golang" has 2 times [root@VM-0-5-centos ~]# curl localhost:6677/golang request url.path:"/golang" has 3 times
http.Request
类型对象除了URL.Path
属性外还有Method
、Proto
等。我们通过handler
函数分别打印出来。
package main import ( //"log" "fmt" "net/http" "sync" ) var count int var mutex sync.Mutex //使用互斥锁 func main() { http.HandleFunc("/", handler) http.ListenAndServe("localhost:6677", nil) } func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "%s,%s,%s,\n", r.Method, r.URL, r.Proto) fmt.Fprintf(w, "host:%q\nremoteaddr:%q\n", r.Host, r.RemoteAddr) for k, v := range r.Header { fmt.Fprintf(w, "Header[%q]:%q\n", k, v) } for k, v := range r.Form { fmt.Fprintf(w, "Form[%q]:%q\n", k, v) } }
创建表单接受后输出如下:
//output GET,/helloweb,HTTP/1.1, host:"localhost:6677" remoteaddr:"127.0.0.1:58088" Header["User-Agent"]:["curl/7.29.0"] Header["Accept"]:["*/*"] Form[parm1]:hello Form[parm2]:web
本次简单的了解了一下golang web服务,也是初尝章节结束。接下来会比较深入的学习golang的精彩细节与精华。
文章有不足的地方欢迎在评论区指出。
欢迎收藏、点赞、提问。关注顶级饮水机管理员,除了管烧热水,有时还做点别的。
相关文章推荐
- SpringBoot入门-快速搭建web服务
- Golang Web 框架 Beego 快速入门 - 01
- JMeter快速入门知识系列(14)----JMeter测试Web服务
- Spring基础:快速入门spring boot(3):创建Restful的Web服务
- Web服务快速入门
- Java Web Services (1) - 第1章 Web服务快速入门
- Golang web 语言编程快速入门视频课程
- Golang Web开发之Gin入门
- linux入门系列20--Web服务之LNMP架构实战
- Spring Cloud(六)服务网关 zuul 快速入门
- 服务化介绍 和 快速入门
- 简单粗暴,详细得不要不要的 JavaWeb快速入门实例(1)
- Tiny快速入门之Web界面快速开发实践
- 【JavaWeb-26】MyBatis快速入门程序+一些扩展
- .NET之ASPWebApplication快速入门(2)
- .NET之ASPWebApplication快速入门(1)
- GeoServer基础教程(二):GeoServer的Web管理界面快速入门
- R语言Web开发框架shiny包快速入门
- [导入].NET之ASPWebApplication快速入门(1)
- JAVAEE——SpringBoot入门:简介、微服务、环境准备、helloworld与探究、快速构建项目