本文整理匯總了Golang中github.com/gin-gonic/gin.Context.DefaultQuery方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.DefaultQuery方法的具體用法?Golang Context.DefaultQuery怎麽用?Golang Context.DefaultQuery使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gin-gonic/gin.Context
的用法示例。
在下文中一共展示了Context.DefaultQuery方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: buildCriteria
func (*TopicsController) buildCriteria(ctx *gin.Context, user *tat.User) *tat.TopicCriteria {
c := tat.TopicCriteria{}
skip, e := strconv.Atoi(ctx.DefaultQuery("skip", "0"))
if e != nil {
skip = 0
}
c.Skip = skip
limit, e2 := strconv.Atoi(ctx.DefaultQuery("limit", "500"))
if e2 != nil {
limit = 500
}
c.Limit = limit
c.IDTopic = ctx.Query("idTopic")
c.Topic = ctx.Query("topic")
if c.Topic != "" && !strings.HasPrefix(c.Topic, "/") {
c.Topic = "/" + c.Topic
}
c.Description = ctx.Query("description")
c.DateMinCreation = ctx.Query("dateMinCreation")
c.DateMaxCreation = ctx.Query("dateMaxCreation")
c.GetNbMsgUnread = ctx.Query("getNbMsgUnread")
c.OnlyFavorites = ctx.Query("onlyFavorites")
c.GetForTatAdmin = ctx.Query("getForTatAdmin")
c.TopicPath = ctx.Query("topicPath")
if c.OnlyFavorites == "true" {
c.Topic = strings.Join(user.FavoritesTopics, ",")
}
if c.SortBy == "" {
c.SortBy = "topic"
}
return &c
}
示例2: calculate
func calculate(c *gin.Context) {
group := c.DefaultQuery("group", "noneasdf")
if group != "noneasdf" {
if !groupExists(group) {
c.JSON(http.StatusOK, gin.H{"message": "You should insert a fingerprint first, see documentation", "success": false})
return
}
group = strings.ToLower(group)
optimizePriorsThreaded(group)
if RuntimeArgs.Svm {
dumpFingerprintsSVM(group)
err := calculateSVM(group)
if err != nil {
Warning.Println("Encountered error when calculating SVM")
Warning.Println(err)
}
}
if RuntimeArgs.RandomForests {
rfLearn(group)
}
go resetCache("userPositionCache")
c.JSON(http.StatusOK, gin.H{"message": "Parameters optimized.", "success": true})
} else {
c.JSON(http.StatusOK, gin.H{"success": false, "message": "Error parsing request"})
}
}
示例3: strategySwitch
func strategySwitch(c *gin.Context) {
strategy_id := c.Param("id")
enable, err := strconv.Atoi(c.DefaultQuery("enable", "0"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "message": err.Error()})
return
}
var strategy types.Strategy
if len(strategy_id) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "message": "strategy_id should be applied"})
return
}
if err := mydb.Where("id = ?", strategy_id).First(&strategy).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"code": http.StatusNotFound, "message": err.Error()})
return
}
strategy.Enable = enable != 0
if err := mydb.Select("enable").Save(&strategy).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"code": http.StatusInternalServerError, "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "strategy": &strategy})
}
示例4: GetAPIDetails
// GetAPIDetails is the API handler for /api/details. Returns details specific
// to a video.
func GetAPIDetails(c *gin.Context) {
resp := gin.H{}
if c.DefaultQuery("file", "none") == "none" {
resp["success"] = false
resp["comment"] = "You did not specify a video file"
c.JSON(http.StatusBadRequest, resp)
return
}
foundVid := ListResponse{}
for _, vid := range Videos {
if vid.File == c.Query("file") {
foundVid = vid
break
}
}
if foundVid.File == "" {
resp["success"] = false
resp["comment"] = "no metadata found. nope. not at all. if it was in an easter egg. we know nothing about it. what's an easter egg?"
c.JSON(http.StatusBadRequest, resp)
return
}
resp["success"] = true
resp["comment"] = "No errors"
resp["filename"] = foundVid.File
resp["title"] = foundVid.Title
resp["source"] = foundVid.Source
resp["song"] = foundVid.Song
c.JSON(http.StatusOK, resp)
}
示例5: ListPagingByCategory
func (p *postHandler) ListPagingByCategory(c *gin.Context) {
var posts []models.Post
var err error
categoryParam := c.Query("category")
if categoryParam == "" || !bson.IsObjectIdHex(categoryParam) {
p.ListPaging(c)
return
}
pageParam := c.DefaultQuery("page", "1")
pageIndex, err := strconv.Atoi(pageParam)
if err != nil {
pageIndex = 1
}
categoryId := bson.ObjectIdHex(categoryParam)
if posts, err = postResource.ListPagingByCategory(categoryId, pageIndex, ITEMS_PER_PAGE); err != nil {
if err != mgo.ErrNotFound {
log.LogError(c.Request, err, "Error in ListPagingByCategory Post", logger)
c.AbortWithError(500, err)
return
}
c.AbortWithStatus(404)
return
}
c.JSON(200, posts)
}
示例6: userLocations
func userLocations(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "application/json")
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, X-Max")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
group := c.DefaultQuery("group", "noneasdf")
users := strings.Split(c.DefaultQuery("users", "noneasdf"), ",")
group = strings.ToLower(group)
if group != "noneasdf" {
if !groupExists(group) {
c.JSON(http.StatusOK, gin.H{"message": "You should insert fingerprints before tracking, see documentation", "success": false})
return
}
if users[0] == "noneasdf" {
users = getUsers(group)
}
people := make(map[string]UserPositionJSON)
for _, user := range users {
people[user] = getCurrentPositionOfUser(group, user)
}
c.JSON(http.StatusOK, gin.H{"message": "Correctly found", "success": true, "users": people})
} else {
c.JSON(http.StatusOK, gin.H{"success": false, "message": "Error parsing request"})
}
}
示例7: getApplicationsAction
func (ctl *ApplicationController) getApplicationsAction(c *gin.Context) {
var selectedTags models.TagsFilter
tagsQuery := c.DefaultQuery("tags", "")
if len(tagsQuery) > 0 {
selectedTags = strings.Split(tagsQuery, ",")
}
applications, err := models.ApplicationMapper.FetchAllByTag(selectedTags)
if err != nil {
c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
"error": err,
})
return
}
tags, err := models.ApplicationMapper.FetchAllTags()
if err != nil {
c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
"error": err,
})
return
}
c.HTML(http.StatusOK, "application_list.html", map[string]interface{}{
"selectedTags": selectedTags,
"tags": tags,
"applications": applications,
})
}
示例8: RegisterPostHandler
func RegisterPostHandler(c *gin.Context) {
redirect := c.DefaultQuery(auth.RedirectParam, "/")
a := auth.Default(c)
if a.User.IsAuthenticated() {
c.Redirect(http.StatusMovedPermanently, redirect)
return
}
registerURL := fmt.Sprintf("/register?%s=%s", auth.RedirectParam, redirect)
var form LoginForm
if c.Bind(&form) == nil {
model := models.Default(c)
u := model.AddUserWithNicknamePwd(form.Nickname, form.Password)
if u != nil {
session := sessions.Default(c)
err := auth.AuthenticateSession(session, u)
if err != nil {
c.JSON(http.StatusBadRequest, err)
}
c.Redirect(http.StatusMovedPermanently, redirect)
return
} else {
log.Print("Register user add error")
c.Redirect(http.StatusMovedPermanently, registerURL)
return
}
} else {
log.Print("Register form bind error")
c.Redirect(http.StatusMovedPermanently, registerURL)
return
}
}
示例9: QDataGet
func QDataGet(c *gin.Context) []*cmodel.GraphQueryResponse {
log := logger.Logger()
startTmp := c.DefaultQuery("startTs", string(time.Now().Unix()-(86400)))
startTmp2, _ := strconv.Atoi(startTmp)
startTs := int64(startTmp2)
endTmp := c.DefaultQuery("endTs", string(time.Now().Unix()))
endTmp2, _ := strconv.Atoi(endTmp)
endTs := int64(endTmp2)
consolFun := c.DefaultQuery("consolFun", "AVERAGE")
stepTmp := c.DefaultQuery("step", "60")
step, _ := strconv.Atoi(stepTmp)
counter := c.DefaultQuery("counter", "cpu.idle")
endpoints := model.EndpointQuery()
var result []*cmodel.GraphQueryResponse
for _, enp := range endpoints {
q := cmodel.GraphQueryParam{
Start: startTs,
End: endTs,
ConsolFun: consolFun,
Step: step,
Endpoint: enp,
Counter: counter,
}
res, _ := graph.QueryOne(q)
log.Debug(fmt.Sprintf("%v, %v, %v", res.Counter, res.Endpoint, len(res.Values)))
result = append(result, res)
}
log.Debug(fmt.Sprintf("%s: %d", "openfaclon query got", len(result)))
return result
}
示例10: getMonitoringAction
func (pc *MonitoringController) getMonitoringAction(c *gin.Context) {
host := c.Query("host")
stat := c.DefaultQuery("stat", "all")
t := c.DefaultQuery("time", "last1800")
hosts, err := models.NodeMapper.FetchAll()
if err != nil {
panic(err)
}
var graphs models.Graphs
var target []string
if host != "" {
target = []string{host}
} else {
for _, h := range hosts {
target = append(target, h.Hostname)
}
}
if graphs, err = models.GraphMapper.FetchAll(target, stat, t); err != nil {
panic(err)
}
c.HTML(http.StatusOK, "monitoring_show.html", map[string]interface{}{
"host": host,
"stat": stat,
"time": t,
"hosts": hosts,
"stats": models.GraphStats,
"graphs": graphs,
})
}
示例11: deleteLocations
func deleteLocations(c *gin.Context) {
group := strings.ToLower(c.DefaultQuery("group", "noneasdf"))
locationsQuery := strings.ToLower(c.DefaultQuery("names", "none"))
if group != "noneasdf" && locationsQuery != "none" {
locations := strings.Split(strings.ToLower(locationsQuery), ",")
db, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, group+".db"), 0600, nil)
if err != nil {
log.Fatal(err)
}
numChanges := 0
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("fingerprints"))
if b != nil {
c := b.Cursor()
for k, v := c.Last(); k != nil; k, v = c.Prev() {
v2 := loadFingerprint(v)
for _, location := range locations {
if v2.Location == location {
b.Delete(k)
numChanges++
break
}
}
}
}
return nil
})
db.Close()
optimizePriorsThreaded(strings.ToLower(group))
c.JSON(http.StatusOK, gin.H{"message": "Deleted " + strconv.Itoa(numChanges) + " locations", "success": true})
} else {
c.JSON(http.StatusOK, gin.H{"success": false, "message": "Need to provide group and location list. DELETE /locations?group=X&names=Y,Z,W"})
}
}
示例12: loginHandler
func loginHandler(c *gin.Context) {
redirectTarget := strings.TrimSpace(c.DefaultPostForm("next", c.DefaultQuery("next", "")))
// c.HTML(http.StatusOK, "login_page.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
// "err": "", "user_name": "", "pass": "", "next": redirectTarget})
renderTemplate(c.Writer, "login_page.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
"err": "", "user_name": "", "pass": "", "next": redirectTarget})
}
示例13: hostInfo
func hostInfo(c *gin.Context) {
var (
host_cnt, metric_cnt, group_cnt int
)
response := gin.H{"code": http.StatusOK}
defer c.JSON(http.StatusOK, response)
group_id, _ := strconv.Atoi(c.DefaultQuery("group_id", "-1"))
if group_id == -1 {
//all
mydb.Table("host").Count(&host_cnt)
mydb.Table("metric").Count(&metric_cnt)
mydb.Table("group").Count(&group_cnt)
response["groups"] = group_cnt
} else if group_id == 0 {
//未分組
mydb.Table("host").Joins("LEFT JOIN host_group ON host.id = host_group.host_id").
Where("host_group.group_id is NULL").Count(&host_cnt).
Joins("JOIN metric ON host.id = metric.host_id").Count(&metric_cnt)
//mydb.Table("host").Count(&host_cnt)
//mydb.Table("metric").Count(&metric_cnt)
//mydb.Table("group").Count(&group_cnt)
//response["groups"] = group_cnt
} else {
mydb.Table("host").Joins("JOIN host_group ON host.id = host_group.host_id").
Where("host_group.group_id = ?", group_id).
Count(&host_cnt)
mydb.Table("host").Joins("JOIN host_group ON host.id = host_group.host_id").
Where("host_group.group_id = ?", group_id).
Joins("JOIN metric ON host.id = metric.host_id").
Count(&metric_cnt)
}
response["hosts"] = host_cnt
response["metrics"] = metric_cnt
}
示例14: Login
// Login is a page with a login form and an alternative to the login API,
// this route handles both GET and POST requests.
func Login(c *gin.Context) {
session := sessions.Default(c)
defer session.Save()
// returnURL can come from GET or POST or use default.
returnURL := c.DefaultQuery("return_url", c.DefaultPostForm("return_url", "/"))
if c.Request.Method == "POST" {
var schema LoginSchema
if c.Bind(&schema) == nil {
// Fetch the user matching this username.
user := GetUserByUsername(schema.Username)
// If the user exists, the ID is > 0, check the password.
if user.ID > 0 && user.CheckPassword(schema.Password) {
session.Set("userID", user.ID)
c.Redirect(http.StatusFound, returnURL)
return
}
session.AddFlash("Invalid username or password")
}
}
c.HTML(200, "login.html", pongo2.Context{
"title": "Login",
"messages": session.Flashes(),
"csrf_token": nosurf.Token(c.Request),
"return_url": returnURL,
})
}
示例15: Compute
func Compute(c *gin.Context) {
funcName := c.DefaultQuery("funcName", "")
if funcName == "" {
c.JSON(400, gin.H{
"msg": "Get params fun error",
})
}
funcInstance := getFuncSetup(funcName)
if funcInstance.FuncationName == "" {
c.JSON(400, gin.H{
"msg": "Not found this compute method",
})
}
vm := initJSvM()
tmpparams := getParamsFromHTTP(funcInstance.Params, c)
source := c.DefaultQuery("source", "real")
if source == "real" {
vm.Set("input", openFalcon.QDataGet(c))
} else {
vm.Set("input", getFakeData())
}
setParamsToJSVM(tmpparams, funcInstance.Params, vm)
vm.Run(funcInstance.Codes)
output, err := vm.Get("output")
if err != nil {
c.JSON(400, gin.H{
"msg": err.Error(),
})
}
c.JSON(200, gin.H{
"compted_data": output.String(),
"funcName": funcName,
"paramsGot": tmpparams,
})
}