From 489aca4fddc07a9315d01d44bed6abc45850a551 Mon Sep 17 00:00:00 2001 From: yangsijie Date: Thu, 1 Aug 2019 21:16:17 +0800 Subject: [PATCH] Update comments --- bfe_balance/backend/health_check.go | 2 +- bfe_balance/bal_table.go | 15 +- bfe_basic/action/action.go | 2 +- bfe_basic/action/action_query.go | 2 +- bfe_basic/common.go | 2 +- bfe_basic/condition/parser/walk.go | 2 +- bfe_basic/request.go | 3 +- .../cluster_conf/cluster_conf_load.go | 10 +- .../route_rule_conf/route_table_load.go | 2 +- .../session_ticket_key_conf.go | 2 +- bfe_http/cookie.go | 2 +- bfe_http/eof_reader.go | 2 +- bfe_http/header.go | 5 +- bfe_http/httputil/persist.go | 5 +- bfe_http/status.go | 2 +- bfe_http2/frame_test.go | 3 +- bfe_http2/http2.go | 6 +- bfe_http2/server.go | 3 +- bfe_module/bfe_filter.go | 10 +- bfe_module/bfe_handler_list.go | 4 +- .../mod_trust_clientip/trustip_conf_load.go | 6 +- bfe_net/textproto/header.go | 4 +- bfe_route/host_table.go | 2 +- bfe_server/bfe_confdata_load.go | 2 +- bfe_server/find_location.go | 2 +- bfe_server/monitor_stat.go | 6 +- bfe_server/register_modules.go | 2 +- bfe_server/response.go | 3 +- bfe_spdy/flow.go | 3 +- bfe_spdy/frame_types.go | 10 +- bfe_spdy/request_body.go | 2 +- bfe_spdy/response_writer.go | 3 +- bfe_spdy/server_conn.go | 2 +- bfe_spdy/server_process_frame.go | 3 +- bfe_spdy/spdy.go | 4 +- bfe_tls/cipher_suites.go | 2 +- bfe_tls/common.go | 4 +- bfe_tls/key_agreement.go | 1 - bfe_util/bns/bns_local.go | 2 +- bfe_util/byte_pool/byte_pool.go | 48 +++---- bfe_util/byte_pool/fixed_byte_pool.go | 48 +++---- bfe_util/hash_set/hash_set.go | 78 +++++------ bfe_util/ipdict/ip_loc_table.go | 36 ++--- bfe_util/ipdict/ipdict.go | 130 +++++++++--------- bfe_util/ipdict/ipdict_test.go | 25 ++-- bfe_util/ipdict/iptable.go | 4 +- bfe_util/net_util/ip.go | 126 ++++++++--------- bfe_util/signal_table/signal_handlers.go | 4 +- bfe_util/signal_table/signal_table.go | 16 +-- bfe_websocket/common.go | 5 +- bfe_websocket/server_tester.go | 12 +- 51 files changed, 314 insertions(+), 365 deletions(-) diff --git a/bfe_balance/backend/health_check.go b/bfe_balance/backend/health_check.go index 0b384f524..29705e005 100644 --- a/bfe_balance/backend/health_check.go +++ b/bfe_balance/backend/health_check.go @@ -180,7 +180,7 @@ func checkHTTPConnect(backend *BfeBackend, checkConf *cluster_conf.BackendCheck) return cluster_conf.MatchStatusCode(statusCode, *checkConf.StatusCode) } -// CheckRedirect check whether backend server become available. +// CheckConnect checks whether backend server become available. func CheckConnect(backend *BfeBackend, checkConf *cluster_conf.BackendCheck) (bool, error) { switch *checkConf.Schem { case "http": diff --git a/bfe_balance/bal_table.go b/bfe_balance/bal_table.go index 2b2c46043..56322e063 100644 --- a/bfe_balance/bal_table.go +++ b/bfe_balance/bal_table.go @@ -125,12 +125,11 @@ func (t *BalTable) gslbInit(gslbConfs gslb_conf.GslbConf) error { t.versions.GslbConfTimeStamp = *gslbConfs.Ts t.versions.GslbConfSrc = *gslbConfs.Hostname - if len(fails) == 0 { - return nil - } else { + if len(fails) != 0 { return fmt.Errorf("error in ClusterTable.gslbInit() for [%s]", strings.Join(fails, ",")) } + return nil } func (t *BalTable) backendInit(backendConfs cluster_table_conf.ClusterTableConf) error { @@ -159,12 +158,11 @@ func (t *BalTable) backendInit(backendConfs cluster_table_conf.ClusterTableConf) // update versions t.versions.ClusterTableConfVer = *backendConfs.Version - if len(fails) == 0 { - return nil - } else { + if len(fails) != 0 { return fmt.Errorf("error in ClusterTable.backendInit() for [%s]", strings.Join(fails, ",")) } + return nil } // SetGslbBasic sets gslb basic conf (from server data conf) for BalTable. @@ -244,11 +242,10 @@ func (t *BalTable) BalTableReload(gslbConfs gslb_conf.GslbConf, t.lock.Unlock() - if len(fails) == 0 { - return nil - } else { + if len(fails) != 0 { return fmt.Errorf("error in BalTableReload() for [%s]", strings.Join(fails, ",")) } + return nil } func (t *BalTable) lookup(clusterName string) (*bal_gslb.BalanceGslb, error) { diff --git a/bfe_basic/action/action.go b/bfe_basic/action/action.go index 90d8b57e4..0ecaa1388 100644 --- a/bfe_basic/action/action.go +++ b/bfe_basic/action/action.go @@ -62,7 +62,7 @@ type Action struct { Params []string // params of action } -// UnmarshalJson decodes given data in json format +// UnmarshalJSON decodes given data in json format func (ac *Action) UnmarshalJSON(data []byte) error { var actionFile ActionFile diff --git a/bfe_basic/action/action_query.go b/bfe_basic/action/action_query.go index efb6fd5ee..e1279ca36 100644 --- a/bfe_basic/action/action_query.go +++ b/bfe_basic/action/action_query.go @@ -115,7 +115,7 @@ func ReqQueryRename(req *bfe_basic.Request, oldName string, newName string) { req.HttpRequest.URL.RawQuery = rawQuery[1:] } -// ReqQueryRename deletes some keys from query +// ReqQueryDel deletes some keys from query func ReqQueryDel(req *bfe_basic.Request, keys []string) { // add "&" prefix and suffix to simplify process rawQuery := "&" + req.HttpRequest.URL.RawQuery + "&" diff --git a/bfe_basic/common.go b/bfe_basic/common.go index 0cba24c58..c49e9e31d 100644 --- a/bfe_basic/common.go +++ b/bfe_basic/common.go @@ -47,7 +47,7 @@ func CreateInternalSrvErrResp(request *Request) *bfe_http.Response { return CreateInternalResp(request, bfe_http.StatusInternalServerError) } -// CreateInternalSrvErrResp returns a HTTP 403 response +// CreateForbiddenResp returns a HTTP 403 response func CreateForbiddenResp(request *Request) *bfe_http.Response { return CreateInternalResp(request, bfe_http.StatusForbidden) } diff --git a/bfe_basic/condition/parser/walk.go b/bfe_basic/condition/parser/walk.go index ae2c61da1..ad5f7d35d 100644 --- a/bfe_basic/condition/parser/walk.go +++ b/bfe_basic/condition/parser/walk.go @@ -16,7 +16,7 @@ package parser -// A Visitor's Visit method is invoked for each node encountered by Walk. +// Visitor wraps the Visit method which is invoked for each node encountered by Walk. // If the result visitor w is not nil, Walk visits each of the children // of node with the visitor w, followed by a call of w.Visit(nil). type Visitor interface { diff --git a/bfe_basic/request.go b/bfe_basic/request.go index e79f9ee84..51f031feb 100644 --- a/bfe_basic/request.go +++ b/bfe_basic/request.go @@ -156,9 +156,8 @@ func (req *Request) SetRequestTransport(backend *backend.BfeBackend, func (req *Request) Protocol() string { if req.Session.IsSecure { return req.Session.Proto - } else { - return req.HttpRequest.Proto } + return req.HttpRequest.Proto } func (r *Request) AddTags(name string, ntags []string) { diff --git a/bfe_config/bfe_cluster_conf/cluster_conf/cluster_conf_load.go b/bfe_config/bfe_cluster_conf/cluster_conf/cluster_conf_load.go index 7580bbaf5..979509eca 100644 --- a/bfe_config/bfe_cluster_conf/cluster_conf/cluster_conf_load.go +++ b/bfe_config/bfe_cluster_conf/cluster_conf/cluster_conf_load.go @@ -90,7 +90,7 @@ type HashConf struct { SessionSticky *bool } -// Cluster conf for Gslb +// GslbBasicConf is basic conf for Gslb type GslbBasicConf struct { CrossRetry *int // retry cross sub clusters RetryMax *int // inner cluster retry @@ -111,7 +111,7 @@ type ClusterBasicConf struct { CancelOnClientClose *bool // cancel blocking operation on server if client connection disconnected } -// ClusterBasicConf is conf of cluster. +// ClusterConf is conf of cluster. type ClusterConf struct { BackendConf *BackendBasic // backend's basic conf CheckConf *BackendCheck // how to check backend @@ -222,7 +222,7 @@ func MatchStatusCode(statusCodeGet int, statusCodeExpect int) (bool, error) { statusCodeGet, convertStatusCode(statusCodeExpect)) } -// BackendBasicCheck check BackendCheck config. +// BackendCheckCheck check BackendCheck config. func BackendCheckCheck(conf *BackendCheck) error { if conf.Schem == nil { // set default schem to http @@ -337,7 +337,7 @@ func HashConfCheck(conf *HashConf) error { return nil } -// ClusterToConf check ClusterBasicConf. +// ClusterBasicConfCheck check ClusterBasicConf. func ClusterBasicConfCheck(conf *ClusterBasicConf) error { if conf.TimeoutReadClientAgain == nil || conf.TimeoutReadClient == nil || @@ -365,7 +365,7 @@ func ClusterBasicConfCheck(conf *ClusterBasicConf) error { return nil } -// ClusterBasicConfCheck check ClusterConf. +// ClusterConfCheck check ClusterConf. func ClusterConfCheck(conf *ClusterConf) error { var err error diff --git a/bfe_config/bfe_route_conf/route_rule_conf/route_table_load.go b/bfe_config/bfe_route_conf/route_rule_conf/route_table_load.go index 790394f9c..ce7dc5fe9 100644 --- a/bfe_config/bfe_route_conf/route_rule_conf/route_table_load.go +++ b/bfe_config/bfe_route_conf/route_rule_conf/route_table_load.go @@ -42,7 +42,7 @@ type RouteRuleFile struct { type RouteRules []RouteRule type RouteRuleFiles []RouteRuleFile -// ProductRule holds mapping from product to rules. +// ProductRouteRule holds mapping from product to rules. type ProductRouteRule map[string]RouteRules type ProductRouteRuleFile map[string]RouteRuleFiles diff --git a/bfe_config/bfe_tls_conf/session_ticket_key_conf/session_ticket_key_conf.go b/bfe_config/bfe_tls_conf/session_ticket_key_conf/session_ticket_key_conf.go index 9dae3f667..adb23c136 100644 --- a/bfe_config/bfe_tls_conf/session_ticket_key_conf/session_ticket_key_conf.go +++ b/bfe_config/bfe_tls_conf/session_ticket_key_conf/session_ticket_key_conf.go @@ -31,7 +31,7 @@ const ( RAW_SESSION_TICKET_KEY_SIZE = 48 // bytes ) -// config for session ticket key +// SessionTicketKeyConf is session ticket key config. type SessionTicketKeyConf struct { Version string // version of config SessionTicketKey string // session ticket key (hex encode) diff --git a/bfe_http/cookie.go b/bfe_http/cookie.go index 486d7f9af..221214fc4 100644 --- a/bfe_http/cookie.go +++ b/bfe_http/cookie.go @@ -57,7 +57,7 @@ type Cookie struct { type CookieMap map[string]*Cookie -// parse cookies(slice) to req.Route.CookieMap(map) +// CookieMapGet parse cookies(slice) to req.Route.CookieMap(map) func CookieMapGet(cookies []*Cookie) CookieMap { cookieMap := make(CookieMap, len(cookies)) diff --git a/bfe_http/eof_reader.go b/bfe_http/eof_reader.go index 88dbc1cf9..13118da61 100644 --- a/bfe_http/eof_reader.go +++ b/bfe_http/eof_reader.go @@ -24,7 +24,7 @@ import ( "strings" ) -// eofReader is a non-nil io.ReadCloser that always returns EOF. +// EofReader is a non-nil io.ReadCloser that always returns EOF. // It embeds a *strings.Reader so it still has a WriteTo method // and io.Copy won't need a buffer. var EofReader = &struct { diff --git a/bfe_http/header.go b/bfe_http/header.go index f454d9448..5588837fd 100644 --- a/bfe_http/header.go +++ b/bfe_http/header.go @@ -59,7 +59,8 @@ func (h Header) Get(key string) string { return textproto.MIMEHeader(h).Get(key) } -// get is like Get, but key must already be in CanonicalHeaderKey form. +// GetDirect gets the value associated with the given key +// in CanonicalHeaderKey form. func (h Header) GetDirect(key string) string { if v := h[key]; len(v) > 0 { return v[0] @@ -233,7 +234,7 @@ func (h Header) writeSubsetWithoutSort(w io.Writer, exclude map[string]bool) err // canonical key for "accept-encoding" is "Accept-Encoding". func CanonicalHeaderKey(s string) string { return textproto.CanonicalMIMEHeaderKey(s) } -// hasToken reports whether token appears with v, ASCII +// HasToken reports whether token appears with v, ASCII // case-insensitive, with space or comma boundaries. // token must be all lowercase. // v may contain mixed cased. diff --git a/bfe_http/httputil/persist.go b/bfe_http/httputil/persist.go index 42c98691f..f6a3a9688 100644 --- a/bfe_http/httputil/persist.go +++ b/bfe_http/httputil/persist.go @@ -163,10 +163,9 @@ func (sc *ServerConn) Read() (req *http.Request, err error) { // data before the close. sc.re = ErrPersistEOF return nil, sc.re - } else { - sc.re = err - return req, err } + sc.re = err + return req, err } sc.lastbody = req.Body sc.nread++ diff --git a/bfe_http/status.go b/bfe_http/status.go index abfda077f..0d57c1235 100644 --- a/bfe_http/status.go +++ b/bfe_http/status.go @@ -127,7 +127,7 @@ var StatusText = map[int]string{ statusNetworkAuthenticationRequired: "Network Authentication Required", } -// StatusText returns a text for the HTTP status code. It returns the empty +// StatusTextGet returns a text for the HTTP status code. It returns the empty // string if the code is unknown. func StatusTextGet(code int) string { return StatusText[code] diff --git a/bfe_http2/frame_test.go b/bfe_http2/frame_test.go index 07bd662ec..a7d024fe7 100644 --- a/bfe_http2/frame_test.go +++ b/bfe_http2/frame_test.go @@ -1030,9 +1030,8 @@ func TestMetaFrameHeader(t *testing.T) { str := func(v interface{}) string { if _, ok := v.(error); ok { return fmt.Sprintf("error %v", v) - } else { - return fmt.Sprintf("value %#v", v) } + return fmt.Sprintf("value %#v", v) } t.Errorf("%s:\n got: %v\nwant: %s", name, str(got), str(tt.want)) } diff --git a/bfe_http2/http2.go b/bfe_http2/http2.go index 021899fca..cdd22502a 100644 --- a/bfe_http2/http2.go +++ b/bfe_http2/http2.go @@ -279,7 +279,7 @@ func httpCodeString(code int) string { return strconv.Itoa(code) } -// connection-specific header fields which should be removed +// HopHeaders are connection-specific header fields which should be removed // when endpoint generates an http/2 message var HopHeaders = map[string]bool{ "Connection": true, @@ -522,7 +522,7 @@ func strSliceContains(ss []string, s string) bool { return false } -// close underlying connection for request +// CloseConn closes underlying connection for request func CloseConn(body io.ReadCloser) { if b, ok := body.(*RequestBody); ok { if b.conn != nil { @@ -533,7 +533,7 @@ func CloseConn(body io.ReadCloser) { var http2Limiter http.FlowLimiter -// init flow limiter for http2 +// SetFlowLimiter init flow limiter for http2 func SetFlowLimiter(limiter http.FlowLimiter) { http2Limiter = limiter } diff --git a/bfe_http2/server.go b/bfe_http2/server.go index 9c326f7f6..6ccec3b33 100644 --- a/bfe_http2/server.go +++ b/bfe_http2/server.go @@ -2501,9 +2501,8 @@ func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, if dataB != nil { return rws.bw.Write(dataB) - } else { - return rws.bw.WriteString(dataS) } + return rws.bw.WriteString(dataS) } func (w *responseWriter) handlerDone() { diff --git a/bfe_module/bfe_filter.go b/bfe_module/bfe_filter.go index 53ffbce24..f2e7a6400 100644 --- a/bfe_module/bfe_filter.go +++ b/bfe_module/bfe_filter.go @@ -48,13 +48,13 @@ import ( "github.com/baidu/bfe/bfe_http" ) -// ResponseFilter filters incomming requests and return a response or nil. +// RequestFilter filters incomming requests and return a response or nil. // Filters are chained together into a HandlerList. type RequestFilter interface { FilterRequest(request *bfe_basic.Request) (int, *bfe_http.Response) } -// NewResponseFilter create a Filter by passed func. +// NewRequestFilter create a Filter by passed func. func NewRequestFilter(f func(request *bfe_basic.Request) (int, *bfe_http.Response)) RequestFilter { rf := new(genericRequestFilter) rf.f = f @@ -75,7 +75,7 @@ type ResponseFilter interface { FilterResponse(req *bfe_basic.Request, res *bfe_http.Response) int } -// NewRequestFilter creates a Filter by passed func +// NewResponseFilter creates a Filter by passed func func NewResponseFilter(f func(req *bfe_basic.Request, res *bfe_http.Response) int) ResponseFilter { rf := new(genericResponseFilter) rf.f = f @@ -95,7 +95,7 @@ type AcceptFilter interface { FilterAccept(*bfe_basic.Session) int } -// NewResponseFilter creates a Filter by passed func +// NewAcceptFilter creates a Filter by passed func func NewAcceptFilter(f func(session *bfe_basic.Session) int) AcceptFilter { rf := new(genericAcceptFilter) rf.f = f @@ -115,7 +115,7 @@ type ForwardFilter interface { FilterForward(*bfe_basic.Request) int } -// NewFinishFilter create a Filter by passed func +// NewForwardFilter create a Filter by passed func func NewForwardFilter(f func(req *bfe_basic.Request) int) ForwardFilter { rf := new(genericForwardFilter) rf.f = f diff --git a/bfe_module/bfe_handler_list.go b/bfe_module/bfe_handler_list.go index 8a66a845e..97a65be04 100644 --- a/bfe_module/bfe_handler_list.go +++ b/bfe_module/bfe_handler_list.go @@ -53,7 +53,7 @@ type HandlerList struct { handlers *list.List /* list of handlers */ } -// NewFinishFilter creates a HandlerList. +// NewHandlerList creates a HandlerList. func NewHandlerList(h_type int) *HandlerList { handlers := new(HandlerList) @@ -63,7 +63,7 @@ func NewHandlerList(h_type int) *HandlerList { return handlers } -// FinishFilter filters accept with HandlerList. +// FilterAccept filters accept with HandlerList. func (hl *HandlerList) FilterAccept(session *bfe_basic.Session) int { retVal := BFE_HANDLER_GOON diff --git a/bfe_modules/mod_trust_clientip/trustip_conf_load.go b/bfe_modules/mod_trust_clientip/trustip_conf_load.go index af29f00c5..76442c082 100644 --- a/bfe_modules/mod_trust_clientip/trustip_conf_load.go +++ b/bfe_modules/mod_trust_clientip/trustip_conf_load.go @@ -85,18 +85,18 @@ func TrustIPConfCheck(conf *TrustIPConfFile) error { return nil } -// load config of trust-ip from file +// TrustIPConfLoad loads config of trust-ip from file func TrustIPConfLoad(filename string) (TrustIPConf, error) { var conf TrustIPConf - /* open the file */ + // open the file file, err1 := os.Open(filename) if err1 != nil { return conf, err1 } - /* decode the file */ + // decode the file decoder := json.NewDecoder(file) config := TrustIPConfFile{} diff --git a/bfe_net/textproto/header.go b/bfe_net/textproto/header.go index 591f3197b..ddc7fb57d 100644 --- a/bfe_net/textproto/header.go +++ b/bfe_net/textproto/header.go @@ -18,11 +18,11 @@ package textproto -// A MIMEHeader represents a MIME-style header mapping +// MIMEHeader represents a MIME-style header mapping // keys to sets of values. type MIMEHeader map[string][]string -// A MIMEKyes represents keys of header in original order +// MIMEKyes represents keys of header in original order type MIMEKeys []string // Add adds the key, value pair to the header. diff --git a/bfe_route/host_table.go b/bfe_route/host_table.go index 1c174e236..3183b8605 100644 --- a/bfe_route/host_table.go +++ b/bfe_route/host_table.go @@ -93,7 +93,7 @@ func (t *HostTable) updateRouteTable(conf *route_rule_conf.RouteTableConf) { t.productRouteTable = conf.RuleMap } -// update all +// Update updates host table func (t *HostTable) Update(hostConf host_rule_conf.HostConf, vipConf vip_rule_conf.VipConf, routeConf *route_rule_conf.RouteTableConf) { diff --git a/bfe_server/bfe_confdata_load.go b/bfe_server/bfe_confdata_load.go index 091749be4..eff3858f2 100644 --- a/bfe_server/bfe_confdata_load.go +++ b/bfe_server/bfe_confdata_load.go @@ -258,7 +258,7 @@ func (srv *BfeServer) enableTLSNextProto(proto string) { } } -// NameConfLoad reloads name conf data. +// NameConfReload reloads name conf data. func (srv *BfeServer) NameConfReload(query url.Values) error { nameConfFile := query.Get("path") if nameConfFile == "" { diff --git a/bfe_server/find_location.go b/bfe_server/find_location.go index 9850ad159..45e642965 100644 --- a/bfe_server/find_location.go +++ b/bfe_server/find_location.go @@ -75,7 +75,7 @@ func (srv *BfeServer) FindLocation(request *bfe_basic.Request) (string, error) { return clusterName, nil } -// FindProEnd finds product for proxied conn (under tls proxy mode). +// FindProduct finds product for proxied conn (under tls proxy mode). func (srv *BfeServer) FindProduct(conn net.Conn) string { sc := srv.GetServerConf() diff --git a/bfe_server/monitor_stat.go b/bfe_server/monitor_stat.go index ab9a41e77..eb3f4b497 100644 --- a/bfe_server/monitor_stat.go +++ b/bfe_server/monitor_stat.go @@ -26,7 +26,7 @@ import ( "github.com/baidu/go-lib/web-monitor/kv_encode" ) -// HostTable returns status of HostTable in json. +// HostTableStatusGet returns status of HostTable in json. func (srv *BfeServer) HostTableStatusGet(query url.Values) ([]byte, error) { srv.confLock.RLock() serverConf := srv.ServerConf @@ -114,7 +114,7 @@ func (srv *BfeServer) ClusterTableVersionGet(query url.Values) ([]byte, error) { return buff, err } -// BalTableVersionGet returns state of balTable. +// BalTableStatusGet returns state of balTable. func (srv *BfeServer) BalTableStatusGet(query url.Values) ([]byte, error) { var buff []byte var err error @@ -141,7 +141,7 @@ func (srv *BfeServer) BalTableStatusGet(query url.Values) ([]byte, error) { return buff, err } -// BalTableStatusGet returns versions of balTable. +// BalTableVersionGet returns versions of balTable. func (srv *BfeServer) BalTableVersionGet(query url.Values) ([]byte, error) { // get versions output := srv.balTable.GetVersions() diff --git a/bfe_server/register_modules.go b/bfe_server/register_modules.go index ade28a037..a8fe450d6 100644 --- a/bfe_server/register_modules.go +++ b/bfe_server/register_modules.go @@ -24,7 +24,7 @@ import ( "github.com/baidu/go-lib/log" ) -// RegisterModule registers bfe work module. +// RegisterModules registers bfe work module. func (srv *BfeServer) RegisterModules(modules []string) error { if modules == nil { return nil diff --git a/bfe_server/response.go b/bfe_server/response.go index 19e83427a..ea1a96a46 100644 --- a/bfe_server/response.go +++ b/bfe_server/response.go @@ -323,9 +323,8 @@ func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err er } if dataB != nil { return w.w.Write(dataB) - } else { - return w.w.WriteString(dataS) } + return w.w.WriteString(dataS) } func (w *response) finishRequest() { diff --git a/bfe_spdy/flow.go b/bfe_spdy/flow.go index d3ee00722..f1670df60 100644 --- a/bfe_spdy/flow.go +++ b/bfe_spdy/flow.go @@ -70,7 +70,6 @@ func (f *flow) add(n int32) bool { func (f *flow) String() string { if f.conn != nil { return fmt.Sprintf("flow(stream:%d, conn:%d)", f.n, f.conn.n) - } else { - return fmt.Sprintf("flow(conn:%d)", f.n) } + return fmt.Sprintf("flow(conn:%d)", f.n) } diff --git a/bfe_spdy/frame_types.go b/bfe_spdy/frame_types.go index 23ce215af..70ddd4e21 100644 --- a/bfe_spdy/frame_types.go +++ b/bfe_spdy/frame_types.go @@ -158,7 +158,7 @@ const ( FlagSettingsPersisted = 0x2 ) -// SettingsFlag represents the id of an id/value pair in a SETTINGS frame. +// SettingsId represents the id of an id/value pair in a SETTINGS frame. type SettingsId uint32 const ( @@ -243,16 +243,16 @@ func (f *DataFrame) String() string { f.StreamId, f.Flags, len(f.Data)) } -// Special frame for flush connection buffer +// FlushFrame is the special frame for flush connection buffer. type FlushFrame struct{} -// Special frame for finish connection +// FinFrame is the special frame for finish connection. type FinFrame struct{} -// Special frame for reset stream with panic +// PanicFrame is the special frame for reset stream with panic. type PanicFrame struct{} -// A SPDY specific error. +// ErrorCode represents SPDY specific error. type ErrorCode string const ( diff --git a/bfe_spdy/request_body.go b/bfe_spdy/request_body.go index a83ba29fc..0c21b0c0f 100644 --- a/bfe_spdy/request_body.go +++ b/bfe_spdy/request_body.go @@ -57,7 +57,7 @@ func (b *RequestBody) Close() error { return nil } -// check wheather without entity body +// Eof check wheather without entity body func (b *RequestBody) Eof() bool { return b.pipe == nil } diff --git a/bfe_spdy/response_writer.go b/bfe_spdy/response_writer.go index 3bafe0d9f..0affcd410 100644 --- a/bfe_spdy/response_writer.go +++ b/bfe_spdy/response_writer.go @@ -177,9 +177,8 @@ func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, } if dataB != nil { return rws.bw.Write(dataB) - } else { - return rws.bw.WriteString(dataS) } + return rws.bw.WriteString(dataS) } func (w *responseWriter) handlerDone() { diff --git a/bfe_spdy/server_conn.go b/bfe_spdy/server_conn.go index fa731b25f..e8ba6564c 100644 --- a/bfe_spdy/server_conn.go +++ b/bfe_spdy/server_conn.go @@ -100,7 +100,7 @@ func (s *Server) maxConcurrentStreams() uint32 { return defaultMaxStreams } -// TLS application level protocol handler for spdy +// NewProtoHandler creates TLS application level protocol handler for spdy func NewProtoHandler(conf *Server) func(*http.Server, *tls.Conn, http.Handler) { if conf == nil { conf = new(Server) diff --git a/bfe_spdy/server_process_frame.go b/bfe_spdy/server_process_frame.go index 22269aae6..92b9a6e6d 100644 --- a/bfe_spdy/server_process_frame.go +++ b/bfe_spdy/server_process_frame.go @@ -229,9 +229,8 @@ func (sc *serverConn) processData(f *DataFrame) error { st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes", st.declBodyBytes, st.bodyBytes)) return StreamError{id, ProtocolError} - } else { - st.body.CloseWithError(io.EOF) } + st.body.CloseWithError(io.EOF) st.state = stateHalfClosedRemote } return nil diff --git a/bfe_spdy/spdy.go b/bfe_spdy/spdy.go index 799a90d7a..15611b91a 100644 --- a/bfe_spdy/spdy.go +++ b/bfe_spdy/spdy.go @@ -246,7 +246,7 @@ func mustUint31(v int32) uint32 { return uint32(v) } -// close underlying connection for request +// CloseConn close underlying connection for request func CloseConn(body io.ReadCloser) { if b, ok := body.(*RequestBody); ok { if b.conn != nil { @@ -257,7 +257,7 @@ func CloseConn(body io.ReadCloser) { var spdyLimiter http.FlowLimiter -// init flow limiter for spdy +// SetFlowLimiter init flow limiter for spdy func SetFlowLimiter(limiter http.FlowLimiter) { spdyLimiter = limiter } diff --git a/bfe_tls/cipher_suites.go b/bfe_tls/cipher_suites.go index 9387dfd53..9b7fc64e3 100644 --- a/bfe_tls/cipher_suites.go +++ b/bfe_tls/cipher_suites.go @@ -115,7 +115,7 @@ var cipherSuites = []*cipherSuite{ {TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, rsaKA, 0, cipher3DES, macSHA1, nil}, } -// check whether cipher suite using RSA key argreement +// CheckSuiteRSA checks whether cipher suite using RSA key argreement func CheckSuiteRSA(id uint16) bool { switch id { case TLS_RSA_WITH_RC4_128_SHA: diff --git a/bfe_tls/common.go b/bfe_tls/common.go index e32d3c8ca..383bb97aa 100644 --- a/bfe_tls/common.go +++ b/bfe_tls/common.go @@ -283,7 +283,7 @@ type NextProtoConf interface { Get(c *Conn) []string } -// customized tls config for specific conn in server side +// Rule represents customized tls config for specific conn in server side type Rule struct { // NextProtos is a list of supported, application level protocols. NextProtos NextProtoConf @@ -843,7 +843,7 @@ func generateHelloRandom(rand io.Reader) ([]byte, error) { return random, nil } -// check ocsp time update range +// OcspTimeRangeCheck check ocsp time update range func OcspTimeRangeCheck(parse *ocsp.Response) bool { serverTime := time.Now() nextUpdate := parse.NextUpdate diff --git a/bfe_tls/key_agreement.go b/bfe_tls/key_agreement.go index a5aba3acb..59a65d366 100644 --- a/bfe_tls/key_agreement.go +++ b/bfe_tls/key_agreement.go @@ -197,7 +197,6 @@ func curveForCurveID(id CurveID) (elliptic.Curve, bool) { } -// for call from outside func CurveForCurveID(id CurveID) (elliptic.Curve, bool) { return curveForCurveID(id) } diff --git a/bfe_util/bns/bns_local.go b/bfe_util/bns/bns_local.go index ae2204d2d..78eb21577 100644 --- a/bfe_util/bns/bns_local.go +++ b/bfe_util/bns/bns_local.go @@ -31,7 +31,7 @@ type NameConf struct { var localNameConf LocalNameConf var localNameLock sync.RWMutex -// LocalNameConf loads name conf file +// LoadLocalNameConf loads name conf file func LoadLocalNameConf(filename string) error { // load local name conf nameConf, err := parseLocalNameConf(filename) diff --git a/bfe_util/byte_pool/byte_pool.go b/bfe_util/byte_pool/byte_pool.go index 1af8f629a..2c8773b13 100644 --- a/bfe_util/byte_pool/byte_pool.go +++ b/bfe_util/byte_pool/byte_pool.go @@ -23,16 +23,14 @@ type BytePool struct { maxElemNum int // max element num } -/* -* NewBytePool - create a new BytePool -* -* PARAMS: -* - elemNum: int, the max element num of BytePool -* - maxElemSize: int, the max length of each element -* -* RETURNS: -* - a pointer point to the BytePool - */ +// NewBytePool creates a new BytePool +// +// PARAMS: +// - elemNum: int, the max element num of BytePool +// - maxElemSize: int, the max length of each element +// +// RETURNS: +// - a pointer point to the BytePool func NewBytePool(elemNum int, maxElemSize int) *BytePool { pool := new(BytePool) pool.buf = make([]byte, elemNum*maxElemSize) @@ -43,13 +41,11 @@ func NewBytePool(elemNum int, maxElemSize int) *BytePool { return pool } -/* -* Set - set the index node of BytePool with key -* -* PARAMS: -* - index: index of the byte Pool -* - key: []byte key - */ +// Set sets the index node of BytePool with key +// +// PARAMS: +// - index: index of the byte Pool +// - key: []byte key func (pool *BytePool) Set(index int32, key []byte) error { if int(index) >= pool.maxElemNum { return fmt.Errorf("index out of range %d %d", index, pool.maxElemNum) @@ -67,15 +63,13 @@ func (pool *BytePool) Set(index int32, key []byte) error { return nil } -/* -* Get the byte slice -* -* PARAMS: -* - index: int, index of the BytePool -* -* RETURNS: -* - key: []byte type store in the BytePool - */ +// Get the byte slice +// +// PARAMS: +// - index: int, index of the BytePool +// +// RETURNS: +// - key: []byte type store in the BytePool func (pool *BytePool) Get(index int32) []byte { start := int(index) * pool.maxElemSize end := start + int(pool.length[index]) @@ -83,7 +77,7 @@ func (pool *BytePool) Get(index int32) []byte { return pool.buf[start:end] } -/* get the space allocate for each element */ +// MaxElemSize returns the space allocate for each element func (pool *BytePool) MaxElemSize() int { return pool.maxElemSize } diff --git a/bfe_util/byte_pool/fixed_byte_pool.go b/bfe_util/byte_pool/fixed_byte_pool.go index dc5d56f56..e1c9e7cdc 100644 --- a/bfe_util/byte_pool/fixed_byte_pool.go +++ b/bfe_util/byte_pool/fixed_byte_pool.go @@ -22,16 +22,14 @@ type FixedBytePool struct { maxElemNum int // max element num } -/* -* NewFixedBytePool - create a new FixedBytePool -* -* PARAMS: -* - elemNum: int, the max element num of FixedBytePool -* - elemSize: int, the max length of each element -* -* RETURNS: -* - a pointer point to the FixedBytePool - */ +// NewFixedBytePool creates a new FixedBytePool +// +// PARAMS: +// - elemNum: int, the max element num of FixedBytePool +// - elemSize: int, the max length of each element +// +// RETURNS: +// - a pointer point to the FixedBytePool func NewFixedBytePool(elemNum int, elemSize int) *FixedBytePool { pool := new(FixedBytePool) pool.buf = make([]byte, elemNum*elemSize) @@ -41,13 +39,11 @@ func NewFixedBytePool(elemNum int, elemSize int) *FixedBytePool { return pool } -/* -* Set - set the index node of FixedBytePool with key -* -* PARAMS: -* - index: index of the byte Pool -* - key: []byte key - */ +// Set sets the index node of FixedBytePool with key +// +// PARAMS: +// - index: index of the byte Pool +// - key: []byte key func (pool *FixedBytePool) Set(index int32, key []byte) error { if int(index) >= pool.maxElemNum { return fmt.Errorf("index out of range %d %d", index, pool.maxElemNum) @@ -62,15 +58,13 @@ func (pool *FixedBytePool) Set(index int32, key []byte) error { return nil } -/* -* Get the byte slice of giving index and length -* -* PARAMS: -* - index: int, index of the FixedBytePool -* -* RETURNS: -* - key: []byte type store in the FixedBytePool - */ +// Get the byte slice of giving index and length +// +// PARAMS: +// - index: int, index of the FixedBytePool +// +// RETURNS: +// - key: []byte type store in the FixedBytePool func (pool *FixedBytePool) Get(index int32) []byte { start := int(index) * pool.elemSize end := start + pool.elemSize @@ -78,7 +72,7 @@ func (pool *FixedBytePool) Get(index int32) []byte { return pool.buf[start:end] } -/* get the space allocate for each element */ +// MaxElemSize return the space allocate for each element func (pool *FixedBytePool) MaxElemSize() int { return pool.elemSize } diff --git a/bfe_util/hash_set/hash_set.go b/bfe_util/hash_set/hash_set.go index de48800d8..736f27303 100644 --- a/bfe_util/hash_set/hash_set.go +++ b/bfe_util/hash_set/hash_set.go @@ -29,10 +29,10 @@ const ( LOAD_FACTOR = 5 ) -/* index table of hashSet */ +// index table of hashSet type hashArray []int32 -/* make a new hashArray and init it */ +// make a new hashArray and init it func newHashArray(indexSize int) hashArray { ha := make(hashArray, indexSize) for i := 0; i < indexSize; i += 1 { @@ -52,19 +52,17 @@ type HashSet struct { hashFunc func(key []byte) uint64 //function for hash } -/* -* NewHashSet - create a newHashSet -* -* PARAMS: -* - elemNum: max element num of hashSet -* - elemSize: maxSize of hashKey after it converted to []byte -* - isFixKeyLen: fixed element size or not -* - hashFunc: hash function -* -* RETURNS: -* - (*HashSet, nil), if success -* - (nil, error), if fail - */ +// NewHashSet creates a newHashSet +// +// PARAMS: +// - elemNum: max element num of hashSet +// - elemSize: maxSize of hashKey after it converted to []byte +// - isFixKeyLen: fixed element size or not +// - hashFunc: hash function +// +// RETURNS: +// - (*HashSet, nil), if success +// - (nil, error), if fail func NewHashSet(elemNum int, elemSize int, isFixKeyLen bool, hashFunc func([]byte) uint64) (*HashSet, error) { if elemNum <= 0 || elemSize <= 0 { @@ -73,15 +71,15 @@ func NewHashSet(elemNum int, elemSize int, isFixKeyLen bool, hashSet := new(HashSet) - /* hashArray is larger in order to reduce hash conflict */ + // hashArray is larger in order to reduce hash conflict hashSet.haSize = elemNum * LOAD_FACTOR hashSet.isFixKeyLen = isFixKeyLen hashSet.ha = newHashArray(hashSet.haSize) - /* create nodePool */ + // create nodePool hashSet.np = newNodePool(elemNum, elemSize, isFixKeyLen) - /* if hashFunc is not given, use default murmur Hash */ + // if hashFunc is not given, use default murmur Hash if hashFunc != nil { hashSet.hashFunc = hashFunc } else { @@ -91,16 +89,14 @@ func NewHashSet(elemNum int, elemSize int, isFixKeyLen bool, return hashSet, nil } -/* -* Add - add an element into the set -* -* PARAMS: -* - key: []byte, element of the set -* -* RETURNS: -* - nil, if succeed -* - error, if fail - */ +// Add - add an element into the set +// +// PARAMS: +// - key: []byte, element of the set +// +// RETURNS: +// - nil, if succeed +// - error, if fail func (set *HashSet) Add(key []byte) error { // check the whether hashSet if full if set.Full() { @@ -134,16 +130,14 @@ func (set *HashSet) Add(key []byte) error { return nil } -/* -* Remove - remove an element from the hashSet -* -* PARAMS: -* - key: []byte, element of the set -* -* RETURNS: -* - nil, if succeed -* - error, if fail - */ +// Remove removes an element from the hashSet +// +// PARAMS: +// - key: []byte, element of the set +// +// RETURNS: +// - nil, if succeed +// - error, if fail func (set *HashSet) Remove(key []byte) error { // validate hashKey err := set.np.validateKey(key) @@ -166,7 +160,7 @@ func (set *HashSet) Remove(key []byte) error { return nil } -/* check if the element exist in Set */ +// Exist checks if the element exist in Set func (set *HashSet) Exist(key []byte) bool { //validate hashKey err := set.np.validateKey(key) @@ -178,18 +172,18 @@ func (set *HashSet) Exist(key []byte) bool { return set.exist(hashNum, key) } -/* check the []byte exist in the giving list head */ +// exist checks the []byte exist in the giving list head func (set *HashSet) exist(hashNum uint64, key []byte) bool { head := set.ha[hashNum] return set.np.exist(head, key) } -/* get elementNum of hashSet */ +// Len returns element Num of hashSet func (set *HashSet) Len() int { return set.np.elemNum() } -/* check if the hashSet full or not */ +// Full checks if the hashSet full or not func (set *HashSet) Full() bool { return set.np.full() } diff --git a/bfe_util/ipdict/ip_loc_table.go b/bfe_util/ipdict/ip_loc_table.go index dd87649c1..0ea34992f 100644 --- a/bfe_util/ipdict/ip_loc_table.go +++ b/bfe_util/ipdict/ip_loc_table.go @@ -28,14 +28,14 @@ const ( MAX_LOC_LEN = 1024 ) -//uppercasing the first letter for binary lib +// uppercasing the first letter for binary lib type ipLocation struct { startIp net.IP endIp net.IP location []byte } -//[]byte to string ,remove last 0 in []bytes +// []byte to string ,remove last 0 in []bytes func byteString(p []byte) string { for i := 0; i < len(p); i++ { if p[i] == 0 { @@ -54,12 +54,12 @@ type IpLocationTable struct { } func NewIpLocationTable(maxSize uint32, LocLen uint32) (*IpLocationTable, error) { - //maxSize max is MAX_LINE + // maxSize max is MAX_LINE if maxSize == 0 || maxSize > MAX_LINE { return nil, fmt.Errorf("NewIpLocationTable caused by maxSize :%d", maxSize) } - //LocLen max size is MAX_LOC_LEN + // LocLen max size is MAX_LOC_LEN if LocLen == 0 || LocLen > MAX_LOC_LEN { return nil, fmt.Errorf("NewIpLocationTable caused by LocLen :%d", LocLen) } @@ -72,7 +72,7 @@ func NewIpLocationTable(maxSize uint32, LocLen uint32) (*IpLocationTable, error) return ipLocTable, nil } -//write ipLocation Struct to locations by [HeaderLen+t.LocLen]byte +// write ipLocation Struct to locations by [HeaderLen+t.LocLen]byte func (t *IpLocationTable) writeStruct(idx uint32, ipLoc ipLocation) { sOffset := idx * (t.LocLen + HEADER_LEN) copy(t.locations[sOffset:sOffset+IP_SIZE], ipLoc.startIp) @@ -80,7 +80,7 @@ func (t *IpLocationTable) writeStruct(idx uint32, ipLoc ipLocation) { copy(t.locations[sOffset+HEADER_LEN:sOffset+HEADER_LEN+t.LocLen], ipLoc.location) } -//read ipLocation from locations by idx +// read ipLocation from locations by idx func (t *IpLocationTable) readStruct(idx uint32) ipLocation { var ipLoc ipLocation sOffset := idx * (t.LocLen + HEADER_LEN) @@ -90,9 +90,9 @@ func (t *IpLocationTable) readStruct(idx uint32) ipLocation { return ipLoc } -//add ip location dict to locations buffer -//assume add startIP:EndIP have been sorted -//every add startIP:EndIP region does not overlap +// Add ip location dict to locations buffer +// assume add startIP:EndIP have been sorted +// every add startIP:EndIP region does not overlap func (t *IpLocationTable) Add(startIP, endIP net.IP, location string) error { if err := checkIPPair(startIP, endIP); err != nil { return fmt.Errorf("Add failed: %s", err.Error()) @@ -105,7 +105,7 @@ func (t *IpLocationTable) Add(startIP, endIP net.IP, location string) error { startIP16 := startIP.To16() endIP16 := endIP.To16() - //write unit(startip,endip,location) to locations buffer + // write unit(startip,endip,location) to locations buffer var loc ipLocation loc.startIp = startIP16 loc.endIp = endIP16 @@ -117,8 +117,8 @@ func (t *IpLocationTable) Add(startIP, endIP net.IP, location string) error { return nil } -//binary search pool to find the ip's location -//search sort of array(order from small to large) +// Search find the ip's location. +// search sort of array(order from small to large) func (t *IpLocationTable) Search(cip net.IP) (string, error) { ipAddr16 := cip.To16() if ipAddr16 == nil { @@ -138,7 +138,7 @@ func (t *IpLocationTable) Search(cip net.IP) (string, error) { return bytes.Compare(b, ipAddr16) >= 0 }) - //get idx corresponding ip section's first ip + // get idx corresponding ip section's first ip var fristIp net.IP if uint32(idx) <= indexLen-1 { s := uint32(idx) * (HEADER_LEN + t.LocLen) @@ -149,18 +149,18 @@ func (t *IpLocationTable) Search(cip net.IP) (string, error) { var preIdx uint32 if uint32(idx) == indexLen { - //consider ipAdd last element(uint32(idx) == indexLen) + // consider ipAdd last element(uint32(idx) == indexLen) preIdx = uint32(indexLen - 1) } else if bytes.Equal(fristIp, ipAddr16) || idx == 0 { - //consider ipAdd locate in frist section (idx == 0) - //consider ipAdd is first ip in ip's section(fristIp == ipAddr16) + // consider ipAdd locate in frist section (idx == 0) + // consider ipAdd is first ip in ip's section(fristIp == ipAddr16) preIdx = uint32(idx) } else { - //other think ipAdd location previous section + // other think ipAdd location previous section preIdx = uint32(idx - 1) } - //read unit(startip,endip,location) from locations buffer + // read unit(startip,endip,location) from locations buffer loc := t.readStruct(preIdx) if bytes.Compare(ipAddr16, loc.endIp) <= 0 && bytes.Compare(ipAddr16, loc.startIp) >= 0 { return byteString(loc.location[0:]), nil diff --git a/bfe_util/ipdict/ipdict.go b/bfe_util/ipdict/ipdict.go index 7da1deac6..7334462ed 100644 --- a/bfe_util/ipdict/ipdict.go +++ b/bfe_util/ipdict/ipdict.go @@ -30,9 +30,7 @@ const ( IP_LENGTH = 16 ) -/* implement Hash method for hashSet - * convert net.IP to type uint64 - */ +// Hash is a hash method which convert net.IP to type uint64. func Hash(ip []byte) uint64 { hash64 := fnv.New64() hash64.Write(ip) @@ -46,14 +44,14 @@ type ipPair struct { type ipPairs []ipPair -/* IPItems manage single IP(hashSet) and ipPairs */ +// IPItems manage single IP(hashSet) and ipPairs type IPItems struct { ipSet *hash_set.HashSet items ipPairs Version string } -/* create new IPItems */ +// NewIPItems creates new IPItems func NewIPItems(maxSingleIPNum int, maxPairIPNum int) (*IPItems, error) { // maxSingleIPNum && maxPairIPNum must >= 0 if maxSingleIPNum < 0 || maxPairIPNum < 0 { @@ -76,26 +74,25 @@ func NewIPItems(maxSingleIPNum int, maxPairIPNum int) (*IPItems, error) { return ipItems, nil } -/* IPItems should implement Len() for calling sort.Sort(items) */ +// Len returns num of items func (items ipPairs) Len() int { return len(items) } -/* IPItems should implement Less(int, int) for calling sort.Sort(items) */ +// Less compares specified items func (items ipPairs) Less(i, j int) bool { return bytes.Compare(items[i].startIP, items[j].startIP) >= 0 } -/* IPItems should implement Swap(int, int) for calling sort.Sort(items) */ +// Swap swaps specified items func (items ipPairs) Swap(i, j int) { items[i], items[j] = items[j], items[i] } -/* checkMerge merge items between index i and j in sorted items. - If items[i] and items[j] can merge, then merge all items between index i and j - Others do not merge. - Constraint: j > i, items[j].endIP >= items[i].startIP -*/ +// checkMerge merge items between index i and j in sorted items. +// If items[i] and items[j] can merge, then merge all items between index i and j +// Others do not merge. +// Constraint: j > i, items[j].endIP >= items[i].startIP func (ipItems *IPItems) checkMerge(i, j int) int { var mergedNum int @@ -127,24 +124,23 @@ func (ipItems *IPItems) checkMerge(i, j int) int { return mergedNum } -/* mergeItems provides for merging sorted items - 1. Sorted dict - startIPStr endIPStr - ------------------------ - 10.26.74.55 10.26.74.255 - 10.23.77.88 10.23.77.240 - 10.21.34.5 10.23.77.100 - 10.12.14.2 10.12.14.50 - ------------------------ - 2. Merged sorted dict - startIPStr endIPStr - ------------------------ - 10.26.74.55 10.26.74.255 - 10.21.34.5 10.23.77.240 - 10.12.14.2 10.12.14.50 - 0.0.0.0 0.0.0.0 - ------------------------ -*/ +// mergeItems provides for merging sorted items +// 1. Sorted dict +// startIPStr endIPStr +// ------------------------ +// 10.26.74.55 10.26.74.255 +// 10.23.77.88 10.23.77.240 +// 10.21.34.5 10.23.77.100 +// 10.12.14.2 10.12.14.50 +// ------------------------ +// 2. Merged sorted dict +// startIPStr endIPStr +// ------------------------ +// 10.26.74.55 10.26.74.255 +// 10.21.34.5 10.23.77.240 +// 10.12.14.2 10.12.14.50 +// 0.0.0.0 0.0.0.0 +// ------------------------ func (ipItems *IPItems) mergeItems() int { var mergedNum int @@ -169,7 +165,7 @@ func (ipItems *IPItems) mergeItems() int { return mergedNum } -/* InsertPair provides insert startIP,endIP into IpItems */ +// InsertPair provides insert startIP,endIP into IpItems func (ipItems *IPItems) InsertPair(startIP, endIP net.IP) error { if err := checkIPPair(startIP, endIP); err != nil { return fmt.Errorf("InsertPair failed: %s", err.Error()) @@ -182,7 +178,7 @@ func (ipItems *IPItems) InsertPair(startIP, endIP net.IP) error { return nil } -/* InsertSingle single ip into ipitems */ +// InsertSingle insert single ip into ipitems func (ipItems *IPItems) InsertSingle(ip net.IP) error { ip16 := ip.To16() if ip16 == nil { @@ -191,40 +187,38 @@ func (ipItems *IPItems) InsertSingle(ip net.IP) error { return ipItems.ipSet.Add(ip16) } -/* - Sort provides for sorting dict according startIP by descending order - 1. Origin dict - startIPStr endIPStr - ------------------------ - 10.26.74.55 10.26.74.255 - 10.12.14.2 10.12.14.50 - 10.21.34.5 10.23.77.100 - 10.23.77.88 10.23.77.240 - ------------------------ - 2. Sorted dict - startIPStr endIPStr - ------------------------ - 10.26.74.55 10.26.74.255 - 10.23.77.88 10.23.77.240 - 10.21.34.5 10.23.77.100 - 10.12.14.2 10.12.14.50 - ------------------------ - 3. Merged sorted dict - startIPStr endIPStr - ------------------------ - 10.26.74.55 10.26.74.255 - 10.21.34.5 10.23.77.240 - 10.12.14.2 10.12.14.50 - 0.0.0.0 0.0.0.0 - ------------------------ - 4. Dict after resliced - startIPStr endIPStr - ------------------------ - 10.26.74.55 10.26.74.255 - 10.21.34.5 10.23.77.240 - 10.12.14.2 10.12.14.50 - ------------------------ -*/ +// Sort provides for sorting dict according startIP by descending order +// 1. Origin dict +// startIPStr endIPStr +// ------------------------ +// 10.26.74.55 10.26.74.255 +// 10.12.14.2 10.12.14.50 +// 10.21.34.5 10.23.77.100 +// 10.23.77.88 10.23.77.240 +// ------------------------ +// 2. Sorted dict +// startIPStr endIPStr +// ------------------------ +// 10.26.74.55 10.26.74.255 +// 10.23.77.88 10.23.77.240 +// 10.21.34.5 10.23.77.100 +// 10.12.14.2 10.12.14.50 +// ------------------------ +// 3. Merged sorted dict +// startIPStr endIPStr +// ------------------------ +// 10.26.74.55 10.26.74.255 +// 10.21.34.5 10.23.77.240 +// 10.12.14.2 10.12.14.50 +// 0.0.0.0 0.0.0.0 +// ------------------------ +// 4. Dict after resliced +// startIPStr endIPStr +// ------------------------ +// 10.26.74.55 10.26.74.255 +// 10.21.34.5 10.23.77.240 +// 10.12.14.2 10.12.14.50 +// ------------------------ func (ipItems *IPItems) Sort() { // Sort items according startIP by descending order @@ -241,7 +235,7 @@ func (ipItems *IPItems) Sort() { ipItems.items = ipItems.items[0:length] } -/* get ip num of IPItems */ +// Length return num of IPItems func (ipItems *IPItems) Length() int { num := len(ipItems.items) num += ipItems.ipSet.Len() diff --git a/bfe_util/ipdict/ipdict_test.go b/bfe_util/ipdict/ipdict_test.go index 93c9f3963..59aa0e163 100644 --- a/bfe_util/ipdict/ipdict_test.go +++ b/bfe_util/ipdict/ipdict_test.go @@ -28,21 +28,20 @@ func checkEqual(src, dst ipPairs) bool { if len(src) != len(dst) { fmt.Println("checkEqual(): len not equal!") return false - } else { - for i := 0; i < len(src); i++ { - if !bytes.Equal(src[i].startIP, dst[i].startIP) { - fmt.Printf("checkEqual(): start element [%d] and [%d] are not equal!\n", - src[i].startIP, dst[i].startIP) - return false - } - - if !bytes.Equal(src[i].endIP, dst[i].endIP) { - fmt.Printf("checkEqual(): end element [%d] and [%d] are not equal!\n", - src[i].endIP, dst[i].endIP) - return false - } + } + for i := 0; i < len(src); i++ { + if !bytes.Equal(src[i].startIP, dst[i].startIP) { + fmt.Printf("checkEqual(): start element [%d] and [%d] are not equal!\n", + src[i].startIP, dst[i].startIP) + return false + } + if !bytes.Equal(src[i].endIP, dst[i].endIP) { + fmt.Printf("checkEqual(): end element [%d] and [%d] are not equal!\n", + src[i].endIP, dst[i].endIP) + return false } + } return true diff --git a/bfe_util/ipdict/iptable.go b/bfe_util/ipdict/iptable.go index 47bbdf728..d202c9a9d 100644 --- a/bfe_util/ipdict/iptable.go +++ b/bfe_util/ipdict/iptable.go @@ -42,14 +42,14 @@ func (t *IPTable) Version() string { return "" } -/* Update provides for thread-safe switching items */ +// Update provides for thread-safe switching items func (t *IPTable) Update(items *IPItems) { t.lock.Lock() t.ipItems = items t.lock.Unlock() } -/* Search provides for binary search IP in dict */ +// Search provides for binary search IP in dict func (t *IPTable) Search(srcIP net.IP) bool { var hit bool t.lock.Lock() diff --git a/bfe_util/net_util/ip.go b/bfe_util/net_util/ip.go index 574739a66..b78132028 100644 --- a/bfe_util/net_util/ip.go +++ b/bfe_util/net_util/ip.go @@ -42,7 +42,7 @@ var privateRanges = []IpRange{ }, } -// InRange - check to see if a given ip address is within a range given +// InRange checks whether a given ip address is within a range given func InRange(r IpRange, ip net.IP) bool { if bytes.Compare(ip, r.start) >= 0 && bytes.Compare(ip, r.end) <= 0 { return true @@ -50,15 +50,13 @@ func InRange(r IpRange, ip net.IP) bool { return false } -/* -parse IP addr from string to net.IP - -Params: - - s: IP addr in string, e.g., "1.2.3.4" - -Returns: - IP addr in net.IP -*/ +// ParseIPv4 parse IP addr from string to net.IP +// +// Params: +// - s: IP addr in string, e.g., "1.2.3.4" +// +// Returns: +// IP addr in net.IP func ParseIPv4(s string) net.IP { ip := net.ParseIP(s) @@ -69,17 +67,15 @@ func ParseIPv4(s string) net.IP { return ip } -/* -convert net.IP to uint32 - -e.g., 1.2.3.4 to 0x01020304 - -Params: - - ipBytes: IPv4 addr in net.IP - -Returns: - IPv4 addr in uint32 -*/ +// IPv4ToUint32 convert net.IP to uint32 +// +// e.g., 1.2.3.4 to 0x01020304 +// +// Params: +// - ipBytes: IPv4 addr in net.IP +// +// Returns: +// IPv4 addr in uint32 func IPv4ToUint32(ipBytes net.IP) (uint32, error) { if len(ipBytes) != 4 { return 0, fmt.Errorf("ip bytes len: %d", len(ipBytes)) @@ -96,17 +92,15 @@ func IPv4ToUint32(ipBytes net.IP) (uint32, error) { return ipNum, nil } -/* -convert IPv4 string to uint32 - -e.g., "1.2.3.4" to 0x01020304 - -Params: - - ipStr: IPv4 addr in string - -Returns: - IPv4 addr in uint32 -*/ +// IPv4StrToUint32 convert IPv4 string to uint32 +// +// e.g., "1.2.3.4" to 0x01020304 +// +// Params: +// - ipStr: IPv4 addr in string +// +// Returns: +// IPv4 addr in uint32 func IPv4StrToUint32(ipStr string) (uint32, error) { ip := ParseIPv4(ipStr) if ip == nil { @@ -116,17 +110,15 @@ func IPv4StrToUint32(ipStr string) (uint32, error) { return IPv4ToUint32(ip) } -/* -convert uint32 net.IP - -e.g., 0x01020304 to 1.2.3.4 - -Params: - - ipNum: IPv4 addr in uint32 - -Returns: - IPv4 addr in net.IP -*/ +// Uint32ToIPv4 convert uint32 net.IP +// +// e.g., 0x01020304 to 1.2.3.4 +// +// Params: +// - ipNum: IPv4 addr in uint32 +// +// Returns: +// IPv4 addr in net.IP func Uint32ToIPv4(ipNum uint32) net.IP { var ipBytes [4]byte @@ -138,31 +130,27 @@ func Uint32ToIPv4(ipNum uint32) net.IP { return net.IPv4(ipBytes[0], ipBytes[1], ipBytes[2], ipBytes[3]).To4() } -/* -convert uint32 to str - -e.g., 0x01020304 to "1.2.3.4" - -Params: - - ipNum: IPv4 addr in uint32 - -Returns: - IPv4 addr in string -*/ +// Uint32ToIPv4Str convert uint32 to str +// +// e.g., 0x01020304 to "1.2.3.4" +// +// Params: +// - ipNum: IPv4 addr in uint32 +// +// Returns: +// IPv4 addr in string func Uint32ToIPv4Str(ipNum uint32) string { str := fmt.Sprintf("%d.%d.%d.%d", byte(ipNum>>24), byte(ipNum>>16), byte(ipNum>>8), byte(ipNum)) return str } -/* -Check input is ipv4 address or not. - -param: - - input: a string -return: - bool -*/ +// IsIPv4Address Check input is ipv4 address or not. +// +// param: +// - input: a string +// return: +// bool func IsIPv4Address(input string) bool { ip := net.ParseIP(input).To4() if ip == nil { @@ -171,14 +159,12 @@ func IsIPv4Address(input string) bool { return true } -/* -Check to see if an ip is in a private subnet. - -param: - - input: an ip string -return: - bool -*/ +// IsPrivateIp Check to see if an ip is in a private subnet. +// +// param: +// - input: an ip string +// return: +// bool func IsPrivateIp(input string) bool { if ip := net.ParseIP(input).To4(); ip != nil { for _, r := range privateRanges { diff --git a/bfe_util/signal_table/signal_handlers.go b/bfe_util/signal_table/signal_handlers.go index 9538bd9fb..1165b2574 100644 --- a/bfe_util/signal_table/signal_handlers.go +++ b/bfe_util/signal_table/signal_handlers.go @@ -22,14 +22,14 @@ import ( "github.com/baidu/go-lib/log" ) -/* TermHandler deal with the signal that should terminate the process */ +// TermHandler deal with the signal that should terminate the process func TermHandler(s os.Signal) { log.Logger.Info("termHandler(): receive signal[%v], terminate.", s) log.Logger.Close() os.Exit(0) } -/* IgnoreHandler deal with the signal that should be ignored */ +// IgnoreHandler deal with the signal that should be ignored func IgnoreHandler(s os.Signal) { log.Logger.Info("ignoreHandler(): receive signal[%v], ignore.", s) } diff --git a/bfe_util/signal_table/signal_table.go b/bfe_util/signal_table/signal_table.go index d32ece1d0..8866afddf 100644 --- a/bfe_util/signal_table/signal_table.go +++ b/bfe_util/signal_table/signal_table.go @@ -31,7 +31,7 @@ type SignalTable struct { state module_state2.State // signal handle state } -/* new and init signal table */ +// NewSignalTable creates and init signal table func NewSignalTable() *SignalTable { table := new(SignalTable) table.shs = make(map[os.Signal]signalHandler) @@ -39,14 +39,14 @@ func NewSignalTable() *SignalTable { return table } -/* register signal handle to the table */ +// Register registers signal handle to the table func (t *SignalTable) Register(s os.Signal, handler signalHandler) { if _, ok := t.shs[s]; !ok { t.shs[s] = handler } } -/* handle for the related signal */ +// handle handles the related signal func (t *SignalTable) handle(sig os.Signal) { t.state.Inc(sig.String(), 1) @@ -55,7 +55,7 @@ func (t *SignalTable) handle(sig os.Signal) { } } -// signal handle go-routine +// signalHandle is the signal handle loop func (table *SignalTable) signalHandle() { var sigs []os.Signal @@ -72,12 +72,12 @@ func (table *SignalTable) signalHandle() { } } -/* start go-routine for signal handle */ +// StartSignalHandle start go-routine for signal handle func (t *SignalTable) StartSignalHandle() { go t.signalHandle() } -/* get state counter of signal handle */ +// SignalStateGet get state counter of signal handle func (t *SignalTable) SignalStateGet() ([]byte, error) { buff, err := json.Marshal(t.state.GetAll()) @@ -85,12 +85,12 @@ func (t *SignalTable) SignalStateGet() ([]byte, error) { return buff, err } -/* set key prefix */ +// SetKeyPrefix set key prefix func (t *SignalTable) SetKeyPrefix(key string) { t.state.SetKeyPrefix(key) } -/* get key prefix */ +// GetKeyPrefix get key prefix func (t *SignalTable) GetKeyPrefix() string { return t.state.GetKeyPrefix() } diff --git a/bfe_websocket/common.go b/bfe_websocket/common.go index 305a5b368..f5501f900 100644 --- a/bfe_websocket/common.go +++ b/bfe_websocket/common.go @@ -39,7 +39,7 @@ var ( errRetryTooMany = errors.New("bfe_websocket: proxy retry too many") ) -// CheckAcceptWebSocket checks whether client request for WebSocket protocol. +// CheckUpgradeWebSocket checks whether client request for WebSocket protocol. func CheckUpgradeWebSocket(req *http.Request) bool { if req.Method != "GET" { return false @@ -71,9 +71,8 @@ func CheckAcceptWebSocket(rsp *http.Response) bool { func Scheme(c net.Conn) string { if _, ok := c.(*tls.Conn); ok { return "wss" // websocket over https - } else { - return "ws" // websocket over http } + return "ws" // websocket over http } // BalanceHandler selects backend for current conn. diff --git a/bfe_websocket/server_tester.go b/bfe_websocket/server_tester.go index 74b96172c..f2bb90fd0 100644 --- a/bfe_websocket/server_tester.go +++ b/bfe_websocket/server_tester.go @@ -115,37 +115,37 @@ func (st *ServerTester) handleWebsocketConn(conn net.Conn) { return } -// client start websocket handshake +// WebSocketHandshake starts websocket handshake (client perspective) func (st *ServerTester) WebSocketHandshake(c *websocket.Config) error { var err error st.wc, err = websocket.NewClient(c, st.cc) return err } -// client send webscoket message +// WebSocketWrite sends webscoket message (client perspective) func (st *ServerTester) WebSocketWrite(data []byte) (int, error) { return st.wc.Write(data) } -// client recv websocket message +// WebSocketRead recv websocket message (client perspective) func (st *ServerTester) WebSocketRead(msg []byte) (int, error) { return st.wc.Read(msg) } -// client read until timeout +// Read reads until timeout (client perspective) func (st *ServerTester) Read(buf []byte) error { st.cc.SetReadDeadline(time.Now().Add(4 * time.Second)) _, err := io.ReadFull(st.cc, buf) return err } -// client write raw data +// Write writes raw data (client perspective) func (st *ServerTester) Write(data []byte) error { _, err := st.cc.Write(data) return err } -// client read and check error +// WantError read and check error (client perspective) func (st *ServerTester) WantError(e string) { err := st.Read(make([]byte, 256)) if err == nil {