本文整理汇总了Golang中github.com/ARGOeu/argo-web-api/utils/mongo.CloseSession函数的典型用法代码示例。如果您正苦于以下问题:Golang CloseSession函数的具体用法?Golang CloseSession怎么用?Golang CloseSession使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了CloseSession函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestListFactors
// TestListFactors will run unit tests against the List function
func (suite *FactorsTestSuite) TestListFactors() {
suite.respFactorsList = `<root>
<Factor site="CETA-GRID" weight="5406"></Factor>
<Factor site="CFP-IST" weight="1019"></Factor>
<Factor site="CIEMAT-LCG2" weight="14595"></Factor>
</root>`
// Prepare the request object
request, _ := http.NewRequest("GET", "/api/v2/factors", strings.NewReader(""))
// add the authentication token which is seeded in testdb
request.Header.Set("x-api-key", "secret")
request.Header.Set("Accept", "application/xml")
// Execute the request in the controller
response := httptest.NewRecorder()
suite.router.ServeHTTP(response, request)
code := response.Code
output := response.Body.String()
suite.Equal(200, code, "Something went wrong")
suite.Equal(suite.respFactorsList, string(output), "Response body mismatch")
// Prepare new request object
request, _ = http.NewRequest("GET", "/api/v2/factors", strings.NewReader(""))
// add the authentication token which is seeded in testdb
request.Header.Set("x-api-key", "wrongkey")
request.Header.Set("Accept", "application/xml")
// Execute the request in the controller
response = httptest.NewRecorder()
suite.router.ServeHTTP(response, request)
code = response.Code
output = response.Body.String()
suite.Equal(401, code, "Should have gotten return code 401 (Unauthorized)")
suite.Equal(suite.respUnauthorized, string(output), "Should have gotten reply Unauthorized")
// Remove the test data from core db not to contaminate other tests
// Open session to core mongo
session, err := mongo.OpenSession(suite.cfg.MongoDB)
if err != nil {
panic(err)
}
defer mongo.CloseSession(session)
// Open collection authentication
c := session.DB(suite.cfg.MongoDB.Db).C("authentication")
// Remove the specific entries inserted during this test
c.Remove(bson.M{"name": "John Doe"})
// Remove the test data from tenant db not to contaminate other tests
// Open session to tenant mongo
session, err = mgo.Dial(suite.tenantcfg.Host)
if err != nil {
panic(err)
}
defer mongo.CloseSession(session)
// Open collection authentication
c = session.DB(suite.tenantcfg.Db).C("weights")
// Remove the specific entries inserted during this test
c.Remove(bson.M{"name": "CIEMAT-LCG2"})
c.Remove(bson.M{"name": "CFP-IST"})
c.Remove(bson.M{"name": "CETA-GRID"})
}
示例2: List
// List returns a list of factors (weights) per endpoint group (i.e. site)
func List(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("")
err := error(nil)
contentType := "text/xml"
charset := "utf-8"
//STANDARD DECLARATIONS END
contentType, err = respond.ParseAcceptHeader(r)
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
if err != nil {
code = http.StatusNotAcceptable
output, _ = respond.MarshalContent(respond.NotAcceptableContentType, contentType, "", " ")
return code, h, output, err
}
tenantDbConfig, err := authentication.AuthenticateTenant(r.Header, cfg)
if err != nil {
output = []byte(http.StatusText(http.StatusUnauthorized))
code = http.StatusUnauthorized //If wrong api key is passed we return UNAUTHORIZED http status
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
session, err := mongo.OpenSession(tenantDbConfig)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
defer mongo.CloseSession(session)
results := []FactorsOutput{}
err = mongo.Find(session, tenantDbConfig.Db, "weights", nil, "name", &results)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
output, err = createView(results, contentType) //Render the results into XML format
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
mongo.CloseSession(session)
return code, h, output, err
}
示例3: List
// List returns a list of factors (weights) per endpoint group (i.e. site)
func List(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("")
err := error(nil)
contentType := "text/xml"
charset := "utf-8"
//STANDARD DECLARATIONS END
contentType, err = respond.ParseAcceptHeader(r)
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
if err != nil {
code = http.StatusNotAcceptable
output, _ = respond.MarshalContent(respond.NotAcceptableContentType, contentType, "", " ")
return code, h, output, err
}
// Grab Tenant DB configuration from context
tenantDbConfig := context.Get(r, "tenant_conf").(config.MongoConfig)
session, err := mongo.OpenSession(tenantDbConfig)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
defer mongo.CloseSession(session)
results := []FactorsOutput{}
err = mongo.Find(session, tenantDbConfig.Db, "weights", nil, "name", &results)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
output, err = createView(results, contentType) //Render the results into XML format
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
mongo.CloseSession(session)
return code, h, output, err
}
示例4: AuthenticateTenant
// AuthenticateTenant is used to find which tenant the user making the requests
// belongs to and return the database configuration for that specific tenant.
// If the api-key in the request is not found in any tenant an empty configuration is
// returned along with an error
func AuthenticateTenant(h http.Header, cfg config.Config) (config.MongoConfig, error) {
session, err := mongo.OpenSession(cfg.MongoDB)
if err != nil {
return config.MongoConfig{}, err
}
defer mongo.CloseSession(session)
apiKey := h.Get("x-api-key")
query := bson.M{"users.api_key": apiKey}
projection := bson.M{"_id": 0, "name": 1, "db_conf": 1, "users": 1}
var results []map[string][]config.MongoConfig
mongo.FindAndProject(session, cfg.MongoDB.Db, "tenants", query, projection, "server", &results)
if len(results) == 0 {
return config.MongoConfig{}, errors.New("Unauthorized")
}
mongoConf := results[0]["db_conf"][0]
// mongoConf := config.MongoConfig{
// Host: conf["server"].(string),
// Port: conf["port"].(int),
// Db: conf["database"].(string),
// Username: conf["username"].(string),
// Password: conf["password"].(string),
// Store: conf["store"].(string),
// }
for _, user := range results[0]["users"] {
if user.ApiKey == apiKey {
mongoConf.User = user.User
mongoConf.Email = user.Email
}
}
return mongoConf, nil
}
示例5: SetupTest
// SetupTest will bootstrap and provide the testing environment
func (suite *FactorsTestSuite) SetupTest() {
// Connect to mongo coredb
session, err := mongo.OpenSession(suite.cfg.MongoDB)
defer mongo.CloseSession(session)
if err != nil {
panic(err)
}
// Add authentication token to mongo coredb
seedAuth := bson.M{"name": "TEST",
"db_conf": []bson.M{bson.M{"server": "127.0.0.1", "port": 27017, "database": "AR_test"}},
"users": []bson.M{bson.M{"name": "Jack Doe", "email": "[email protected]", "api_key": "secret", "roles": []string{"viewer"}}}}
_ = mongo.Insert(session, suite.cfg.MongoDB.Db, "tenants", seedAuth)
// Add a few factors in collection
c := session.DB(suite.tenantcfg.Db).C("weights")
c.Insert(bson.M{"hepspec": 14595, "name": "CIEMAT-LCG2"})
c.Insert(bson.M{"hepspec": 1019, "name": "CFP-IST"})
c.Insert(bson.M{"hepspec": 5406, "name": "CETA-GRID"})
c = session.DB(suite.cfg.MongoDB.Db).C("roles")
c.Insert(
bson.M{
"resource": "factors.list",
"roles": []string{"editor", "viewer"},
})
}
示例6: ListOne
// ListOne handles the listing of one specific profile based on its given id
func ListOne(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("")
err := error(nil)
charset := "utf-8"
//STANDARD DECLARATIONS END
// Set Content-Type response Header value
contentType := r.Header.Get("Accept")
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
vars := mux.Vars(r)
// Grab Tenant DB configuration from context
tenantDbConfig := context.Get(r, "tenant_conf").(config.MongoConfig)
// Open session to tenant database
session, err := mongo.OpenSession(tenantDbConfig)
defer mongo.CloseSession(session)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
filter := bson.M{"id": vars["ID"]}
// Retrieve Results from database
results := []MongoInterface{}
err = mongo.Find(session, tenantDbConfig.Db, "metric_profiles", filter, "name", &results)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
// Check if nothing found
if len(results) < 1 {
output, _ = respond.MarshalContent(respond.NotFound, contentType, "", " ")
code = 404
return code, h, output, err
}
// Create view of the results
output, err = createListView(results, "Success", code) //Render the results into JSON
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
示例7: List
// List the existing metric profiles for the tenant making the request
// Also there is an optional url param "name" to filter results by
func List(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("")
err := error(nil)
charset := "utf-8"
//STANDARD DECLARATIONS END
// Set Content-Type response Header value
contentType := r.Header.Get("Accept")
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
urlValues := r.URL.Query()
// Grab Tenant DB configuration from context
tenantDbConfig := context.Get(r, "tenant_conf").(config.MongoConfig)
// Open session to tenant database
session, err := mongo.OpenSession(tenantDbConfig)
defer mongo.CloseSession(session)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
// Retrieve Results from database
var filter interface{}
if len(urlValues["name"]) > 0 {
filter = bson.M{"name": urlValues["name"][0]}
} else {
filter = nil
}
results := []MongoInterface{}
err = mongo.Find(session, tenantDbConfig.Db, "metric_profiles", filter, "name", &results)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
// Create view of the results
output, err = createListView(results, "Success", code) //Render the results into JSON
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
示例8: routeGroup
func routeGroup(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("")
err := error(nil)
charset := "utf-8"
//STANDARD DECLARATIONS END
// Handle response format based on Accept Header
contentType := r.Header.Get("Accept")
vars := mux.Vars(r)
// Grab Tenant DB configuration from context
tenantcfg := context.Get(r, "tenant_conf").(config.MongoConfig)
session, err := mongo.OpenSession(tenantcfg)
defer mongo.CloseSession(session)
if err != nil {
return code, h, output, err
}
requestedReport := reports.MongoInterface{}
err = mongo.FindOne(session, tenantcfg.Db, "reports", bson.M{"info.name": vars["report_name"]}, &requestedReport)
if err != nil {
code = http.StatusNotFound
message := "The report with the name " + vars["report_name"] + " does not exist"
output, err := createErrorMessage(message, code, contentType) //Render the response into XML or JSON
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
selectedGroupType := requestedReport.DetermineGroupType(vars["group_type"])
if selectedGroupType == "endpoint" {
if vars["lgroup_type"] == "" {
vars["lgroup_type"] = vars["group_type"]
vars["lgroup_name"] = vars["group_name"]
vars["group_type"] = ""
vars["group_name"] = ""
}
return ListEndpointGroupResults(r, cfg)
} else if selectedGroupType == "group" {
return ListSuperGroupResults(r, cfg)
}
code = http.StatusNotFound
message := "The report " + vars["report_name"] + " does not define any group type: " + vars["group_type"]
output, err = createErrorMessage(message, code, contentType) //Render the response into XML or JSON
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
示例9: List
func List(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("")
err := error(nil)
contentType := "text/xml"
charset := "utf-8"
//STANDARD DECLARATIONS END
//Read the search values
urlValues := r.URL.Query()
//Searchig is based on name and namespace
input := AvailabilityProfileSearch{
urlValues["name"],
urlValues["namespace"],
}
results := []AvailabilityProfileOutput{}
session, err := mongo.OpenSession(cfg)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
query := readOne(input)
if len(input.Name) == 0 {
query = nil //If no name and namespace is provided then we have to retrieve all profiles thus we send nil into db query
}
err = mongo.Find(session, cfg.MongoDB.Db, "aps", query, "_id", &results)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
mongo.CloseSession(session)
output, err = createView(results) //Render the results into XML format
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
示例10: Create
//Create a new metric profile
func Create(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("")
err := error(nil)
charset := "utf-8"
//STANDARD DECLARATIONS END
// Set Content-Type response Header value
contentType := r.Header.Get("Accept")
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
// Grab Tenant DB configuration from context
tenantDbConfig := context.Get(r, "tenant_conf").(config.MongoConfig)
session, err := mongo.OpenSession(tenantDbConfig)
defer mongo.CloseSession(session)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
incoming := MongoInterface{}
// Try ingest request body
body, err := ioutil.ReadAll(io.LimitReader(r.Body, cfg.Server.ReqSizeLimit))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
// Parse body json
if err := json.Unmarshal(body, &incoming); err != nil {
output, _ = respond.MarshalContent(respond.BadRequestBadJSON, contentType, "", " ")
code = 400
return code, h, output, err
}
// Generate new id
incoming.ID = mongo.NewUUID()
err = mongo.Insert(session, tenantDbConfig.Db, "metric_profiles", incoming)
if err != nil {
panic(err)
}
// Create view of the results
output, err = createRefView(incoming, "Metric Profile successfully created", 201, r) //Render the results into JSON
code = 201
return code, h, output, err
}
示例11: GetMetricResult
// GetMetricResult returns the detailed message from a probe
func GetMetricResult(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("")
err := error(nil)
charset := "utf-8"
//STANDARD DECLARATIONS END
// Set Content-Type response Header value
contentType := r.Header.Get("Accept")
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
// Grab Tenant DB configuration from context
tenantDbConfig := context.Get(r, "tenant_conf").(config.MongoConfig)
// Parse the request into the input
urlValues := r.URL.Query()
vars := mux.Vars(r)
input := metricResultQuery{
EndpointName: vars["endpoint_name"],
MetricName: vars["metric_name"],
ExecTime: urlValues.Get("exec_time"),
}
session, err := mongo.OpenSession(tenantDbConfig)
defer mongo.CloseSession(session)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
result := metricResultOutput{}
metricCol := session.DB(tenantDbConfig.Db).C("status_metrics")
// Query the detailed metric results
err = metricCol.Find(prepQuery(input)).One(&result)
output, err = createMetricResultView(result, contentType)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
return code, h, output, err
}
示例12: routeCheckGroup
func routeCheckGroup(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("group check")
err := error(nil)
contentType := "application/xml"
charset := "utf-8"
//STANDARD DECLARATIONS END
// Handle response format based on Accept Header
// Default is application/xml
format := r.Header.Get("Accept")
if strings.EqualFold(format, "application/json") {
contentType = "application/json"
}
vars := mux.Vars(r)
tenantcfg, err := authentication.AuthenticateTenant(r.Header, cfg)
if err != nil {
return code, h, output, err
}
session, err := mongo.OpenSession(tenantcfg)
defer mongo.CloseSession(session)
if err != nil {
return code, h, output, err
}
result := reports.MongoInterface{}
err = mongo.FindOne(session, tenantcfg.Db, "reports", bson.M{"info.name": vars["report_name"]}, &result)
if err != nil {
message := "The report with the name " + vars["report_name"] + " does not exist"
output, err := createMessageOUT(message, format) //Render the response into XML or JSON
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
if vars["group_type"] != result.GetEndpointGroupType() {
message := "The report " + vars["report_name"] + " does not define endpoint group type: " + vars["group_type"]
output, err := createMessageOUT(message, format) //Render the response into XML or JSON
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
return ListEndpointTimelines(r, cfg)
}
示例13: routeCheckGroup
func routeCheckGroup(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("group check")
err := error(nil)
charset := "utf-8"
//STANDARD DECLARATIONS END
// Handle response format based on Accept Header
contentType := r.Header.Get("Accept")
vars := mux.Vars(r)
// Grab Tenant DB configuration from context
tenantcfg := context.Get(r, "tenant_conf").(config.MongoConfig)
session, err := mongo.OpenSession(tenantcfg)
defer mongo.CloseSession(session)
if err != nil {
code = http.StatusInternalServerError
output, _ = respond.MarshalContent(respond.InternalServerErrorMessage, contentType, "", " ")
return code, h, output, err
}
result := reports.MongoInterface{}
err = mongo.FindOne(session, tenantcfg.Db, "reports", bson.M{"info.name": vars["report_name"]}, &result)
if err != nil {
code = http.StatusNotFound
message := "The report with the name " + vars["report_name"] + " does not exist"
output, err := createMessageOUT(message, code, contentType) //Render the response into XML or JSON
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
if vars["group_type"] != result.GetEndpointGroupType() {
code = http.StatusNotFound
message := "The report " + vars["report_name"] + " does not define endpoint group type: " + vars["group_type"]
output, err := createMessageOUT(message, code, contentType) //Render the response into XML or JSON
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
return ListMetricTimelines(r, cfg)
}
示例14: List
func List(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("")
err := error(nil)
contentType := "text/xml"
charset := "utf-8"
//STANDARD DECLARATIONS END
session, err := mongo.OpenSession(cfg)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
results := []FactorsOutput{}
err = mongo.Find(session, "AR", "hepspec", nil, "p", &results)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
output, err = createView(results) //Render the results into XML format
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
mongo.CloseSession(session)
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
return code, h, output, err
}
示例15: Create
//Create a new metric profile
func Create(r *http.Request, cfg config.Config) (int, http.Header, []byte, error) {
//STANDARD DECLARATIONS START
code := http.StatusOK
h := http.Header{}
output := []byte("")
err := error(nil)
charset := "utf-8"
//STANDARD DECLARATIONS END
contentType, err := respond.ParseAcceptHeader(r)
h.Set("Content-Type", fmt.Sprintf("%s; charset=%s", contentType, charset))
if err != nil {
code = http.StatusNotAcceptable
output, _ = respond.MarshalContent(respond.NotAcceptableContentType, contentType, "", " ")
return code, h, output, err
}
tenantDbConfig, err := authentication.AuthenticateTenant(r.Header, cfg)
if err != nil {
output, _ = respond.MarshalContent(respond.UnauthorizedMessage, contentType, "", " ")
code = http.StatusUnauthorized //If wrong api key is passed we return UNAUTHORIZED http status
return code, h, output, err
}
session, err := mongo.OpenSession(tenantDbConfig)
defer mongo.CloseSession(session)
if err != nil {
code = http.StatusInternalServerError
return code, h, output, err
}
incoming := OpsProfile{}
// Try ingest request body
body, err := ioutil.ReadAll(io.LimitReader(r.Body, cfg.Server.ReqSizeLimit))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
// Parse body json
if err := json.Unmarshal(body, &incoming); err != nil {
output, _ = respond.MarshalContent(respond.BadRequestBadJSON, contentType, "", " ")
code = 400
return code, h, output, err
}
// Validate States
var errList []string
errList = append(errList, incoming.validateDuplicates()...)
errList = append(errList, incoming.validateStates()...)
errList = append(errList, incoming.validateMentions()...)
if len(errList) > 0 {
output, err = createErrView("Validation Error", 422, errList)
code = 422
return code, h, output, err
}
// Generate new id
incoming.ID = mongo.NewUUID()
err = mongo.Insert(session, tenantDbConfig.Db, "operations_profiles", incoming)
if err != nil {
panic(err)
}
// Create view of the results
output, err = createRefView(incoming, "Operations Profile successfully created", 201, r) //Render the results into JSON
code = 201
return code, h, output, err
}