Gin 学习之自定义服务器配置信息

简介: Gin 学习之自定义服务器配置信息

01

概念


Gin 框架通过调用 Default 函数,返回一个 *gin.Engine,然后调用 Run 方法构建一个服务器。


func gin.Default() *gin.Engine


Run 方法:


func (engine *Engine) Run(addr ...string) (err error) {
  defer func() { debugPrintError(err) }()
  address := resolveAddress(addr)
  debugPrint("Listening and serving HTTP on %s\n", address)
  err = http.ListenAndServe(address, engine)
  return
}


细心的读者朋友可能已经注意到 Run 方法只能接收一个地址,无法设置服务器的其他配置信息。


通过查看 Run 方法的代码,可以发现 Run 方法实际上是封装了标准库net/http 的 ListenAndServe 函数。


我们接着查看 ListenAndServe 函数的代码:


func ListenAndServe(addr string, handler Handler) error {
  server := &Server{Addr: addr, Handler: handler}
  return server.ListenAndServe()
}


通过查看 ListenAndServe 函数的代码,可以发现 ListenAndServe 函数实际上是定义了一个 Server 结构的变量,并调用其 ListenAndServe 方法。


02

自定义服务器配置信息


根据 Part 01 的内容铺垫,如果我们想要自定义服务器的配置信息,就需要我们通过定义一个 Server 结构的变量,使用 Server 结构的 ListenAndServe 方法构建服务器。因为 Server 结构包含更多关于服务器配置信息的字段。


Server 结构体的代码:


Server struct {
    // Addr optionally specifies the TCP address for the server to listen on,
    // in the form "host:port". If empty, ":http" (port 80) is used.
    // The service names are defined in RFC 6335 and assigned by IANA.
    // See net.Dial for details of the address format.
    Addr string
    Handler Handler // handler to invoke, http.DefaultServeMux if nil
    // TLSConfig optionally provides a TLS configuration for use
    // by ServeTLS and ListenAndServeTLS. Note that this value is
    // cloned by ServeTLS and ListenAndServeTLS, so it's not
    // possible to modify the configuration with methods like
    // tls.Config.SetSessionTicketKeys. To use
    // SetSessionTicketKeys, use Server.Serve with a TLS Listener
    // instead.
    TLSConfig *tls.Config
    // ReadTimeout is the maximum duration for reading the entire
    // request, including the body.
    //
    // Because ReadTimeout does not let Handlers make per-request
    // decisions on each request body's acceptable deadline or
    // upload rate, most users will prefer to use
    // ReadHeaderTimeout. It is valid to use them both.
    ReadTimeout time.Duration
    // ReadHeaderTimeout is the amount of time allowed to read
    // request headers. The connection's read deadline is reset
    // after reading the headers and the Handler can decide what
    // is considered too slow for the body. If ReadHeaderTimeout
    // is zero, the value of ReadTimeout is used. If both are
    // zero, there is no timeout.
    ReadHeaderTimeout time.Duration
    // WriteTimeout is the maximum duration before timing out
    // writes of the response. It is reset whenever a new
    // request's header is read. Like ReadTimeout, it does not
    // let Handlers make decisions on a per-request basis.
    WriteTimeout time.Duration
    // IdleTimeout is the maximum amount of time to wait for the
    // next request when keep-alives are enabled. If IdleTimeout
    // is zero, the value of ReadTimeout is used. If both are
    // zero, there is no timeout.
    IdleTimeout time.Duration
    // MaxHeaderBytes controls the maximum number of bytes the
    // server will read parsing the request header's keys and
    // values, including the request line. It does not limit the
    // size of the request body.
    // If zero, DefaultMaxHeaderBytes is used.
    MaxHeaderBytes int
    // TLSNextProto optionally specifies a function to take over
    // ownership of the provided TLS connection when an ALPN
    // protocol upgrade has occurred. The map key is the protocol
    // name negotiated. The Handler argument should be used to
    // handle HTTP requests and will initialize the Request's TLS
    // and RemoteAddr if not already set. The connection is
    // automatically closed when the function returns.
    // If TLSNextProto is not nil, HTTP/2 support is not enabled
    // automatically.
    TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
    // ConnState specifies an optional callback function that is
    // called when a client connection changes state. See the
    // ConnState type and associated constants for details.
    ConnState func(net.Conn, ConnState)
    // ErrorLog specifies an optional logger for errors accepting
    // connections, unexpected behavior from handlers, and
    // underlying FileSystem errors.
    // If nil, logging is done via the log package's standard logger.
    ErrorLog *log.Logger
    // BaseContext optionally specifies a function that returns
    // the base context for incoming requests on this server.
    // The provided Listener is the specific Listener that's
    // about to start accepting requests.
    // If BaseContext is nil, the default is context.Background().
    // If non-nil, it must return a non-nil context.
    BaseContext func(net.Listener) context.Context
    // ConnContext optionally specifies a function that modifies
    // the context used for a new connection c. The provided ctx
    // is derived from the base context and has a ServerContextKey
    // value.
    ConnContext func(ctx context.Context, c net.Conn) context.Context
    inShutdown atomicBool // true when when server is in shutdown
    disableKeepAlives int32     // accessed atomically.
    nextProtoOnce     sync.Once // guards setupHTTP2_* init
    nextProtoErr      error     // result of http2.ConfigureServer if used
    mu         sync.Mutex
    listeners  map[*net.Listener]struct{}
    activeConn map[*conn]struct{}
    doneChan   chan struct{}
    onShutdown []func()
}


