golang http 服务器的接口梳理

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()
}

原文地址:https://www.cnblogs.com/linyihai/p/10847562.html

时间: 2024-08-01 00:13:31

golang http 服务器的接口梳理的相关文章

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

App开发:模拟服务器数据接口 - MockApi 为了方便app开发过程中,不受服务器接口的限制,便于客户端功能的快速测试,可以在客户端实现一个模拟服务器数据接口的MockApi模块.本篇文章就尝试为使用gradle的android项目设计实现MockApi. 需求概述 在app开发过程中,在和服务器人员协作时,一般会第一时间确定数据接口的请求参数和返回数据格式,然后服务器人员会尽快提供给客户端可调试的假数据接口.不过有时候就算是假数据接口也来不及提供,或者是接口数据格式来回变动--很可能是客

开放录像服务器SDK接口(AnyChat Record Server SDK)

亲,非常高兴的告诉您,从AnyChat r4115版本开始,我们开放了录像服务器SDK接口(AnyChat Record Server SDK). 录像服务器SDK支持的平台包括Windows.Linux(x86.x64),支持的开发语言有C++.Java,示例代码位于SDK的src\recordserver目录下.AnyChat Record Server SDK是服务器端SDK,用于上层应用实现特定的服务器录制功能.通过SDK接口可以获取到每个用户的视频.语音.通信数据,由上层应用自己写入文

Golang游戏服务器

我对和GOLANG写MMO服务器的一些遐想: 1.沙盒(隔离性) SKYNET:原生LUA STATE作为沙盒, 进行服务器间隔离安全性高: 服务可以很容易的配置到不同节点之上. GO:估计用RECOVER,PANIC来支持, 用GORUTINE来当做服务:或许间点可以通过开关,选择性开放服务,也是可以做到的. 2.热更新 SKYNET:snax 热更新, 还是比较方便, 直接个修改接口代码 GO:或许可以通过, SERVICE化服务, 可以做到无感知更新程序: 不得不说GO写网络太方便了,很多

grpc(4):使用 golang 调用consul api 接口,注册user-tomcat服务

1,关于consul dubbo的注册中心是zookeeper,redis. motan的注册中心是zookeeper,consul. kubernetes的注册中心是 etcd. 使用consul的好处是服务发现啥的都支持了. 可以使用域名进行负载均衡. 也是一个不错的 Server-Side Discovery Pattern . 2,启动consul服务,调用接口 首先要在服务器安装一个consul服务: http://blog.csdn.net/freewebsys/article/de

AsyncTask类插入数据到服务器与接口回调

////////////////2016/04/21///////////////////// //////////////by XBW/////////////////////////// ///////////环境  api22 eclipse ///////////// 搞了这么久终于弄好了接口,之前都是一个人在做项目,自己随心所欲的写代码,想怎么写就怎么写,到了团队呢,这接口那接口,各种类,各种枚举,各种内部类,抽象类,单例懒汉,单例饿汉的,也算学了不少东西, 我做的是把数据插入到数据库

模式识别之腾讯云服务器---腾讯服务器机器学习接口

在用过阿里云后,感觉阿里云服务器有时候不稳定,而且还延时大,所以逛逛腾讯云,发现有个机器学习接口,就略看了下,东西还蛮多的 lda lr cnn http://www.qcloud.com/product/XGPush.html 费用也差不多700最低配置一年 http://www.qcloud.com/wiki/%E7%AE%97%E6%B3%95%E5%8E%9F%E7%90%86 http://www.cnblogs.com/wavky/p/from-China-to-Japan.html

【网络开发】WeX5的Ajax和Django服务器json接口对接跨域问题解决

问题背景 WeX5是典型的html5+js架构.源文件全部放到服务器的UI Server中,使用通用的tomcat,例如使用域名www.wuyoubar.cn:8080/x5. Android和IOS的服务器端Django已经实现了json的处理,json的主域名www.wuyoubar.cn:80 PC访问WeX5页面.避免重复进行数据处理,WeX5的JS代码里面直接使用Ajax请求Django的json接口数据.这样就出现了跨域的问题,对于客户端来说,请求的源码,页面文件,css和js代码等

音视频中录像服务器SDK接口

录像服务器SDK支持的平台包括Windows.Linux(x86.x64),支持的开发语言有C++.Java,示例代码位于SDK的src\recordserver目录下.AnyChat Record Server SDK是服务器端SDK,用于上层应用实现特定的服务器录制功能.通过SDK接口可以获取到每个用户的视频.语音.通信数据,由上层应用自己写入文件. 录像服务器SDK的工作原理是: 一.录像服务器启动:调用API:BRRS_InitSDK(0);之后,录像服务器主动与核心服务器建立连接,连接

WSGI:全拼为Pyon Web服务器网关接口,Pyon今日,转发这段视频

yecars 是一个用于生成 Ecars 图表的类库.Ecars 是百度开源的一个数据可视化 JS 库.用 Ecars 生成的图可视化效果非常棒,yecars 是为了 SringBoo默认情况使用jar方式进行打包,并通过jar的方式来启动一个服务. 可以这样启动是因为Sring Boo内嵌了多种服务器,SringBoo 1514版本 本文利用jenkins在k8s中简单实践了一下CICD,部分实验内容来自Se U a CICD Pieline wi Kubernees?,除此外,还试验了一把利