From 660aa6508da58844687aaa05357db855112fec8c Mon Sep 17 00:00:00 2001 From: swarupn Date: Wed, 19 May 2021 16:04:40 +0530 Subject: [PATCH] Issue-Id: #I3OW9P maintainability related quality improvement for mep-agent Signed-off-by: swarupn --- src/config/address.go | 74 +++++++++--------- src/config/log.go | 5 +- src/controllers/endpointcontroller.go | 38 ++++++---- src/controllers/errcontroller.go | 4 +- src/controllers/tokencontroller.go | 12 +-- src/main/main.go | 14 ++-- src/model/auth.go | 3 +- src/model/conf.go | 4 +- src/model/instance.go | 104 ++++++++++++++------------ src/model/tokenmodel.go | 3 +- src/router/router.go | 2 +- src/service/heart.go | 25 ++++--- src/service/register.go | 85 +++++++++++---------- src/service/request.go | 77 ++++++++++--------- src/service/start.go | 20 ++--- src/service/token.go | 22 +++--- src/test/address_test.go | 5 +- src/test/controller_test.go | 2 +- src/test/endpointcontroller_test.go | 4 +- src/test/heart_test.go | 6 +- src/test/register_test.go | 12 +-- src/test/token_test.go | 8 +- src/test/util_test.go | 14 ++-- src/test/validation_test.go | 4 +- src/util/sign.go | 50 ++++++------- src/util/util.go | 67 +++++++++-------- src/util/validation.go | 37 ++++----- 27 files changed, 372 insertions(+), 329 deletions(-) diff --git a/src/config/address.go b/src/config/address.go index 13baf55..e842ac9 100644 --- a/src/config/address.go +++ b/src/config/address.go @@ -14,7 +14,7 @@ * limitations under the License. */ -// server address url config +// Package config server address url config package config import ( @@ -24,52 +24,54 @@ import ( "strings" ) -type ServerUrl struct { - MepServerRegisterUrl string - MepAuthUrl string - MepHeartBeatUrl string - MepServiceDiscoveryUrl string +// ServerURL : List of Urls. +type ServerURL struct { + MepServerRegisterURL string + MepAuthURL string + MepHeartBeatURL string + MepServiceDiscoveryURL string } const ( - MepAuthApigwUrl string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/token" - MepSerRegisterApigwUrl string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/mec_service_mgmt/v1/applications/${appInstanceId}/services" - MepSerQueryByNameApigwUrl string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/mec_service_mgmt/v1/services?ser_name=" - MepHeartBeatApigwUrl string = "https://${MEP_IP}:${MEP_APIGW_PORT}" - MepIp string = "${MEP_IP}" - MepApigwPort string = "${MEP_APIGW_PORT}" + mepAuthApigwURL string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/token" + mepSerRegisterApigwURL string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/mec_service_mgmt/v1/applications/${appInstanceId}/services" + mepSerQueryByNameApigwURL string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/mec_service_mgmt/v1/services?ser_name=" + mepHeartBeatApigwURL string = "https://${MEP_IP}:${MEP_APIGW_PORT}" + mepIP string = "${MEP_IP}" + mepApigwPort string = "${MEP_APIGW_PORT}" ) -var ServerUrlConfig ServerUrl +// ServerURLConfig server Url Configuration. +var ServerURLConfig ServerURL -// Returns server URL -func GetServerUrl() (ServerUrl, error) { - - var serverUrl ServerUrl +// GetServerURL returns server URL. +func GetServerURL() (ServerURL, error) { + var serverURL ServerURL // validate the env params - mepIp := os.Getenv("MEP_IP") - if util.ValidateDns(mepIp) != nil { - return serverUrl, errors.New("validate MEP_IP failed") + mepIPVal := os.Getenv("MEP_IP") + if util.ValidateDNS(mepIP) != nil { + return serverURL, errors.New("validate MEP_IP failed") } - mepApiGwPort := os.Getenv("MEP_APIGW_PORT") - if util.ValidateByPattern(util.PORT_PATTERN, mepApiGwPort) != nil { - return serverUrl, errors.New("validate MEP_APIGW_PORT failed") + mepAPIGwPort := os.Getenv("MEP_APIGW_PORT") + if util.ValidateByPattern(util.PortPattern, mepAPIGwPort) != nil { + return serverURL, errors.New("validate MEP_APIGW_PORT failed") } - serverUrl.MepServerRegisterUrl = strings.Replace( - strings.Replace(MepSerRegisterApigwUrl, MepIp, mepIp, 1), - MepApigwPort, mepApiGwPort, 1) + serverURL.MepServerRegisterURL = strings.Replace( + strings.Replace(mepSerRegisterApigwURL, mepIP, mepIPVal, 1), + mepApigwPort, mepAPIGwPort, 1) + + serverURL.MepAuthURL = strings.Replace( + strings.Replace(mepAuthApigwURL, mepIP, mepIPVal, 1), + mepApigwPort, mepAPIGwPort, 1) - serverUrl.MepAuthUrl = strings.Replace( - strings.Replace(MepAuthApigwUrl, MepIp, mepIp, 1), - MepApigwPort, mepApiGwPort, 1) + serverURL.MepHeartBeatURL = strings.Replace( + strings.Replace(mepHeartBeatApigwURL, mepIP, mepIPVal, 1), + mepApigwPort, mepAPIGwPort, 1) - serverUrl.MepHeartBeatUrl = strings.Replace( - strings.Replace(MepHeartBeatApigwUrl, MepIp, mepIp, 1), - MepApigwPort, mepApiGwPort, 1) + serverURL.MepServiceDiscoveryURL = strings.Replace( + strings.Replace(mepSerQueryByNameApigwURL, mepIP, mepIPVal, 1), + mepApigwPort, mepAPIGwPort, 1) - serverUrl.MepServiceDiscoveryUrl = strings.Replace( - strings.Replace(MepSerQueryByNameApigwUrl, MepIp, mepIp, 1), - MepApigwPort, mepApiGwPort, 1) - return serverUrl, nil + return serverURL, nil } diff --git a/src/config/log.go b/src/config/log.go index e3a1001..6fa3747 100644 --- a/src/config/log.go +++ b/src/config/log.go @@ -14,7 +14,7 @@ * limitations under the License. */ -// logrus config +// Package config logrus config package config import ( @@ -40,9 +40,8 @@ func init() { Compress: true, // compress } logrus.SetOutput(ioWriter) - } else { - logrus.Warn("Failed to log to file, using default stderr") + logrus.Warn("Failed to log to file, using default stderr.") } logrus.SetLevel(logrus.InfoLevel) diff --git a/src/controllers/endpointcontroller.go b/src/controllers/endpointcontroller.go index b2e5b87..9398e01 100644 --- a/src/controllers/endpointcontroller.go +++ b/src/controllers/endpointcontroller.go @@ -14,72 +14,78 @@ * limitations under the License. */ +// Package controllers Endpoint controller package controllers import ( "encoding/json" + "github.com/astaxie/beego" + log "github.com/sirupsen/logrus" "mep-agent/src/config" "mep-agent/src/service" "mep-agent/src/util" - - "github.com/astaxie/beego" - log "github.com/sirupsen/logrus" + "net/http" ) +// EndpointController beego Endpoint Controller. type EndpointController struct { beego.Controller } +// Service Service information. type Service struct { TransportInfo TransportInfo `yaml:"transportInfo" json:"transportInfo"` } -// Transport information of the service. +// TransportInfo Transport information of the service. type TransportInfo struct { Id string `yaml:"id" json:"id"` Name string `yaml:"name" json:"name"` Description string `yaml:"description" json:"description"` Protocol string `yaml:"protocol" json:"protocol"` Version string `yaml:"version" json:"version"` - Endpoint EndPointInfo `yaml:"endpoint" json:"endpoint"` + Endpoint endPointInfo `yaml:"endpoint" json:"endpoint"` } -// End point of the service. -type EndPointInfo struct { +// endPointInfo End point of the service. +type endPointInfo struct { Uris []string `json:"uris" validate:"omitempty,dive,uri"` - Addresses []EndPointInfoAddress `json:"addresses" validate:"omitempty,dive"` + Addresses []endPointInfoAddress `json:"addresses" validate:"omitempty,dive"` Alternative interface{} `json:"alternative"` } -type EndPointInfoAddress struct { +// endPointInfoAddress Endpoint info address. +type endPointInfoAddress struct { Host string `json:"host" validate:"required"` Port uint32 `json:"port" validate:"required,gt=0,lte=65535"` } +// Get handles endpoint request from app. func (c *EndpointController) Get() { log.Info("received get endpoint request from app") - serName := c.Ctx.Input.Param(":serName") - url := config.ServerUrlConfig.MepServiceDiscoveryUrl + serName - - requestData := service.RequestData{Data: "", Url: url, Token: &util.MepToken} + serName := c.Ctx.Input.Param(":serName") + url := config.ServerURLConfig.MepServiceDiscoveryURL + serName + requestData := service.RequestData{Data: "", URL: url, Token: &util.MepToken} resBody, errPostRequest := service.SendQueryRequest(requestData) if errPostRequest != nil { log.Error("Failed heart beat request to mep, URL is " + url) } - var resBodyMap []Service + log.Info("resBodyMap: ", resBody) + err := json.Unmarshal([]byte(resBody), &resBodyMap) if err != nil { log.Error("Unmarshal failed") c.Data["json"] = "Service does not exist." - c.Ctx.ResponseWriter.WriteHeader(400) + c.Ctx.ResponseWriter.WriteHeader(http.StatusBadRequest) } else { transportInfo := resBodyMap[0].TransportInfo log.Info("Endpoint: ", transportInfo.Endpoint) c.Data["json"] = transportInfo.Endpoint - c.Ctx.ResponseWriter.WriteHeader(200) + c.Ctx.ResponseWriter.WriteHeader(http.StatusOK) } + c.ServeJSON() } diff --git a/src/controllers/errcontroller.go b/src/controllers/errcontroller.go index 8109799..1f5353a 100644 --- a/src/controllers/errcontroller.go +++ b/src/controllers/errcontroller.go @@ -14,15 +14,17 @@ * limitations under the License. */ +// Package controllers Error controller handles unknown page request package controllers import "github.com/astaxie/beego" +// ErrorController beego error controller. type ErrorController struct { beego.Controller } -// Error handling for invalid request +// Error404 Error handling for invalid request. func (c *ErrorController) Error404() { c.Data["content"] = "page not found" c.TplName = "error/404.tpl" diff --git a/src/controllers/tokencontroller.go b/src/controllers/tokencontroller.go index 3a92fb2..8531ff5 100644 --- a/src/controllers/tokencontroller.go +++ b/src/controllers/tokencontroller.go @@ -14,30 +14,32 @@ * limitations under the License. */ +// Package controllers TokenController controller package package controllers import ( "github.com/astaxie/beego" log "github.com/sirupsen/logrus" "mep-agent/src/util" + "net/http" ) +// TokenController handles token request. type TokenController struct { beego.Controller } -// Get /mep-agent/v1/token function +// Get /mep-agent/v1/token function. func (c *TokenController) Get() { log.Info("received get token request from app") if !util.FirstToken { log.Error("First Token not yet received.") - c.Ctx.ResponseWriter.WriteHeader(412) + c.Ctx.ResponseWriter.WriteHeader(http.StatusPreconditionFailed) + return } // Get the last token c.Data["json"] = &util.MepToken - c.Ctx.ResponseWriter.WriteHeader(200) + c.Ctx.ResponseWriter.WriteHeader(http.StatusOK) c.ServeJSON() } - - diff --git a/src/main/main.go b/src/main/main.go index 0cb0ffd..1429034 100644 --- a/src/main/main.go +++ b/src/main/main.go @@ -14,17 +14,19 @@ * limitations under the License. */ +// main package package main import ( - "github.com/astaxie/beego" - log "github.com/sirupsen/logrus" "mep-agent/src/config" - "mep-agent/src/controllers" + controller "mep-agent/src/controllers" _ "mep-agent/src/router" "mep-agent/src/service" "mep-agent/src/util" "os" + + "github.com/astaxie/beego" + log "github.com/sirupsen/logrus" ) func main() { @@ -36,14 +38,14 @@ func main() { os.Exit(1) } - service.TlsConf, err = service.TlsConfig() + service.TLSConf, err = service.TLSConfig() if err != nil { log.Error("Failed to set TLS Configurations") util.ClearMap() os.Exit(1) } - config.ServerUrlConfig, err = config.GetServerUrl() + config.ServerURLConfig, err = config.GetServerURL() if err != nil { log.Error("Failed to get server url Configurations") util.ClearMap() @@ -54,6 +56,6 @@ func main() { go service.BeginService().Start("./conf/app_instance_info.yaml") log.Info("Starting server") - beego.ErrorController(&controllers.ErrorController{}) + beego.ErrorController(&controller.ErrorController{}) beego.Run() } diff --git a/src/model/auth.go b/src/model/auth.go index 867255d..78e5b33 100644 --- a/src/model/auth.go +++ b/src/model/auth.go @@ -14,9 +14,10 @@ * limitations under the License. */ -// aksk model +// Package model Authentication model package model +// Auth Authentication information. type Auth struct { SecretKey *[]byte AccessKey string diff --git a/src/model/conf.go b/src/model/conf.go index 1a2f877..c24391a 100644 --- a/src/model/conf.go +++ b/src/model/conf.go @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// define the conf model + +// Package model define the conf model package model +// AppConfInfo : App configuration information. type AppConfInfo struct { SslCiphers string `yaml:"sslCiphers" json:"sslCiphers"` } diff --git a/src/model/instance.go b/src/model/instance.go index c897ac9..2314b46 100644 --- a/src/model/instance.go +++ b/src/model/instance.go @@ -14,116 +14,126 @@ * limitations under the License. */ -// define the type information +// Package model define the type information package model +// AppInstanceInfo : Application instance info. type AppInstanceInfo struct { ServiceInfoPosts []ServiceInfoPost `yaml:"serviceInfoPosts" json:"serviceInfoPosts"` - SerAvailabilityNotificationSubscriptions []SerAvailabilityNotificationSubscription `yaml:"serAvailabilityNotificationSubscriptions" json:"serAvailabilityNotificationSubscriptions"` + SerAvailabilityNotificationSubscriptions []serAvailabilityNotificationSubscription `yaml:"serAvailabilityNotificationSubscriptions" json:"serAvailabilityNotificationSubscriptions"` } -// Service Information to be registered. +// ServiceInfoPost Service Information to be registered. type ServiceInfoPost struct { SerName string `yaml:"serName" json:"serName"` - SerCategory CategoryRef `yaml:"serCategory" json:"serCategory"` + SerCategory categoryRef `yaml:"serCategory" json:"serCategory"` Version string `yaml:"version" json:"version"` - State ServiceState `yaml:"state" json:"state"` + State serviceState `yaml:"state" json:"state"` TransportId string `yaml:"transportId" json:"transportId"` - TransportInfo TransportInfo `yaml:"transportInfo" json:"transportInfo"` - Serializer SerializerType `yaml:"serializer" json:"serializer"` - ScopeOfLocality LocalityType `yaml:"scopeOfLocality" json:"scopeOfLocality"` + TransportInfo transportInfo `yaml:"transportInfo" json:"transportInfo"` + Serializer serializerType `yaml:"serializer" json:"serializer"` + ScopeOfLocality localityType `yaml:"scopeOfLocality" json:"scopeOfLocality"` ConsumedLocalOnly bool `yaml:"consumedLocalOnly" json:"consumedLocalOnly"` IsLocal bool `yaml:"isLocal" json:"isLocal"` LivenessInterval int `yaml:"livenessInterval" json:"livenessInterval,omitempty"` - Links _links `json:"_links,omitempty"` + Links _links `json:"_links,omitempty"` SerInstanceId string `json:"serInstanceId,omitempty"` } -type ServiceInfo struct { - SerName string `json:"serName"` - Version string `json:"version"` - -} - -type CategoryRef struct { +// categoryRef Service category. +type categoryRef struct { Href string `yaml:"href" json:"href"` Id string `yaml:"id" json:"id"` Name string `yaml:"name" json:"name"` Version string `yaml:"version" json:"version"` } -type ServiceState string +// serviceState Service state. +type serviceState string -// Transport Information of the service to be registered. -type TransportInfo struct { +// transportInfo Transport Information of the service to be registered. +type transportInfo struct { Id string `yaml:"id" json:"id"` Name string `yaml:"name" json:"name"` Description string `yaml:"description" json:"description"` - TransportType TransportType `yaml:"type" json:"type"` + TransportType transportType `yaml:"type" json:"type"` Protocol string `yaml:"protocol" json:"protocol"` Version string `yaml:"version" json:"version"` - Endpoint EndPointInfo `yaml:"endpoint" json:"endpoint"` - Security SecurityInfo `yaml:"security" json:"security"` - ImplSpecificInfo ImplSpecificInfo `yaml:"implSpecificInfo" json:"implSpecificInfo"` + Endpoint endPointInfo `yaml:"endpoint" json:"endpoint"` + Security securityInfo `yaml:"security" json:"security"` + ImplSpecificInfo implSpecificInfo `yaml:"implSpecificInfo" json:"implSpecificInfo"` } -type TransportType string +type transportType string -// Endpoint of the service to be registered. -type EndPointInfo struct { - Addresses []EndPointInfoAddress `yaml:"addresses" json:"addresses"` +// endPointInfo: Endpoint of the service to be registered. +type endPointInfo struct { + Addresses []endPointInfoAddress `yaml:"addresses" json:"addresses"` } -type EndPointInfoAddress struct { +// endPointInfoAddress: Endpoint information. +type endPointInfoAddress struct { Host string `yaml:"host" json:"host"` Port uint32 `yaml:"port" json:"port"` } -type SecurityInfo struct { - OAuth2Info SecurityInfoOAuth2Info `yaml:"oAuth2Info" json:"oAuth2Info"` +// securityInfo: Security information. +type securityInfo struct { + OAuth2Info securityInfoOAuth2Info `yaml:"oAuth2Info" json:"oAuth2Info"` } -type SecurityInfoOAuth2Info struct { - GrantTypes []SecurityInfoOAuth2InfoGrantType `yaml:"grantTypes" json:"grantTypes"` +// securityInfoOAuth2Info Security Auth2 information. +type securityInfoOAuth2Info struct { + GrantTypes []securityInfoOAuth2InfoGrantType `yaml:"grantTypes" json:"grantTypes"` TokenEndpoint string `yaml:"tokenEndpoint" json:"tokenEndpoint"` } -type SecurityInfoOAuth2InfoGrantType string +// securityInfoOAuth2InfoGrantType Security Auth2 grant type. +type securityInfoOAuth2InfoGrantType string -type ImplSpecificInfo struct { +// implSpecificInfo Impl specific info if any. +type implSpecificInfo struct { } -type SerializerType string +// serializerType Serializer Type. +type serializerType string -type LocalityType string +// localityType : Scope of Locality Type. +type localityType string -type SerAvailabilityNotificationSubscription struct { +// serAvailabilityNotificationSubscription : Service Availability Notification Subscription. +type serAvailabilityNotificationSubscription struct { SubscriptionType string `yaml:"subscriptionType" json:"subscriptionType"` CallbackReference string `yaml:"callbackReference" json:"callbackReference"` - Links Self `yaml:"links" json:"links"` - FilteringCriteria SerAvailabilityNotificationSubscriptionFilteringCriteria `yaml:"filteringCriteria" json:"filteringCriteria"` + Links self `yaml:"links" json:"links"` + FilteringCriteria serAvailabilityNotificationSubscriptionFilteringCriteria `yaml:"filteringCriteria" json:"filteringCriteria"` } -type Self struct { - Self LinkType `yaml:"self" json:"self"` +// self link. +type self struct { + Self linkType `yaml:"self" json:"self"` } -type LinkType struct { +// linkType Link type. +type linkType struct { Href string `yaml:"href" json:"href"` } -type SerAvailabilityNotificationSubscriptionFilteringCriteria struct { +// serAvailabilityNotificationSubscriptionFilteringCriteria : Service Availability Notification Subscription FilteringCriteria. +type serAvailabilityNotificationSubscriptionFilteringCriteria struct { SerInstanceIds []string `yaml:"serInstanceIds" json:"serInstanceIds"` SerNames []string `yaml:"serNames" json:"serNames"` - SerCategories []CategoryRef `yaml:"serCategories" json:"serCategories"` - States []ServiceState `yaml:"states" json:"states"` + SerCategories []categoryRef `yaml:"serCategories" json:"serCategories"` + States []serviceState `yaml:"states" json:"states"` IsLocal bool `yaml:"isLocal" json:"isLocal"` } +// _links : Liveness link. type _links struct { - Self LivenessLinktype `yaml:"self" json:"self"` + Self livenessLinktype `yaml:"self" json:"self"` } -type LivenessLinktype struct { +// Liveness link type. +type livenessLinktype struct { Liveness string `json:"liveness"` } diff --git a/src/model/tokenmodel.go b/src/model/tokenmodel.go index 5857b61..0beda35 100644 --- a/src/model/tokenmodel.go +++ b/src/model/tokenmodel.go @@ -14,9 +14,10 @@ * limitations under the License. */ -// token model +// Package model token model package model +// TokenModel : Token model. type TokenModel struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` diff --git a/src/router/router.go b/src/router/router.go index d83ad24..fcbf422 100644 --- a/src/router/router.go +++ b/src/router/router.go @@ -14,6 +14,7 @@ * limitations under the License. */ +// Package route routes package package route import ( @@ -25,4 +26,3 @@ func init() { beego.Router("/mep-agent/v1/token", &controllers.TokenController{}) beego.Router("/mep-agent/v1/endpoint/:serName", &controllers.EndpointController{}) } - diff --git a/src/service/heart.go b/src/service/heart.go index b5d6fb2..73cc5ec 100644 --- a/src/service/heart.go +++ b/src/service/heart.go @@ -14,7 +14,7 @@ * limitations under the License. */ -// heart service +// Package service heart service package service import ( @@ -24,30 +24,31 @@ import ( "mep-agent/src/model" "mep-agent/src/util" ) - -type HeartBeatData struct { +// heartBeatData: Heartbeat information. +type heartBeatData struct { token *model.TokenModel data string url string } -type ServiceLivenessUpdate struct { + +type serviceLivenessUpdate struct { State string `json:"state"` } -// Send service heartbeat to MEP +// HeartBeatRequestToMep Send service heartbeat to MEP. func HeartBeatRequestToMep(serviceInfo model.ServiceInfoPost) { - - heartBeatRequest := ServiceLivenessUpdate{State: "ACTIVE"} - data, errJsonMarshal := json.Marshal(heartBeatRequest) - if errJsonMarshal != nil { + heartBeatRequest := serviceLivenessUpdate{State: "ACTIVE"} + data, errJSONMarshal := json.Marshal(heartBeatRequest) + if errJSONMarshal != nil { log.Error("Failed to marshal service info to object") + return } - url := config.ServerUrlConfig.MepHeartBeatUrl + serviceInfo.Links.Self.Liveness - var heartBeatData = HeartBeatData{data: string(data), url: url, token: &util.MepToken} - _, errPostRequest := SendHeartBeatRequest(heartBeatData) + url := config.ServerURLConfig.MepHeartBeatURL + serviceInfo.Links.Self.Liveness + var heartBeatInfo = heartBeatData{data: string(data), url: url, token: &util.MepToken} + _, errPostRequest := sendHeartBeatRequest(heartBeatInfo) if errPostRequest != nil { log.Error("Failed heart beat request to mep, URL is " + url) } diff --git a/src/service/register.go b/src/service/register.go index 8f5ef92..5361361 100644 --- a/src/service/register.go +++ b/src/service/register.go @@ -14,12 +14,13 @@ * limitations under the License. */ -// register to mep service +// Package service register to mep service package service import ( "encoding/json" "errors" + log "github.com/sirupsen/logrus" "mep-agent/src/config" "mep-agent/src/model" "mep-agent/src/util" @@ -27,104 +28,106 @@ import ( "strings" "sync" "time" - - log "github.com/sirupsen/logrus" ) const ( - RETRY_TIMES int = 5 - RETRY_PERIOD int = 30 - MAX_SERVICE_COUNT int = 50 + retryTimes int = 5 + retryPeriod int = 30 + maxServiceCount int = 50 ) -type RegisterData struct { +type registerData struct { token *model.TokenModel data string url string } +// dataStore : Store service info posts. var dataStore []model.ServiceInfoPost -// Registers service to mep +// RegisterToMep Registers service to mep. func RegisterToMep(conf model.AppInstanceInfo, wg *sync.WaitGroup) ([]model.ServiceInfoPost, error) { log.Info("begin to register service to mep") serviceInfos := conf.ServiceInfoPosts - appInstanceId := util.AppInstanceId + appInstanceID := util.AppInstanceID - if len(serviceInfos) > MAX_SERVICE_COUNT { - log.Error("Failed to register all the services to mep, appInstanceId is " + appInstanceId) - return nil, errors.New("Registration of service failed, cannot contain more than " + - strconv.Itoa(MAX_SERVICE_COUNT) + " services in a single request") + if len(serviceInfos) > maxServiceCount { + log.Error("Failed to register all the services to mep, appInstanceId is " + appInstanceID) + return nil, errors.New("registration of service failed, cannot contain more than " + + strconv.Itoa(maxServiceCount) + " services in a single request") } - if util.ValidateUUID(appInstanceId) != nil { + if util.ValidateUUID(appInstanceID) != nil { return nil, errors.New("validate appInstanceId failed") } - url := strings.Replace(config.ServerUrlConfig.MepServerRegisterUrl, "${appInstanceId}", appInstanceId, 1) + url := strings.Replace(config.ServerURLConfig.MepServerRegisterURL, "${appInstanceId}", appInstanceID, 1) for _, serviceInfo := range serviceInfos { - data, errJsonMarshal := json.Marshal(serviceInfo) - if errJsonMarshal != nil { + data, errJSONMarshal := json.Marshal(serviceInfo) + if errJSONMarshal != nil { log.Error("Failed to marshal service info to object") + continue } - var registerData = RegisterData{data: string(data), url: url, token: &util.MepToken} - resBody, errPostRequest := PostRegisterRequest(registerData) + var registerInfo = registerData{data: string(data), url: url, token: &util.MepToken} + resBody, errPostRequest := postRegisterRequest(registerInfo) if errPostRequest != nil { - log.Error("failed to register to mep, appInstanceId is " + appInstanceId + + log.Error("failed to register to mep, appInstanceId is " + appInstanceID + ", serviceName is " + serviceInfo.SerName) wg.Add(1) - go retryRegister(registerData, appInstanceId, serviceInfo, wg) + go retryRegister(registerInfo, appInstanceID, serviceInfo, wg) } else { - log.Info("register to mep success, appInstanceId is " + appInstanceId + + log.Info("register to mep success, appInstanceId is " + appInstanceID + ", serviceName is " + serviceInfo.SerName) - _, errPostRequest = storeRegisterData(resBody) + errPostRequest = storeRegisterData(resBody) if errPostRequest != nil { continue } - } - } log.Info("services registered to mep count ", len(dataStore)) + return dataStore, nil } -func retryRegister(registerData RegisterData, appInstanceId string, serviceInfo model.ServiceInfoPost, +func retryRegister(registerData registerData, appInstanceID string, serviceInfo model.ServiceInfoPost, wg *sync.WaitGroup) { defer wg.Done() - for i := 1; i < RETRY_TIMES; i++ { + for i := 1; i < retryTimes; i++ { log.Warn("Failed to register to mep, register will retry 5 times, already register " + strconv.Itoa(i) + - " times, the next register will begin after " + strconv.Itoa(RETRY_PERIOD*i) + " seconds.") - time.Sleep(time.Duration(RETRY_PERIOD*i) * time.Second) + " times, the next register will begin after " + strconv.Itoa(retryPeriod*i) + " seconds.") + time.Sleep(time.Duration(retryPeriod*i) * time.Second) - resBody, errPostRequest := PostRegisterRequest(registerData) + resBody, errPostRequest := postRegisterRequest(registerData) if errPostRequest != nil { - log.Error("Failed to register to mep, appInstanceId is " + appInstanceId + + log.Error("Failed to register to mep, appInstanceId is " + appInstanceID + ", serviceName is " + serviceInfo.SerName) } else { - log.Info("Register to mep success, appInstanceId is " + appInstanceId + + log.Info("Register to mep success, appInstanceId is " + appInstanceID + ", serviceName is " + serviceInfo.SerName) - _, errJsonUnMarshal := storeRegisterData(resBody) - if errJsonUnMarshal != nil { - log.Error("Failed to unmarshal object to service info " + errJsonUnMarshal.Error()) + errJSONUnMarshal := storeRegisterData(resBody) + if errJSONUnMarshal != nil { + log.Error("Failed to unmarshal object to service info " + errJSONUnMarshal.Error()) } + break } } } -func storeRegisterData(resBody string) ([]model.ServiceInfoPost, error) { - data := model.ServiceInfoPost{} - errJsonUnMarshal := json.Unmarshal([]byte(resBody), &data) +func storeRegisterData(resBody string) error { + var data = model.ServiceInfoPost{} + errJSONUnMarshal := json.Unmarshal([]byte(resBody), &data) - if errJsonUnMarshal != nil { + if errJSONUnMarshal != nil { log.Error("Failed to unmarshal object to service info") - return nil, errJsonUnMarshal + + return errJSONUnMarshal } dataStore = append(dataStore,data) - return dataStore, nil + + return nil } diff --git a/src/service/request.go b/src/service/request.go index cb9b1db..efe196f 100644 --- a/src/service/request.go +++ b/src/service/request.go @@ -14,7 +14,7 @@ * limitations under the License. */ -// util service +// Package service util service package service import ( @@ -33,23 +33,26 @@ import ( "gopkg.in/yaml.v2" ) -const AUTHORIZATION = "Authorization" +// authorization authorization string. +const authorization = "Authorization" -var TlsConf *tls.Config +// TLSConf Tls configuration. +var TLSConf *tls.Config +// RequestData : Request Data. type RequestData struct { Token *model.TokenModel Data string - Url string + URL string } -// const +// cipherSuiteMap cipher Suites. var cipherSuiteMap = map[string]uint16{ "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, } -// get yaml and parse to AppInstanceInfo object +// GetAppInstanceConf get yaml and parse to AppInstanceInfo object. func GetAppInstanceConf(path string) (model.AppInstanceInfo, error) { yamlFile, err := ioutil.ReadFile(path) var info model.AppInstanceInfo @@ -60,6 +63,7 @@ func GetAppInstanceConf(path string) (model.AppInstanceInfo, error) { if err != nil { return info, err } + return info, nil } @@ -73,20 +77,21 @@ func getAPPConf(path string) (model.AppConfInfo, error) { if err != nil { return info, err } + return info, nil } -// register to mep -func PostRegisterRequest(registerData RegisterData) (string, error) { +// postRegisterRequest : register to mep. +func postRegisterRequest(registerData registerData) (string, error) { // construct http request req, errNewRequest := http.NewRequest("POST", registerData.url, strings.NewReader(registerData.data)) if errNewRequest != nil { return "", errNewRequest } - req.Header.Set(AUTHORIZATION, registerData.token.TokenType+" "+registerData.token.AccessToken) + req.Header.Set(authorization, registerData.token.TokenType+" "+registerData.token.AccessToken) // send http request - response, errDo := DoRequest(req) + response, errDo := doRequest(req) if errDo != nil { return "", errDo } @@ -104,8 +109,8 @@ func PostRegisterRequest(registerData RegisterData) (string, error) { return string(body), nil } -// get token from mep -func PostTokenRequest(param string, url string, auth model.Auth) (string, error) { +// get token from mep. +func postTokenRequest(param string, url string, auth model.Auth) (string, error) { log.Infof("PostTokenRequest param: %s, url: %s, ak: %s", param, url, auth.AccessKey) // construct http request req, errNewRequest := http.NewRequest("POST", url, strings.NewReader(param)) @@ -115,21 +120,21 @@ func PostTokenRequest(param string, url string, auth model.Auth) (string, error) // request header req.Header.Set("Content-Type", "application/json") - req.Header.Set(util.DATE_HEADER, time.Now().Format(util.DATE_FORMAT)) + req.Header.Set(util.DateHeader, time.Now().Format(util.DateFormat)) req.Header.Set("Host", req.Host) // calculate signature by safe algorithm sign := util.Sign{ AccessKey: auth.AccessKey, SecretKey: auth.SecretKey, } - authorization, errSign := sign.GetAuthorizationValueWithSign(req) + authorizationVal, errSign := sign.GetAuthorizationValueWithSign(req) if errSign != nil { return "", errSign } - req.Header.Set(AUTHORIZATION, authorization) + req.Header.Set(authorization, authorizationVal) // send http request - response, errDo := DoRequest(req) + response, errDo := doRequest(req) if errDo != nil { return "", errDo } @@ -145,22 +150,21 @@ func PostTokenRequest(param string, url string, auth model.Auth) (string, error) return "", errors.New("request failed, status is " + strconv.Itoa(response.StatusCode)) } log.Infof("response status: %s", response.Status) + return string(body), nil } -// do request -func DoRequest(req *http.Request) (*http.Response, error) { - - tr := &http.Transport{ - TLSClientConfig: TlsConf, +// doRequest: do request. +func doRequest(req *http.Request) (*http.Response, error) { + var tr = &http.Transport{ + TLSClientConfig: TLSConf, } client := &http.Client{Transport: tr} - return client.Do(req) } -// Constructs tls configuration -func TlsConfig() (*tls.Config, error) { +// TLSConfig : Constructs tls configuration. +func TLSConfig() (*tls.Config, error) { appConf, errGetConf := getAPPConf("./conf/app_conf.yaml") if errGetConf != nil { log.Error("parse app_conf.yaml failed") @@ -198,6 +202,7 @@ func getCipherSuites(sslCiphers string) []uint16 { mapValue, ok := cipherSuiteMap[cipherName] if !ok { log.Warn("Not recommended cipher suite.") + return nil } cipherSuiteArr = append(cipherSuiteArr, mapValue) @@ -205,18 +210,19 @@ func getCipherSuites(sslCiphers string) []uint16 { if len(cipherSuiteArr) > 0 { return cipherSuiteArr } + return nil } -// Send Service heartbeat to MEP -func SendHeartBeatRequest(heartBeatData HeartBeatData) (string, error) { +// sendHeartBeatRequest Send Service heartbeat to MEP. +func sendHeartBeatRequest(heartBeatData heartBeatData) (string, error) { req, errNewRequest := http.NewRequest("PUT", heartBeatData.url, strings.NewReader(heartBeatData.data)) if errNewRequest != nil { return "", errNewRequest } - req.Header.Set(AUTHORIZATION, heartBeatData.token.TokenType+" "+heartBeatData.token.AccessToken) + req.Header.Set(authorization, heartBeatData.token.TokenType+" "+heartBeatData.token.AccessToken) - response, errDo := DoRequest(req) + response, errDo := doRequest(req) if errDo != nil { return "", errDo } @@ -228,20 +234,20 @@ func SendHeartBeatRequest(heartBeatData HeartBeatData) (string, error) { } if response.StatusCode == http.StatusOK || response.StatusCode == http.StatusNoContent { return string(body), nil - } else { - return "", errors.New("heartbeat request failed, status is " + strconv.Itoa(response.StatusCode)) } + + return "", errors.New("heartbeat request failed, status is " + strconv.Itoa(response.StatusCode)) } -// Query endpoint from MEP +// SendQueryRequest Query endpoint from MEP. func SendQueryRequest(requestData RequestData) (string, error) { - req, errNewRequest := http.NewRequest("GET", requestData.Url, strings.NewReader(requestData.Data)) + req, errNewRequest := http.NewRequest("GET", requestData.URL, strings.NewReader(requestData.Data)) if errNewRequest != nil { return "", errNewRequest } - req.Header.Set(AUTHORIZATION, requestData.Token.TokenType+" "+requestData.Token.AccessToken) + req.Header.Set(authorization, requestData.Token.TokenType+" "+requestData.Token.AccessToken) - response, errDo := DoRequest(req) + response, errDo := doRequest(req) if errDo != nil { return "", errDo } @@ -253,7 +259,6 @@ func SendQueryRequest(requestData RequestData) (string, error) { } if response.StatusCode == http.StatusOK || response.StatusCode == http.StatusNoContent { return string(body), nil - } else { - return "", errors.New("heartbeat request failed, status is " + strconv.Itoa(response.StatusCode)) } + return "", errors.New("send query request failed, status is " + strconv.Itoa(response.StatusCode)) } diff --git a/src/service/start.go b/src/service/start.go index e47111a..59286e8 100644 --- a/src/service/start.go +++ b/src/service/start.go @@ -14,7 +14,7 @@ * limitations under the License. */ -// start service +// Package service start service package service import ( @@ -26,27 +26,29 @@ import ( log "github.com/sirupsen/logrus" ) -type Ser struct { +// ser Empty service +type ser struct { } -// Returns ser struct -func BeginService() *Ser { - return &Ser{} +// BeginService Returns ser struct. +func BeginService() *ser { + return &ser{} } -// service entrance -func (ser *Ser) Start(confPath string) { - +// Start service entrance +func (ser *ser) Start(confPath string) { var wg = &sync.WaitGroup{} // read app_instance_info.yaml file and transform to AppInstanceInfo object conf, errGetConf := GetAppInstanceConf(confPath) if errGetConf != nil { log.Error("parse app_instance_info.yaml failed.") + return } - _, errAppInst := util.GetAppInstanceId() + _, errAppInst := util.GetAppInstanceID() if errAppInst != nil { log.Error("get app instance id failed.") + return } // signed ak and sk, then request the token diff --git a/src/service/token.go b/src/service/token.go index a5e1c14..14ae033 100644 --- a/src/service/token.go +++ b/src/service/token.go @@ -14,7 +14,7 @@ * limitations under the License. */ -// get token service +// Package service get token service package service import ( @@ -27,28 +27,27 @@ import ( "unsafe" ) -// Request token from mep_auth -func GetMepToken(auth model.Auth) error { - - // construct http request and send - resp, errPostRequest := PostTokenRequest("", config.ServerUrlConfig.MepAuthUrl, auth) +// GetMepToken Request token from mep_auth. +func GetMepToken(auth model.Auth) error { // construct http request and send + resp, errPostRequest := postTokenRequest("", config.ServerURLConfig.MepAuthURL, auth) if errPostRequest != nil { return errPostRequest } // unmarshal resp to object - errJson := json.Unmarshal([]byte(resp), &util.MepToken) + errJSON := json.Unmarshal([]byte(resp), &util.MepToken) // clear resp util.ClearByteArray(*(*[]byte)(unsafe.Pointer(&resp))) - if errJson != nil { - return errJson + if errJSON != nil { + return errJSON } log.Info("get token success.") - //start timer to refresh token + // start timer to refresh token go startRefreshTimer() + return nil } @@ -67,7 +66,7 @@ func startRefreshTimer() { log.Info("timer not yet started") } } - //start timer with latest token expiry value - buffertime + // start timer with latest token expiry value - buffertime util.RefreshTimer = time.NewTimer(time.Duration(util.MepToken.ExpiresIn-util.RefreshTimeBuffer) * time.Second) log.Info("Refresh timer started") go func() { @@ -79,6 +78,7 @@ func startRefreshTimer() { errGetMepToken := GetMepToken(auth) if errGetMepToken != nil { log.Error("Get token failed.") + return } }() diff --git a/src/test/address_test.go b/src/test/address_test.go index 25130c3..de181e2 100644 --- a/src/test/address_test.go +++ b/src/test/address_test.go @@ -14,6 +14,7 @@ * limitations under the License. */ +// Test package package test import ( @@ -33,7 +34,7 @@ func TestGetServerUrl(t *testing.T) { }) defer patch1.Reset() - patch2 := gomonkey.ApplyFunc(util.ValidateDns, func(string) error { + patch2 := gomonkey.ApplyFunc(util.ValidateDNS, func(string) error { return nil }) defer patch2.Reset() @@ -43,6 +44,6 @@ func TestGetServerUrl(t *testing.T) { }) defer patch3.Reset() - _, err := config.GetServerUrl() + _, err := config.GetServerURL() assert.Equal(t, nil, err) } diff --git a/src/test/controller_test.go b/src/test/controller_test.go index 2c1f9be..dbe64fe 100644 --- a/src/test/controller_test.go +++ b/src/test/controller_test.go @@ -14,7 +14,7 @@ * limitations under the License. */ - +//Test package package test import ( diff --git a/src/test/endpointcontroller_test.go b/src/test/endpointcontroller_test.go index 428e222..99e8478 100644 --- a/src/test/endpointcontroller_test.go +++ b/src/test/endpointcontroller_test.go @@ -33,8 +33,8 @@ import ( ) func TestEndpointControllerGet(t *testing.T) { - patch1 := gomonkey.ApplyFunc(config.GetServerUrl, func() (config.ServerUrl, error) { - return config.ServerUrl{MepServiceDiscoveryUrl: "http://127.0.0.1:8088/mep/mec_service_mgmt/v1/services?ser_name="}, nil + patch1 := gomonkey.ApplyFunc(config.GetServerURL, func() (config.ServerURL, error) { + return config.ServerURL{MepServiceDiscoveryURL: "http://127.0.0.1:8088/mep/mec_service_mgmt/v1/services?ser_name="}, nil }) defer patch1.Reset() diff --git a/src/test/heart_test.go b/src/test/heart_test.go index f0aebd9..499bc3e 100644 --- a/src/test/heart_test.go +++ b/src/test/heart_test.go @@ -40,10 +40,10 @@ func TestHeartBeatRequestToMep(t *testing.T) { w.WriteHeader(http.StatusNoContent) })) - patch1 := gomonkey.ApplyFunc(config.GetServerUrl, func() (config.ServerUrl, error) { - return config.ServerUrl{MepHeartBeatUrl: ts.URL}, nil + patch1 := gomonkey.ApplyFunc(config.GetServerURL, func() (config.ServerURL, error) { + return config.ServerURL{MepHeartBeatURL: ts.URL}, nil }) - patch2 := gomonkey.ApplyFunc(service.TlsConfig, func() (*tls.Config, error) { + patch2 := gomonkey.ApplyFunc(service.TLSConfig, func() (*tls.Config, error) { return nil, nil }) diff --git a/src/test/register_test.go b/src/test/register_test.go index a0082ff..273a54a 100644 --- a/src/test/register_test.go +++ b/src/test/register_test.go @@ -50,13 +50,13 @@ func TestRegisterToMep(t *testing.T) { } })) - patch1 := gomonkey.ApplyFunc(config.GetServerUrl, func() (config.ServerUrl, error) { - return config.ServerUrl{MepServerRegisterUrl: ts.URL}, nil + patch1 := gomonkey.ApplyFunc(config.GetServerURL, func() (config.ServerURL, error) { + return config.ServerURL{MepServerRegisterURL: ts.URL}, nil }) - patch2 := gomonkey.ApplyFunc(service.TlsConfig, func() (*tls.Config, error) { + patch2 := gomonkey.ApplyFunc(service.TLSConfig, func() (*tls.Config, error) { return nil, nil }) - patch3 := gomonkey.ApplyFunc(util.GetAppInstanceId, func() (string , error) { + patch3 := gomonkey.ApplyFunc(util.GetAppInstanceID, func() (string , error) { return "", nil }) defer ts.Close() @@ -70,12 +70,12 @@ func TestRegisterToMep(t *testing.T) { t.Error(errGetConf.Error()) } os.Setenv("APPINSTID", "5abe4782-2c70-4e47-9a4e-0ee3a1a0fd1f") - _, errAppInst := util.GetAppInstanceId() + _, errAppInst := util.GetAppInstanceID() if errAppInst != nil { t.Error(errGetConf.Error()) } util.MepToken = model.TokenModel{AccessToken: "akakak", TokenType: "Bear", ExpiresIn: 3600} - util.AppInstanceId = "5abe4782-2c70-4e47-9a4e-0ee3a1a0fd1f" + util.AppInstanceID = "5abe4782-2c70-4e47-9a4e-0ee3a1a0fd1f" _, errRegister := service.RegisterToMep(conf, &waitRoutineFinish) if errRegister != nil { diff --git a/src/test/token_test.go b/src/test/token_test.go index e63830e..5a1f7b5 100644 --- a/src/test/token_test.go +++ b/src/test/token_test.go @@ -51,11 +51,11 @@ func TestGetMepToken(t *testing.T) { defer ts.Close() api := ts.URL - patch1 := gomonkey.ApplyFunc(config.GetServerUrl, func() (config.ServerUrl, error) { - return config.ServerUrl{MepAuthUrl: api}, nil + patch1 := gomonkey.ApplyFunc(config.GetServerURL, func() (config.ServerURL, error) { + return config.ServerURL{MepAuthURL: api}, nil }) - config.ServerUrlConfig, _ = config.GetServerUrl() - patch2 := gomonkey.ApplyFunc(service.TlsConfig, func() (*tls.Config, error) { + config.ServerURLConfig, _ = config.GetServerURL() + patch2 := gomonkey.ApplyFunc(service.TLSConfig, func() (*tls.Config, error) { return nil, nil }) diff --git a/src/test/util_test.go b/src/test/util_test.go index a6ae45c..5679d99 100644 --- a/src/test/util_test.go +++ b/src/test/util_test.go @@ -34,16 +34,16 @@ func TestClearByteArray(t *testing.T) { } func TestReadTokenFromEnvironment1(t *testing.T) { - os.Setenv("AK", "ZXhhbXBsZUFL") - os.Setenv("SK", "ZXhhbXBsZVNL") + os.Setenv("ak", "ZXhhbXBsZUFL") + os.Setenv("sk", "ZXhhbXBsZVNL") err := util.ReadTokenFromEnvironment() - assert.EqualValues(t, 0, len(os.Getenv("AK"))) - assert.EqualValues(t, 0, len(os.Getenv("SK"))) + assert.EqualValues(t, 0, len(os.Getenv("ak"))) + assert.EqualValues(t, 0, len(os.Getenv("sk"))) assert.NoError(t, err, "No error is expected") } func TestReadTokenFromEnvironment2(t *testing.T) { - os.Setenv("AK", "ZXhhbXBsZUFL") + os.Setenv("ak", "ZXhhbXBsZUFL") err := util.ReadTokenFromEnvironment() Expected := "ak and sk keys should be set in env variable" assert.EqualError(t, err, Expected) @@ -52,12 +52,12 @@ func TestReadTokenFromEnvironment2(t *testing.T) { func TestGetAppInstanceIdDecodeFailed(t *testing.T) { os.Setenv("APPINSTID", "b1fe5b4d-76a7-4a52-b60f-932fde7c8d57") - _, err := util.GetAppInstanceId() + _, err := util.GetAppInstanceID() assert.Equal(t, err, nil) } func TestGetAppInstanceIdNotSet(t *testing.T) { - _, err := util.GetAppInstanceId() + _, err := util.GetAppInstanceID() Expected := "appInstanceId should be set in env variable" assert.EqualError(t, err, Expected) } diff --git a/src/test/validation_test.go b/src/test/validation_test.go index c6838a3..b495ad0 100644 --- a/src/test/validation_test.go +++ b/src/test/validation_test.go @@ -25,11 +25,11 @@ import ( func TestValidateIp(t *testing.T) { convey.Convey("ValidateDns", t, func() { convey.Convey("ValidateIpSuccess", func() { - convey.So(util.ValidateDns("mep-api-gw"), convey.ShouldBeNil) + convey.So(util.ValidateDNS("mep-api-gw"), convey.ShouldBeNil) }) convey.Convey("ValidateDnsFail", func() { - convey.So(util.ValidateDns("127.0.0."), convey.ShouldNotBeNil) + convey.So(util.ValidateDNS("127.0.0."), convey.ShouldNotBeNil) }) }) } diff --git a/src/util/sign.go b/src/util/sign.go index beb6c22..7a1528b 100644 --- a/src/util/sign.go +++ b/src/util/sign.go @@ -14,7 +14,7 @@ * limitations under the License. */ -// signature service +// Package util signature service package util import ( @@ -34,20 +34,22 @@ import ( ) const ( - SEPARATOR string = "/" - LINE_SEPARATOR string = "\n" - DATE_FORMAT string = "20060102T150405Z" - ALGORITHM string = "SDK-HMAC-SHA256" - DATE_HEADER string = "x-sdk-date" + separator string = "/" + lineSeparator string = "\n" + // DateFormat Date format + DateFormat string = "20060102T150405Z" + algorithm string = "SDK-HMAC-SHA256" + // DateHeader Date header. + DateHeader string = "x-sdk-date" ) - +//Sign Signature type Sign struct { SecretKey *[]byte AccessKey string } -// Returns authorization value with signature +// GetAuthorizationValueWithSign Returns authorization value with signature. func (sig *Sign) GetAuthorizationValueWithSign(req *http.Request) (string, error) { signature, errGetSignature := sig.GetSignature(req) if errGetSignature != nil { @@ -57,7 +59,7 @@ func (sig *Sign) GetAuthorizationValueWithSign(req *http.Request) (string, error return getAuthorizationHeaderValue(signature, sig.AccessKey, getSignedHeaders(req)), nil } -// get signature from request +// GetSignature get signature from request. func (sig *Sign) GetSignature(req *http.Request) (string, error) { if req == nil { return "", errors.New("request is nil") @@ -68,7 +70,7 @@ func (sig *Sign) GetSignature(req *http.Request) (string, error) { return "", errGetCanonicalRequest } // create string to sign - stringToSign, errGetStringToSign := getStringToSign(canonicalRequest, req.Header.Get(DATE_HEADER)) + stringToSign, errGetStringToSign := getStringToSign(canonicalRequest, req.Header.Get(DateHeader)) if errGetStringToSign != nil { return "", errGetStringToSign } @@ -80,14 +82,12 @@ func (sig *Sign) GetSignature(req *http.Request) (string, error) { return signature, nil } -// construct canonical request and return -func getCanonicalRequest(req *http.Request) (string, error) { - - // begin construct canonical request +// construct canonical request and return. +func getCanonicalRequest(req *http.Request) (string, error) { // begin construct canonical request // request method method := req.Method // request uri - uri := getCanonicalUri(req) + uri := getCanonicalURI(req) // query string query := getCanonicalQueryString(req) // request headers @@ -100,13 +100,13 @@ func getCanonicalRequest(req *http.Request) (string, error) { return "", errGetRequestBodyHash } // construct complete - return strings.Join([]string{method, uri, query, headersReq, headersSign, hexEncodeBody}, LINE_SEPARATOR), nil + return strings.Join([]string{method, uri, query, headersReq, headersSign, hexEncodeBody}, lineSeparator), nil } -// construct canonical uri can return -func getCanonicalUri(req *http.Request) string { +// construct canonical uri can return. +func getCanonicalURI(req *http.Request) string { // split uri to []string - paths := strings.Split(req.URL.Path, SEPARATOR) + paths := strings.Split(req.URL.Path, separator) var uris []string for _, path := range paths { // ignore the empty string and relative path string @@ -116,12 +116,12 @@ func getCanonicalUri(req *http.Request) string { uris = append(uris, url.QueryEscape(path)) } // create canonical uri - canonicalUri := SEPARATOR + strings.Join(uris, SEPARATOR) + canonicalUri := separator + strings.Join(uris, separator) // check the uri suffix - if strings.HasSuffix(canonicalUri, SEPARATOR) { + if strings.HasSuffix(canonicalUri, separator) { return canonicalUri } else { - return canonicalUri + SEPARATOR + return canonicalUri + separator } } @@ -154,7 +154,7 @@ func getCanonicalHeaders(req *http.Request) string { headers = append(headers, strings.ToLower(key) + ":" + strings.Join(val, ",")) } sort.Strings(headers) - return strings.Join(headers, LINE_SEPARATOR) + LINE_SEPARATOR + return strings.Join(headers, lineSeparator) + lineSeparator } // return signed headers list as string @@ -217,7 +217,7 @@ func getStringToSign(canonicalRequest string, dateTime string) (string, error) { return "", errHexEncode } // construct complete - return strings.Join([]string{ALGORITHM, dateTime, hexEncodeReq}, LINE_SEPARATOR), nil + return strings.Join([]string{algorithm, dateTime, hexEncodeReq}, lineSeparator), nil } // calculate the signature with string to sign and secret key. @@ -253,5 +253,5 @@ func getAuthorizationHeaderValue(signature, accessKey, signedHeaders string) str // signature sign := "Signature=" + signature // construct complete - return strings.Join([]string{ALGORITHM, access, headers, sign}, " ") + return strings.Join([]string{algorithm, access, headers, sign}, " ") } diff --git a/src/util/util.go b/src/util/util.go index 8a27c54..f0f8835 100644 --- a/src/util/util.go +++ b/src/util/util.go @@ -14,7 +14,7 @@ * limitations under the License. */ -// Clear util +// Package util utility package package util import ( @@ -25,34 +25,34 @@ import ( "time" ) -//App configuration properties -type AppConfigProperties map[string]*[]byte +// appConfigProperties App configuration properties. +type appConfigProperties map[string]*[]byte -//Application configurations -var AppConfig = AppConfigProperties{} +// AppConfig Application configurations. +var AppConfig = appConfigProperties{} -// Token +// MepToken Token. var MepToken = model.TokenModel{} -//Mark initial token has been received +// FirstToken Mark initial token has been received. var FirstToken = false -//App instance ID from configuration -var AppInstanceId string +// AppInstanceID App instance ID from configuration. +var AppInstanceID string -//Refresh token timer +// RefreshTimer Refresh token timer. var RefreshTimer *time.Timer -//Timer buffer 5 sec +// RefreshTimeBuffer Timer buffer 5 sec. const RefreshTimeBuffer = 5 const ( - AK string = "AK" - SK string = "SK" - APPINSTID string = "APPINSTID" + ak string = "ak" + sk string = "sk" + appInstID string = "APPINSTID" ) -// Clears byte array +// ClearByteArray Clears byte array. func ClearByteArray(data []byte) { if data == nil { return @@ -62,44 +62,47 @@ func ClearByteArray(data []byte) { } } -// clear [string, *[]byte] map, called only in error case +// ClearMap clear [string, *[]byte] map, called only in error case. func ClearMap() { for _, element := range AppConfig { ClearByteArray(*element) } } -//read and clearing the variable from the environment +// ReadTokenFromEnvironment read and clearing the variable from the environment. func ReadTokenFromEnvironment() error { - //clean the environment - defer os.Unsetenv(AK) - defer os.Unsetenv(SK) + // clean the environment + defer os.Unsetenv(ak) + defer os.Unsetenv(sk) - ak := os.Getenv(AK) - sk := os.Getenv(SK) + akVal := os.Getenv(ak) + skVal := os.Getenv(sk) - if len(ak) == 0 || len(sk) == 0 { + if len(akVal) == 0 || len(skVal) == 0 { err := errors.New("ak and sk keys should be set in env variable") log.Error("Keys should not be empty") + return err } - akByte := []byte(ak) + akByte := []byte(akVal) AppConfig["ACCESS_KEY"] = &akByte - skByte := []byte(sk) + skByte := []byte(skVal) AppConfig["SECRET_KEY"] = &skByte log.Infof("Ak: %s", akByte) + return nil } -//Read application instanceId -func GetAppInstanceId() (string, error) { - defer os.Unsetenv(APPINSTID) - instId := os.Getenv(APPINSTID) - if len(instId) == 0 { +// GetAppInstanceID Read application instanceId. +func GetAppInstanceID() (string, error) { + defer os.Unsetenv(appInstID) + instID := os.Getenv(appInstID) + if len(instID) == 0 { err := errors.New("appInstanceId should be set in env variable") log.Error("appInstanceId must be set") + return "", err } - AppInstanceId = instId - return instId, nil + AppInstanceID = instID + return instID, nil } diff --git a/src/util/validation.go b/src/util/validation.go index a0a104e..381c5f6 100644 --- a/src/util/validation.go +++ b/src/util/validation.go @@ -14,49 +14,49 @@ * limitations under the License. */ -// validation util +// Package util utility package util import ( "errors" - "github.com/go-playground/validator/v10" "net" "regexp" + + "github.com/go-playground/validator/v10" ) const ( - //IP_PATTERN string = `^[a-z][a-z-]{0,126}[a-z]$` - PORT_PATTERN string = `^([1-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$` - //AK_PATTERN string = `^\w{20}$` - //SK_PATTERN string = `^\w{64}$` - DOMAIN_PATTERN string = `^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$` - DNS_PATTERN string = `^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$` - maxHostNameLen = 253 + // PortPattern Regular expression for Port. + PortPattern string = `^([1-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$` + // domainPattern Regular expression for Domain. + domainPattern string = `^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$` + dnsPattern string = `^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$` + maxHostNameLen = 253 ) -// Validates Ip address -func ValidateDns(ip string) error { +// ValidateDNS Validates Ip address. +func ValidateDNS(ip string) error { ipv := net.ParseIP(ip) if ipv != nil && (ipv.IsMulticast() || ipv.Equal(net.IPv4bcast)) { return errors.New("invalid dns ip") } - if ipv != nil { return nil } - return ValidateByPattern(DNS_PATTERN, ip) + return ValidateByPattern(dnsPattern, ip) } -// Validates domain name +// ValidateDomainName Validates domain name. func ValidateDomainName(name string) error { if len(name) == 0 || len(name) > maxHostNameLen { return errors.New("validate domain name failed") } - return ValidateByPattern(DOMAIN_PATTERN, name) + + return ValidateByPattern(domainPattern, name) } -// Validates given string with pattern +// ValidateByPattern Validates given string with pattern. func ValidateByPattern(pattern string, param string) error { res, errMatch := regexp.MatchString(pattern, param) if errMatch != nil { @@ -65,10 +65,11 @@ func ValidateByPattern(pattern string, param string) error { if !res { return errors.New("validate failed") } + return nil } -// Validates UUID +// ValidateUUID Validates UUID. func ValidateUUID(id string) error { if len(id) != 0 { validate := validator.New() @@ -79,6 +80,6 @@ func ValidateUUID(id string) error { } else { return errors.New("UUID validate failed") } + return nil } - -- Gitee