github.com/cloudwego/hertz@v0.9.3/pkg/common/config/option.go (about)

     1  /*
     2   * Copyright 2022 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package config
    18  
    19  import (
    20  	"context"
    21  	"crypto/tls"
    22  	"net"
    23  	"time"
    24  
    25  	"github.com/cloudwego/hertz/pkg/app/server/registry"
    26  	"github.com/cloudwego/hertz/pkg/network"
    27  )
    28  
    29  // Option is the only struct that can be used to set Options.
    30  type Option struct {
    31  	F func(o *Options)
    32  }
    33  
    34  const (
    35  	defaultKeepAliveTimeout   = 1 * time.Minute
    36  	defaultReadTimeout        = 3 * time.Minute
    37  	defaultAddr               = ":8888"
    38  	defaultNetwork            = "tcp"
    39  	defaultBasePath           = "/"
    40  	defaultMaxRequestBodySize = 4 * 1024 * 1024
    41  	defaultWaitExitTimeout    = time.Second * 5
    42  	defaultReadBufferSize     = 4 * 1024
    43  )
    44  
    45  type Options struct {
    46  	KeepAliveTimeout             time.Duration
    47  	ReadTimeout                  time.Duration
    48  	WriteTimeout                 time.Duration
    49  	IdleTimeout                  time.Duration
    50  	RedirectTrailingSlash        bool
    51  	MaxRequestBodySize           int
    52  	MaxKeepBodySize              int
    53  	GetOnly                      bool
    54  	DisableKeepalive             bool
    55  	RedirectFixedPath            bool
    56  	HandleMethodNotAllowed       bool
    57  	UseRawPath                   bool
    58  	RemoveExtraSlash             bool
    59  	UnescapePathValues           bool
    60  	DisablePreParseMultipartForm bool
    61  	NoDefaultDate                bool
    62  	NoDefaultContentType         bool
    63  	StreamRequestBody            bool
    64  	NoDefaultServerHeader        bool
    65  	DisablePrintRoute            bool
    66  	SenseClientDisconnection     bool
    67  	Network                      string
    68  	Addr                         string
    69  	BasePath                     string
    70  	ExitWaitTimeout              time.Duration
    71  	TLS                          *tls.Config
    72  	H2C                          bool
    73  	ReadBufferSize               int
    74  	ALPN                         bool
    75  	Tracers                      []interface{}
    76  	TraceLevel                   interface{}
    77  	ListenConfig                 *net.ListenConfig
    78  	BindConfig                   interface{}
    79  	ValidateConfig               interface{}
    80  	CustomBinder                 interface{}
    81  	CustomValidator              interface{}
    82  
    83  	// TransporterNewer is the function to create a transporter.
    84  	TransporterNewer    func(opt *Options) network.Transporter
    85  	AltTransporterNewer func(opt *Options) network.Transporter
    86  
    87  	// In netpoll library, OnAccept is called after connection accepted
    88  	// but before adding it to epoll. OnConnect is called after adding it to epoll.
    89  	// The difference is that onConnect can get data but OnAccept cannot.
    90  	// If you'd like to check whether the peer IP is in the blacklist, you can use OnAccept.
    91  	// In go net, OnAccept is executed after connection accepted but before establishing
    92  	// tls connection. OnConnect is executed after establishing tls connection.
    93  	OnAccept  func(conn net.Conn) context.Context
    94  	OnConnect func(ctx context.Context, conn network.Conn) context.Context
    95  
    96  	// Registry is used for service registry.
    97  	Registry registry.Registry
    98  	// RegistryInfo is base info used for service registry.
    99  	RegistryInfo *registry.Info
   100  	// Enable automatically HTML template reloading mechanism.
   101  
   102  	AutoReloadRender bool
   103  	// If AutoReloadInterval is set to 0(default).
   104  	// The HTML template will reload according to files' changing event
   105  	// otherwise it will reload after AutoReloadInterval.
   106  	AutoReloadInterval time.Duration
   107  
   108  	// Header names are passed as-is without normalization
   109  	// if this option is set.
   110  	//
   111  	// Disabled header names' normalization may be useful only for proxying
   112  	// responses to other clients expecting case-sensitive header names.
   113  	//
   114  	// By default, request and response header names are normalized, i.e.
   115  	// The first letter and the first letters following dashes
   116  	// are uppercased, while all the other letters are lowercased.
   117  	// Examples:
   118  	//
   119  	//     * HOST -> Host
   120  	//     * content-type -> Content-Type
   121  	//     * cONTENT-lenGTH -> Content-Length
   122  	DisableHeaderNamesNormalizing bool
   123  }
   124  
   125  func (o *Options) Apply(opts []Option) {
   126  	for _, op := range opts {
   127  		op.F(o)
   128  	}
   129  }
   130  
   131  func NewOptions(opts []Option) *Options {
   132  	options := &Options{
   133  		// Keep-alive timeout. When idle connection exceeds this time,
   134  		// server will send keep-alive packets to ensure it's a validated
   135  		// connection.
   136  		//
   137  		// NOTE: Usually there is no need to care about this value, just
   138  		// care about IdleTimeout.
   139  		KeepAliveTimeout: defaultKeepAliveTimeout,
   140  
   141  		// the timeout of reading from low-level library
   142  		ReadTimeout: defaultReadTimeout,
   143  
   144  		// When there is no request during the idleTimeout, the connection
   145  		// will be closed by server.
   146  		// Default to ReadTimeout. Zero means no timeout.
   147  		IdleTimeout: defaultReadTimeout,
   148  
   149  		// Enables automatic redirection if the current route can't be matched but a
   150  		// handler for the path with (without) the trailing slash exists.
   151  		// For example if /foo/ is requested but a route only exists for /foo, the
   152  		// client is redirected to /foo with http status code 301 for GET requests
   153  		// and 308 for all other request methods.
   154  		RedirectTrailingSlash: true,
   155  
   156  		// If enabled, the router tries to fix the current request path, if no
   157  		// handle is registered for it.
   158  		// First superfluous path elements like ../ or // are removed.
   159  		// Afterwards the router does a case-insensitive lookup of the cleaned path.
   160  		// If a handle can be found for this route, the router makes a redirection
   161  		// to the corrected path with status code 301 for GET requests and 308 for
   162  		// all other request methods.
   163  		// For example /FOO and /..//Foo could be redirected to /foo.
   164  		// RedirectTrailingSlash is independent of this option.
   165  		RedirectFixedPath: false,
   166  
   167  		// If enabled, the router checks if another method is allowed for the
   168  		// current route, if the current request can not be routed.
   169  		// If this is the case, the request is answered with 'Method Not Allowed'
   170  		// and HTTP status code 405.
   171  		// If no other Method is allowed, the request is delegated to the NotFound
   172  		// handler.
   173  		HandleMethodNotAllowed: false,
   174  
   175  		// If enabled, the url.RawPath will be used to find parameters.
   176  		UseRawPath: false,
   177  
   178  		// RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes.
   179  		RemoveExtraSlash: false,
   180  
   181  		// If true, the path value will be unescaped.
   182  		// If UseRawPath is false (by default), the UnescapePathValues effectively is true,
   183  		// as url.Path gonna be used, which is already unescaped.
   184  		UnescapePathValues: true,
   185  
   186  		// ContinueHandler is called after receiving the Expect 100 Continue Header
   187  		//
   188  		// https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3
   189  		// https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1
   190  		// Using ContinueHandler a server can make decisioning on whether or not
   191  		// to read a potentially large request body based on the headers
   192  		//
   193  		// The default is to automatically read request bodies of Expect 100 Continue requests
   194  		// like they are normal requests
   195  		DisablePreParseMultipartForm: false,
   196  
   197  		// When set to true, causes the default Content-Type header to be excluded from the response.
   198  		NoDefaultContentType: false,
   199  
   200  		// When set to true, causes the default date header to be excluded from the response.
   201  		NoDefaultDate: false,
   202  
   203  		// Routes info printing is not disabled by default
   204  		// Disabled when set to True
   205  		DisablePrintRoute: false,
   206  
   207  		// The ability to sense client disconnection is disabled by default
   208  		SenseClientDisconnection: false,
   209  
   210  		// "tcp", "udp", "unix"(unix domain socket)
   211  		Network: defaultNetwork,
   212  
   213  		// listen address
   214  		Addr: defaultAddr,
   215  
   216  		// basePath
   217  		BasePath: defaultBasePath,
   218  
   219  		// Define the max request body size. If the body Size exceeds this value,
   220  		// an error will be returned
   221  		MaxRequestBodySize: defaultMaxRequestBodySize,
   222  
   223  		// max reserved body buffer size when reset Request & Response
   224  		// If the body size exceeds this value, then the buffer will be put to
   225  		// sync.Pool instead of hold by Request/Response directly.
   226  		MaxKeepBodySize: defaultMaxRequestBodySize,
   227  
   228  		// only accept GET request
   229  		GetOnly: false,
   230  
   231  		DisableKeepalive: false,
   232  
   233  		// request body stream switch
   234  		StreamRequestBody: false,
   235  
   236  		NoDefaultServerHeader: false,
   237  
   238  		// graceful shutdown wait time
   239  		ExitWaitTimeout: defaultWaitExitTimeout,
   240  
   241  		// tls config
   242  		TLS: nil,
   243  
   244  		// Set init read buffer size. Usually there is no need to set it.
   245  		ReadBufferSize: defaultReadBufferSize,
   246  
   247  		// ALPN switch
   248  		ALPN: false,
   249  
   250  		// H2C switch
   251  		H2C: false,
   252  
   253  		// tracers
   254  		Tracers: []interface{}{},
   255  
   256  		// trace level, default LevelDetailed
   257  		TraceLevel: new(interface{}),
   258  
   259  		Registry: registry.NoopRegistry,
   260  
   261  		// Disabled header names' normalization, default false
   262  		DisableHeaderNamesNormalizing: false,
   263  	}
   264  	options.Apply(opts)
   265  	return options
   266  }