本文整理匯總了Golang中github.com/gin-gonic/gin.Context類的典型用法代碼示例。如果您正苦於以下問題:Golang Context類的具體用法?Golang Context怎麽用?Golang Context使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Context類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: createRoomEndPoint
func createRoomEndPoint(c *gin.Context) {
var json = &struct {
Name string `form:"name" json:"name" binding:"required"`
Description string `form:"description" json:"description"`
}{}
if c.Bind(json) != nil {
c.JSON(http.StatusBadRequest, gin.H{"ERR": "WRONG_INPUT"})
return
}
userID64, _ := c.Get("userID")
roomRaw := &RoomData{
Name: json.Name,
Description: json.Description,
OwnerID: userID64.(int),
}
roomID, err := saveRoomRaw(roomRaw)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"ERR": "INTERNAL_SERVER_ERR"})
return
}
if peer, ok := peers.get(userID64.(int)); ok {
peer.joinRoom(roomID)
}
// return roomid and name
c.JSON(http.StatusOK, gin.H{
"ID": roomID, "Name": json.Name,
})
}
示例2: GetTableRows
func GetTableRows(c *gin.Context) {
limit := 1000 // Number of rows to fetch
limitVal := c.Request.FormValue("limit")
if limitVal != "" {
num, err := strconv.Atoi(limitVal)
if err != nil {
c.JSON(400, Error{"Invalid limit value"})
return
}
if num <= 0 {
c.JSON(400, Error{"Limit should be greater than 0"})
return
}
limit = num
}
opts := client.RowsOptions{
Limit: limit,
SortColumn: c.Request.FormValue("sort_column"),
SortOrder: c.Request.FormValue("sort_order"),
}
res, err := DbClient.TableRows(c.Params.ByName("table"), opts)
serveResult(res, err, c)
}
示例3: addOrRemoveLabel
func (m *MessagesController) addOrRemoveLabel(ctx *gin.Context, messageIn *messageJSON, message models.Message, user models.User) {
if messageIn.Text == "" {
ctx.AbortWithError(http.StatusBadRequest, errors.New("Invalid Text for label"))
return
}
info := gin.H{}
if messageIn.Action == "label" {
addedLabel, err := message.AddLabel(messageIn.Text, messageIn.Option)
if err != nil {
log.Errorf("Error while adding a label to a message %s", err)
ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
info = gin.H{"info": fmt.Sprintf("label %s added to message", addedLabel.Text), "label": addedLabel, "message": message}
} else if messageIn.Action == "unlabel" {
err := message.RemoveLabel(messageIn.Text)
if err != nil {
log.Errorf("Error while remove a label from a message %s", err)
ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
info = gin.H{"info": fmt.Sprintf("label %s removed from message", messageIn.Text), "message": message}
} else {
ctx.AbortWithError(http.StatusBadRequest, errors.New("Invalid action : "+messageIn.Action))
return
}
go models.WSMessage(&models.WSMessageJSON{Action: messageIn.Action, Username: user.Username, Message: message})
ctx.JSON(http.StatusCreated, info)
}
示例4: DeleteUserInstance
func DeleteUserInstance(c *gin.Context) {
db := c.MustGet("db").(gorm.DB)
consumer := c.MustGet("consumer").(models.User)
id := c.Params.ByName("id")
var user models.User
db.First(&user, id)
if user.Username == "" {
response := make(map[string]string)
response["error"] = "Resource not found."
c.JSON(404, response)
} else {
if (consumer.Admin) || (user.Id == consumer.Id) {
db.Delete(&user)
if user.Id != consumer.Id {
if user.Gravatar == "" {
user.Gravatar = user.Email
}
user.Email = ""
}
user.Password = ""
c.JSON(200, user)
} else {
response := make(map[string]string)
response["error"] = "Invalid credentials."
c.JSON(401, response)
}
}
}
示例5: LoginHandler
func LoginHandler(c *gin.Context) {
var code int
var response gin.H
var loginData loginForm
c.BindJSON(&loginData)
errors := loginData.validate()
if len(errors) == 0 {
user, authErrors := authOrRegisterUser(loginData)
if authErrors["password"] != "" {
code = 422
response = gin.H{"success": false, "errors": authErrors}
} else {
code = 200
response = gin.H{
"success": true,
"new": user.RestoreCode != "",
"auth": gin.H{
"account": user.Email,
"token": createUserToken(user),
"roles": user.Roles,
},
}
}
} else {
code = 422
response = gin.H{"success": false, "errors": errors}
}
c.JSON(code, response)
}
示例6: logs
func (rest *RestInterface) logs(c *gin.Context) {
agentID := agentInformation(c)
db := rest.pool.Get()
defer db.Close()
log.Printf("[+] gin: log (gid: %s, nid: %s)\n", agentID.GID, agentID.NID)
// read body
content, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
log.Println("[-] cannot read body:", err)
c.JSON(http.StatusInternalServerError, "error")
return
}
// push body to redis
id := fmt.Sprintf("%s:%s:log", agentID.GID, agentID.NID)
log.Printf("[+] message destination [%s]\n", id)
// push message to client queue
_, err = db.Do("RPUSH", id, content)
c.JSON(http.StatusOK, "ok")
}
示例7: ShowRepo
func ShowRepo(c *gin.Context) {
user := session.User(c)
repo := session.Repo(c)
builds, _ := store.GetBuildList(c, repo)
groups := []*model.BuildGroup{}
var curr *model.BuildGroup
for _, build := range builds {
date := time.Unix(build.Created, 0).Format("Jan 2 2006")
if curr == nil || curr.Date != date {
curr = &model.BuildGroup{}
curr.Date = date
groups = append(groups, curr)
}
curr.Builds = append(curr.Builds, build)
}
httputil.SetCookie(c.Writer, c.Request, "user_last", repo.FullName)
c.HTML(200, "repo.html", gin.H{
"User": user,
"Repo": repo,
"Builds": builds,
"Groups": groups,
})
}
示例8: HomeCtr
func (fc *FrontController) HomeCtr(c *gin.Context) {
page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
if err != nil {
log.Fatal(err)
}
page -= 1
if page < 0 {
page = 0
}
prev_page := page
if prev_page < 1 {
prev_page = 1
}
next_page := page + 2
rpp := 20
offset := page * rpp
CKey := fmt.Sprintf("home-page-%d-rpp-%d", page, rpp)
var blogList string
val, ok := Cache.Get(CKey)
if val != nil && ok == true {
fmt.Println("Ok, we found cache, Cache Len: ", Cache.Len())
blogList = val.(string)
} else {
rows, err := DB.Query("Select aid, title from top_article where publish_status = 1 order by aid desc limit ? offset ? ", &rpp, &offset)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var (
aid int
title sql.NullString
)
for rows.Next() {
err := rows.Scan(&aid, &title)
if err != nil {
log.Fatal(err)
}
blogList += fmt.Sprintf(
"<li><a href=\"/view/%d\">%s</a></li>",
aid,
title.String,
)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
Cache.Add(CKey, blogList)
}
session := sessions.Default(c)
username := session.Get("username")
c.HTML(http.StatusOK, "index.html", gin.H{
"bloglist": template.HTML(blogList),
"username": username,
"prev_page": prev_page,
"next_page": next_page,
})
}
示例9: CreateFiles
// CreateFiles creates files.
func CreateFiles(c *gin.Context) (int, error) {
var forms FilesForm
start := time.Now()
c.BindWith(&forms, binding.JSON)
log.Debugf("CreateFiles c form : %v", forms)
user, _ := userService.CurrentUser(c)
sqlStrBuffer := new(bytes.Buffer)
stringHelper.Concat(sqlStrBuffer, "INSERT INTO file(user_id, name, size, created_at) VALUES ")
values := []interface{}{}
for _, file := range forms.Files {
stringHelper.Concat(sqlStrBuffer, "(?, ?, ?, ?),")
values = append(values, user.Id, file.Name, file.Size, time.Now())
}
// sqlStrBuffer.Truncate(sqlStrBuffer.Len() - 1) is slower than slice.
if len(values) > 0 {
sqlStr := sqlStrBuffer.String()
sqlStr = sqlStr[0 : len(sqlStr)-1]
log.Debugf("sqlStr for File : %s", sqlStr)
db.ORM.Exec(sqlStr, values...)
elapsed := time.Since(start)
log.Debugf("CreateFiles elapsed : %s", elapsed)
}
return http.StatusCreated, nil
}
示例10: usersDetail
func usersDetail(c *gin.Context) {
user_id := c.Params.ByName("id")
a_id, _ := strconv.Atoi(user_id)
user := getuser(a_id)
content := gin.H{"Name": user.Name, "content": user.Address}
c.JSON(200, content)
}
示例11: QueryData
func QueryData(c *gin.Context) {
result := QDataGet(c)
c.JSON(200, gin.H{
"status": "ok",
"data": result,
})
}
示例12: 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
}
示例13: GetUsers
func GetUsers(c *gin.Context) {
m := Msg{
Message: "This is GetUsers",
Status: 200,
}
c.JSON(200, m)
}
示例14: suggest
func suggest(c *gin.Context) {
cfg := getConfig(c)
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
for {
movie, err := cfg.Store.GetRandom()
if err != nil {
continue
}
if err := conn.WriteJSON(movie); err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
time.Sleep(socketWaitFor)
}
}
示例15: FromContext
func FromContext(c *gin.Context) *Session {
if val, ok := c.Get("session"); ok {
if s, ok := val.(*Session); ok {
return s
}
}
cookie, err := c.Request.Cookie(CookieKey)
if err != nil {
s := Create()
s.storeInContext(c)
http.SetCookie(c.Writer, s.cookie())
return s
}
s, err := Load(cookie.Value)
if err != nil {
s := Create()
s.storeInContext(c)
http.SetCookie(c.Writer, s.cookie())
return s
}
s.storeInContext(c)
return s
}