golang http 服务器的接口梳理

Golang构建HTTP服务(二)--- Handler,ServeMux与中间件

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 服务器的接口梳理的更多相关文章

  1. 治理Go模块 服务治理 中台业务 Golang的net.Conn接口,double close

    小结: 1.中台业务 前台业务 快车.专车.顺风车,在滴滴这些业务线叫做前台服务,他们有一些共同的特性,都有司机信息,订单的状态,收银,账号等等这些业务逻辑,我们会把专门的业务逻辑集合起来,形成专职的 ...

  2. Golang 基础之基础语法梳理 (三)

    大家好,今天将梳理出的 Go语言基础语法内容,分享给大家. 请多多指教,谢谢. 本次<Go语言基础语法内容>共分为三个章节,本文为第三章节 Golang 基础之基础语法梳理 (一) Gol ...

  3. Golang 基础之基础语法梳理 (一)

    大家好,今天将梳理出的 Go语言基础语法内容,分享给大家. 请多多指教,谢谢. 本次<Go语言基础语法内容>共分为三个章节,本文为第一章节 Golang 基础之基础语法梳理 (一) Gol ...

  4. App开发:模拟服务器数据接口 - MockApi

    为了方便app开发过程中,不受服务器接口的限制,便于客户端功能的快速测试,可以在客户端实现一个模拟服务器数据接口的MockApi模块.本篇文章就尝试为使用gradle的android项目设计实现Moc ...

  5. GoLang之方法与接口

    GoLang之方法与接口 Go语言没有沿袭传统面向对象编程中的诸多概念,比如继承.虚函数.构造函数和析构函数.隐藏的this指针等. 方法 Go 语言中同时有函数和方法.方法就是一个包含了接受者的函数 ...

  6. 微信公众平台开发-微信服务器IP接口实例(含源码)

    微信公众平台开发-access_token获取及应用(含源码)作者: 孟祥磊-<微信公众平台开发实例教程> 学习了access_token的获取及应用后,正式的使用access_token ...

  7. React 获取服务器API接口数据:axios、fetchJsonp

    使用axios.fetchJsonp获取服务器的接口数据.其中fetchJsonp是跨域访问 一.使用axios 1.安装axios模块 npm install --save axios 2.引用模块 ...

  8. WSGI——python web 服务器网关接口

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10826084.html 一:服务器.服务器软件.应用程序(后台) 我们常说“服务器”,实际上服务器是一个很宽 ...

  9. Cockpit- Linux 服务器管理接口

    Cockpit- Linux 服务器管理接口 功能 它包含 systemd 服务管理器. 有一个用于故障排除和日志分析的 Journal 日志查看器. 包括 LVM 在内的存储配置比以前任何时候都要简 ...

随机推荐

  1. 学好Python后可从事岗位+学习Python的难度

    一.学好Python好就业: 1.Linux运维.Linux运维是必须而且一定要掌握Python语言,Python可以满足Linux运维工程师的工作需求提升效率,总而提升自己的能力.用Python实现 ...

  2. springboot2.x自定义拦截把static静态文件给拦截的坑

    新人新帖,喷后请指正,谢谢 1.王中王,坑中坑 和很多人一样,我在springboo自定义配置登录拦截的时候,写一个WebConfig类继承WebMvcConfigureAdapter,重写AddRe ...

  3. python爬虫实例——爬取歌单

    学习自<<从零开始学python网络爬虫>> 爬取酷狗歌单,保存入csv文件 直接上源代码:(含注释) import requests #用于请求网页获取网页数据 from b ...

  4. Spring Boot 2.2.1 发布,一个有点坑的版本!

    上一篇:Spring Boot 2.2.0 正式发布,支持 JDK 13! Spring Boot 2.2.0 没发布多久,Spring Boot 2.2.1 又发布了,这是一个很有意思,又有点 &q ...

  5. bat无线热点设置

    netsh wlan set hostednetwork mode=allow ssid=happyla key=1234567890netsh wlan start hostednetwork

  6. jquery设置bootstrap-table的当前选中页码的获取与设置

    一.获取当前table分页的页码 有两种方式可以获得当前选中的页码: 1.通过table的onPageChange方法 $('#agentTable').bootstrapTable({ data: ...

  7. 【C++】虚函数的实现机制

    一.什么是虚函数? 虚函数是在类中由virtual关键字声明的成员函数,并且每一个含有虚函数的类都至少有一个与之对应的虚函数表,其中存放着该类所有虚函数对应的函数指针 在基类中进行如下定义: virt ...

  8. VS2013中反汇编常用指令理解

    最近复习C语言,对反汇编感兴趣,就用下图举例解释一下我的理解,如有错还请大佬指教. 首先,认识两个常用指令 :   lea ---> 取地址赋值      mov ---> (同类型)赋值 ...

  9. C++强大背后

    转自MiloYip大神的博客 [原文]http://www.cnblogs.com/miloyip/archive/2010/09/17/behind_cplusplus.html 在31年前(197 ...

  10. 『正睿OI 2019SC Day2』

    分治 普通分治 普通分治是指针对序列或平面问题的分治算法. 思想 普通分治的思想是指将一个序列问题或平面问题通过某种划分方式划分为若干个子问题,直到子问题规模足够小,可以直接回答,再通过合并得到原问题 ...