当前位置: 首页 > news >正文

Go网络编程-HTTP程序设计_2

HTTP程序设计

Go编写HTTP服务器,用 Go实现一个 http server非常容易,Go 语言标准库 net/http自带了一系列结构和方法来帮助开发者简化 HTTP 服务开发的相关流程。因此,我们不需要依赖任何第三方组件就能构建并启动一个高并发的 HTTP 服务器。

简单的HTTP服务器

函数:

 // http.ListenAndServefunc ListenAndServe(addr string, handler Handler) error

用于启动HTTP服务器,监听addr,并使用handler来处理请求。返回启动错误。其中:

  • addr,TCP address,形式为 IP:port,IP省略表示监听全部网络接口

  • handler,经常的被设置为nil,表示使用DefaultServeMux(默认服务复用器)来处理请求。

  • DefaultServeMux要使用以下两个函数来添加请求处理器

    • func Handle(pattern string, handler Handler)

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

示例代码:

httpServerSimple.go

 func HttpServerSimple() {// 一:设置不同路由(path)对应不同的处理器// /ping <-> ponghttp.HandleFunc("/ping", handlePing)​// 三:使用http.Handle设置处理器对象infoHandler := InfoHandler{info: "Welcome to Mashibing Go classroom.",}http.Handle("/info", infoHandler)​// 二:启动监听并提供服务addr := ":8088"log.Println("http server is listening on ", addr)err := http.ListenAndServe(addr, nil)log.Fatalln(err)}​// http.ResponseWriter 响应Writer// *http.Request 请求对象,包含了请求信息func handlePing(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "pong")}​// InfoHandler 实现Handler接口的类型type InfoHandler struct {info string}​func (h InfoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, h.info)}

其中:Handler 接口的定义为:

 type Handler interface {ServeHTTP(ResponseWriter, *Request)}

我们的 InfoHandler实现了Handler接口,可以作为 http.Handle()的第二个参数来使用。

测试,通过main.main() 启动服务器:

httpServerSimple.go

 func main() {// 简单的HTTP服务器HttpServerSimple()}

运行

 go run httpServerSimple.go2023/03/02 21:00:29 http server is listening on  :8088

请求测试:

 curl http://localhost:8088/pingpong​curl http://localhost:8088/infoWelcome to Mashibing Go classroom.

复杂的HTTP服务器

定制性的HTTP服务器,通过 Server 类型进行设置。其定义如下:

 // net/httptype Server struct {// TCP AddressAddr stringHandler Handler // handler to invoke, http.DefaultServeMux if nil// LSConfig optionally provides a TLS configuration for use// by ServeTLS and ListenAndServeTLSTLSConfig *tls.Config// 读请求超时时间ReadTimeout time.Duration// 读请求头超时时间ReadHeaderTimeout time.Duration// 写响应超时时间WriteTimeout time.Duration// 空闲超时时间IdleTimeout time.Duration// Header最大长度MaxHeaderBytes int​// 其他字段略}

该类型的 func (srv *Server) ListenAndServe() error 函数用于监听和服务。

示例代码:

 // @file: HttpServerCustom.go​func HttpServerCustom() {myHandler := CustomHandler{message: "http.Server"}s := &http.Server{Addr:           ":8080",Handler:        myHandler,ReadTimeout:    10 * time.Second,WriteTimeout:   10 * time.Second,MaxHeaderBytes: 1 << 20,}log.Fatal(s.ListenAndServe())}​type CustomHandler struct {message string}​func (h CustomHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {time.Sleep(10 * time.Second)fmt.Fprintf(w, h.message)}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 新时代多目标优化【数学建模】领域的极致探索——数学规划模型
  • ​数据结构之初始二叉树(3)
  • C语言 ——— 打印水仙花数
  • ubuntu22.04安装SecureCRT8.7.3,完成顺利使用
  • 【面试题】数据结构:堆排序的排序思想?
  • 辅助类BigDecima/BigInteger
  • 【Windows】操作系统之任务管理器(第一篇)
  • 车载音视频App框架设计
  • 前端pc和小程序接入快递100(跳转方式和api方式)====实时查询接口
  • Self-supervised Learning for Pre-Training 3D Point Clouds: A Survey
  • 如何免费用java c#实现手机在网状态查询
  • 【Apache POI】Java解析Excel文件并处理合并单元格-粘贴即用
  • Java 在PDF中替换文字(详解)
  • Google资深工程师深度讲解Go语言-课程笔记
  • 一个简单的springboot应用搭建过程
  • 「前端早读君006」移动开发必备:那些玩转H5的小技巧
  • Android路由框架AnnoRouter:使用Java接口来定义路由跳转
  • Java Agent 学习笔记
  • SQL 难点解决:记录的引用
  • web标准化(下)
  • 大整数乘法-表格法
  • 关于使用markdown的方法(引自CSDN教程)
  • 缓存与缓冲
  • 利用jquery编写加法运算验证码
  • 漂亮刷新控件-iOS
  • 思否第一天
  • 想写好前端,先练好内功
  • 国内唯一,阿里云入选全球区块链云服务报告,领先AWS、Google ...
  • 通过调用文摘列表API获取文摘
  • ​​​​​​​​​​​​​​汽车网络信息安全分析方法论
  • #Ubuntu(修改root信息)
  • #我与Java虚拟机的故事#连载18:JAVA成长之路
  • $.ajax,axios,fetch三种ajax请求的区别
  • (70min)字节暑假实习二面(已挂)
  • (C语言)逆序输出字符串
  • (C语言)字符分类函数
  • (delphi11最新学习资料) Object Pascal 学习笔记---第2章第五节(日期和时间)
  • (Oracle)SQL优化技巧(一):分页查询
  • (二)JAVA使用POI操作excel
  • (使用vite搭建vue3项目(vite + vue3 + vue router + pinia + element plus))
  • (图)IntelliTrace Tools 跟踪云端程序
  • (自适应手机端)响应式服装服饰外贸企业网站模板
  • .net 4.0 A potentially dangerous Request.Form value was detected from the client 的解决方案
  • .NET MVC 验证码
  • .net mvc部分视图
  • .NET企业级应用架构设计系列之结尾篇
  • [ C++ ] STL---string类的使用指南
  • [\u4e00-\u9fa5] //匹配中文字符
  • [20150904]exp slow.txt
  • [2016.7 day.5] T2
  • [AutoSar]BSW_Memory_Stack_004 创建一个简单NV block并调试
  • [BZOJ 3282] Tree 【LCT】
  • [C++]: 模板进阶
  • [C++]二叉搜索树
  • [C++11 多线程同步] --- 条件变量的那些坑【条件变量信号丢失和条件变量虚假唤醒(spurious wakeup)】