通过 Server 结构体的字段,可以设置更多的服务器配置信息,实现我们构建自定义服务器的需求。





目录
相关文章
|
存储 弹性计算 网络协议
阿里云服务器ECS自定义购买流程:亲测图文全解析
本文详细图解阿里云ECS自定义购买全流程,涵盖付费模式、地域选择、实例规格、镜像、存储、网络、安全组及登录设置等核心配置,助您轻松掌握专业级云服务器搭建方法。
480 0
|
弹性计算 网络协议 Linux
阿里云服务器简介及使用教程,附送云服务器ECS自定义创建流程
阿里云ECS是安全可靠、弹性灵活的云计算服务,支持多种实例规格与操作系统,可快速创建和管理云服务器。本文详解ECS介绍、购买流程及使用教程,涵盖配置选择、网络设置、安全组规则等,助您轻松上手。
919 16
|
存储 弹性计算 网络协议
超详细的阿里云服务器购买流程,ECS自定义购买配置教程
本文详细图解阿里云ECS服务器自定义购买全流程,涵盖付费模式、地域选择、网络配置、实例规格、镜像、存储、安全组及登录设置等核心步骤,助您轻松掌握专业级云服务器搭建方法。
|
弹性计算 Ubuntu Linux
阿里云服务器镜像怎么选?公共/自定义/共享/云市场/社区镜像区别与适用场景梳理
在购买阿里云服务器的过程中,选择合适的镜像(即云服务器的操作系统)是至关重要的一步。阿里云服务器镜像涵盖了公共镜像、自定义镜像、共享镜像、云市场镜像(镜像市场)和社区镜像等多种类型,对于新手用户来说,面对这些不同类型的镜像,往往会感到困惑,不知道它们之间的区别,更不知道如何根据自身需求进行选择。本文为大家解析这些镜像的特点、区别,并为大家提供选择参考。
2122 60
|
存储 弹性计算 安全
阿里云服务器自定义、快速、活动、云市场镜像四种主流方式解析与选择参考
阿里云服务器如何购买?目前主要的购买方式有自定义购买、快速购买、通过活动购买、通过云市场镜像页面购买这四种购买方式。然而,面对阿里云服务器多样化的购买方式和配置选项,许多用户可能会感到迷茫,不知道该如何选择最适合自己的购买途径。本文将详细解析阿里云服务器的四种主流购买方式的适用场景及购买流程,以供大家了解他们之间的区别及选择参考。
540 58
|
存储 弹性计算 网络协议
如何自定义购买阿里云服务器ECS?详细参考步骤,答疑解惑
阿里云ECS(弹性计算服务)支持用户根据需求自定义配置服务器,包括实例规格、存储、带宽、镜像类型及安全组等。购买前需完成实名认证并确保账户余额充足。操作流程涵盖选择付费模式(包年包月/按量付费)、地域、镜像、网络设置、登录凭证及高级选项等。创建实例约需3-5分钟,建议慎重选择不可更改的配置(如地域),并注意安全性与带宽计费策略。详细步骤可参考官方文档。
|
存储 监控 API
【Azure App Service】分享使用Python Code获取App Service的服务器日志记录管理配置信息
本文介绍了如何通过Python代码获取App Service中“Web服务器日志记录”的配置状态。借助`azure-mgmt-web` SDK,可通过初始化`WebSiteManagementClient`对象、调用`get_configuration`方法来查看`http_logging_enabled`的值,从而判断日志记录是否启用及存储方式(关闭、存储或文件系统)。示例代码详细展示了实现步骤,并附有执行结果与官方文档参考链接,帮助开发者快速定位和解决问题。
506 22
|
存储 弹性计算 Linux
阿里云服务器购买流程参考:快速、自定义、活动三种购买方式详解与流程指南
对于初次接触阿里云服务器的用户来说,选择合适的购买方式并了解详细的购买流程至关重要,阿里云提供了快速购买、自定义购买和活动购买等多种购买方式,以满足不同用户的需求。本文将为大家展示阿里云服务器的三种主要购买方式:快速购买、自定义购买以及通过活动购买,以供大家了解具体的流程,帮助用户轻松上手,快速搭建高效、稳定的云端环境。
750 10
|
存储 弹性计算 安全
阿里云服务器四种购买方式解析:自定义、快速、活动、云市场镜像选购流程参考
阿里云服务器主要的购买方式有自定义购买、快速购买、通过活动购买、通过云市场镜像页面购买这四种购买方式。然而,面对阿里云服务器多样化的购买方式和配置选项,有些新手用户并不清楚他们的区别及具体流程,因此可能不知道哪种方式更适合自己。本文将详细解析阿里云服务器的四种主流购买方式的适用场景及购买流程,帮助用户轻松选择最适合自己的购买途径。

热门文章

最新文章