golang http 服务器的接口梳理
golang http 服务器的接口梳理
Hanlde和HandleFunc以及Handler, HandlerFunc
func Handle(pattern string, handler Handler)
// Handle 函数将pattern和对应的handler注册进DefaultServeMux
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
// HandleFunc registers the handler function for the given pattern in the DefaultServeMux
// Handler
//
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
// HandlerFunc能够将一个普通的处理函数转化为Handler
type HandlerFunc func(ResponseWriter, *Request)
HandleFunc仅接受一个func为参数,相对于简洁些。Handle则需要传入一个带有ServeHTTP的结构体,因此控制逻辑可以灵活些。
Handle的例子
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
type countHandler struct {
mu sync.Mutex // guards n
n int
}
func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
defer h.mu.Unlock()
h.n++
fmt.Fprintf(w, "count is %d\n", h.n)
}
func main() {
http.Handle("/count", new(countHandler))
log.Fatal(http.ListenAndServe(":8080", nil))
}
HandleFunc的例子
h1 := func(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "Hello from a HandleFunc #1!\n")
}
h2 := func(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "Hello from a HandleFunc #2!\n")
}
http.HandleFunc("/", h1)
http.HandleFunc("/endpoint", h2)
log.Fatal(http.ListenAndServe(":8080", nil))
##### ListenAndServe
```
// 监听TCP然后调用handler对应的Serve去处理请求。handler默认为nil,则使用DefaultServeMux
func ListenAndServe(addr string, handler Handler) error
```
##### ServeMux
路由调度器,根据请求url调用handler去处理。实现了Handle,HandleFunc方法。
ServeMux实现了ServeHTTP因此也是一个Handler接口
```
// 新建
func NewServeMux() *ServeMux
// 方法
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
func (mux *ServeMux) Handle(pattern string, handler Handler)
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
//
mux := http.NewServeMux()
mux.Handle("/api/", apiHandler{})
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
// The "/" pattern matches everything, so we need to check
// that we're at the root here.
if req.URL.Path != "/" {
http.NotFound(w, req)
return
}
fmt.Fprintf(w, "Welcome to the home page!")
})
```
##### Server 类型
```
type Server struct {
Addr string // TCP address to listen on, ":http" if empty
Handler Handler // handler to invoke, http.DefaultServeMux if nil
TLSConfig *tls.Config
ReadTimeout time.Duration
ReadHeaderTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
MaxHeaderBytes int
TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
ConnState func(net.Conn, ConnState)
ErrorLog *log.Logger
// contains filtered or unexported fields
}
// 方法
func (srv *Server) Close() error
func (srv *Server) ListenAndServe() error
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
func (srv *Server) RegisterOnShutdown(f func())
func (srv *Server) Serve(l net.Listener) error
func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error
func (srv *Server) SetKeepAlivesEnabled(v bool)
func (srv *Server) Shutdown(ctx context.Context) error
```
可以通过Server类型来改变默认的Server配置,如改变监听端口等。
```
func main(){
http.HandleFunc("/", index)
server := &http.Server{
Addr: ":8000",
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
}
server.ListenAndServe()
}
// 自定义的serverMux对象也可以传到server对象中。
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", index)
server := &http.Server{
Addr: ":8000",
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
Handler: mux,
}
server.ListenAndServe()
}
golang http 服务器的接口梳理的更多相关文章
- 治理Go模块 服务治理 中台业务 Golang的net.Conn接口,double close
小结: 1.中台业务 前台业务 快车.专车.顺风车,在滴滴这些业务线叫做前台服务,他们有一些共同的特性,都有司机信息,订单的状态,收银,账号等等这些业务逻辑,我们会把专门的业务逻辑集合起来,形成专职的 ...
- Golang 基础之基础语法梳理 (三)
大家好,今天将梳理出的 Go语言基础语法内容,分享给大家. 请多多指教,谢谢. 本次<Go语言基础语法内容>共分为三个章节,本文为第三章节 Golang 基础之基础语法梳理 (一) Gol ...
- Golang 基础之基础语法梳理 (一)
大家好,今天将梳理出的 Go语言基础语法内容,分享给大家. 请多多指教,谢谢. 本次<Go语言基础语法内容>共分为三个章节,本文为第一章节 Golang 基础之基础语法梳理 (一) Gol ...
- App开发:模拟服务器数据接口 - MockApi
为了方便app开发过程中,不受服务器接口的限制,便于客户端功能的快速测试,可以在客户端实现一个模拟服务器数据接口的MockApi模块.本篇文章就尝试为使用gradle的android项目设计实现Moc ...
- GoLang之方法与接口
GoLang之方法与接口 Go语言没有沿袭传统面向对象编程中的诸多概念,比如继承.虚函数.构造函数和析构函数.隐藏的this指针等. 方法 Go 语言中同时有函数和方法.方法就是一个包含了接受者的函数 ...
- 微信公众平台开发-微信服务器IP接口实例(含源码)
微信公众平台开发-access_token获取及应用(含源码)作者: 孟祥磊-<微信公众平台开发实例教程> 学习了access_token的获取及应用后,正式的使用access_token ...
- React 获取服务器API接口数据:axios、fetchJsonp
使用axios.fetchJsonp获取服务器的接口数据.其中fetchJsonp是跨域访问 一.使用axios 1.安装axios模块 npm install --save axios 2.引用模块 ...
- WSGI——python web 服务器网关接口
转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10826084.html 一:服务器.服务器软件.应用程序(后台) 我们常说“服务器”,实际上服务器是一个很宽 ...
- Cockpit- Linux 服务器管理接口
Cockpit- Linux 服务器管理接口 功能 它包含 systemd 服务管理器. 有一个用于故障排除和日志分析的 Journal 日志查看器. 包括 LVM 在内的存储配置比以前任何时候都要简 ...
随机推荐
- PATA1001A+BFormat
这里学到的主要是将数字存储到数组中,倒序输出使用取余10加除10 while(sum) { num[len++] = sum % 10; sum /= 10; } 然后是每三位输出一个逗号,因为是倒序 ...
- helm原理
Helm: helm就相当于Linux的包管理工具yum,但它管理的程序包是一些打包好的清单文件. 其核心术语: Chart:一个helm程序包,它里面可理解为,包含了一下定义Pod的清单文件,这些清 ...
- python requests 上传excel数据流
headers=self.headers #获取导入模版 file_home = self.import_template log.info(file_home) wb = load_workbook ...
- python总结二
1.在命令行:dd是删除光标所在的那一整行 yy是复制光标所在的那一整行 p是将已复制的数据在光标的下一行粘贴 P是将已复制的数据在光标的上一行粘贴 2.在命令行中查找的话 从上往下查找:/ 从下往上 ...
- Flask项目之入门
from flask import Flask #实例化Flask对象 app = Flask(__name__) #传入当前的文件名__name__ #将‘/’ 和函数index的对应关系添加到路由 ...
- Maven 教程(12)— Maven生命周期和插件
原文地址:https://blog.csdn.net/liupeifeng3514/article/details/79549695 除了坐标.依赖以及仓库之外,Maven的另外两个核心概念是生命周期 ...
- AQS3---出队(凌乱,供参考,先看AQS2)
出队时候,如果队列处于稳定状态,那么就是一个挨着一个出队,难点在于出队的时候,队列正处于调整阶段,那么此时队列中的关系是混乱无章可寻的. 出队:unlock释放锁,不在队列线程去抢锁,队列第一个正常 ...
- Linux下常用目录有哪些?分别有什么作用?
/boot:这个目录是用来存放与系统启动相关的文件 /root:root用户的家目录 /bin:存放大部分的二进制的可执行文件,也就是大部分的linux命令. /tmp:这个文件目录一般是公共的,也就 ...
- 模板方法(TemplateMethod)模式
模板方法模式是准备一个抽象类,将部分逻辑以具体方法以及构造子的形式出现,然后声明一些抽象方法来迫使子类实现剩余的逻辑.不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑部分有不同的实现.这也 ...
- Excel批量添加不同的批注
Sub 批量添加不同批注() Dim rng As Range Dim i As String Range("A1:D1").ClearComments For Each rng ...