當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Context.Param方法代碼示例

本文整理匯總了Golang中github.com/gin-gonic/gin.Context.Param方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.Param方法的具體用法?Golang Context.Param怎麽用?Golang Context.Param使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在github.com/gin-gonic/gin.Context的用法示例。


在下文中一共展示了Context.Param方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: clientHandler

func clientHandler(c *gin.Context) {
	data, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		log.Println(err)
		return
	}
	log.Printf("[CLIENT] %s\n", string(data))
	javaConn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8081", http.Header{})
	if err != nil {
		log.Println(err)
		return
	}
	initialJSON, _ := json.Marshal(map[string]string{"name": c.Param("name")})
	javaConn.WriteMessage(websocket.TextMessage, initialJSON)
	javaConn.ReadMessage()
	javaConn.WriteMessage(websocket.TextMessage, data)
	_, p, err := javaConn.ReadMessage()
	if err != nil {
		log.Println(err)
		return
	}
	log.Printf("[SPIGOT] %s\n", string(p))
	javaConn.Close()
	c.Writer.Write(p)
}
開發者ID:np-overflow,項目名稱:minecraft-proxy,代碼行數:25,代碼來源:main.go

示例2: ExecutionCreate

//ExecutionCreate serves the route POST /tasks/:task_id/executions
func ExecutionCreate(c *gin.Context) {
	models.InTx(func(txn *gorm.DB) bool {
		var task models.Task
		if txn.Where("id like ? ", c.Param("task_id")).First(&task); task.ID == "" {
			c.JSON(http.StatusNotFound, "")
			return false
		}
		var execution models.Execution
		if err := c.BindJSON(&execution); err != nil {
			c.JSON(http.StatusBadRequest, err)
			return false
		}
		execution.TaskID = task.ID
		if valid, errMap := models.ValidStruct(&execution); !valid {
			c.JSON(http.StatusConflict, errMap)
			return false
		}
		if txn.Create(&execution).Error != nil {
			c.JSON(http.StatusBadRequest, "Execution can't be saved")
			return false
		}
		c.JSON(http.StatusOK, execution)
		return true
	})
}
開發者ID:khoa-le,項目名稱:guartz,代碼行數:26,代碼來源:executions.go

示例3: Generate8bit

func Generate8bit(c *gin.Context) {
	name := c.Param("name")
	gender := c.Param("gender")

	switch {
	case gender == "m":
		gender = "male"
	case gender == "f":
		gender = "female"
	case gender == "male" || gender == "female":
		//do nothing
	default:
		c.AbortWithError(http.StatusInternalServerError, errors.New("Invalid parameters"))
		return
	}

	log.Println(name)
	InitAssets()
	img := GenerateIdenticon8bits(gender, []byte(name))
	c.Header("Content-Type", "image/png")
	c.Stream(func(w io.Writer) bool {
		png.Encode(w, img)
		return false
	})
}
開發者ID:julianshen,項目名稱:goticon,代碼行數:25,代碼來源:goticon.go

示例4: GetAdminNewsEdit

func GetAdminNewsEdit(c *gin.Context) {
	nw := News{}
	i, _ := strconv.Atoi(c.Param("kkk"))
	NewsSession.Find(gin.H{"id": i}).One(&nw)
	fmt.Println(nw.Short, nw.Id)
	c.HTML(200, "editn.html", gin.H{"news": nw})
}
開發者ID:Collapsik,項目名稱:kkk,代碼行數:7,代碼來源:news.go

示例5: GetResource

func (rc *ResourceController) GetResource(ctx *gin.Context) {
	var id bson.ObjectId
	req := ctx.Request
	resourceType := getResourceType(req.URL)

	// Validate id as a bson Object ID
	id, err := toBsonObjectID(ctx.Param("id"))
	if err != nil {
		ctx.AbortWithError(http.StatusBadRequest, err)
		return
	}
	logger.Log.WithFields(
		logrus.Fields{"resource type": resourceType, "id": id}).Info("GetResource")

	resource, err := rc.LoadResource(resourceType, id)
	if err != nil {
		if err == mgo.ErrNotFound {
			ctx.String(http.StatusNotFound, "Not Found")
			ctx.Abort()
			return
		} else {
			ctx.AbortWithError(http.StatusBadRequest, err)
			return
		}
	}

	logger.Log.WithFields(logrus.Fields{"resource": resource}).Info("GetResource")

	ctx.JSON(http.StatusOK, resource)
}
開發者ID:mitre,項目名稱:ptmatch,代碼行數:30,代碼來源:resource_controller.go

示例6: fibonacci

func fibonacci(c *gin.Context) {

	nParam := c.Param("n")
	n, err := strconv.Atoi(nParam)

	if err != nil || n == 0 {
		c.JSON(http.StatusBadRequest, errorResponse{
			ErrorCode:       1000,
			Message:         "Received inputParameter is not a correct limit value",
			InputParameters: nParam,
		})
		return
	}

	fibelems, err := fibSrv.CountNValues(n)
	if err != nil {
		c.JSON(http.StatusInternalServerError, errorResponse{
			ErrorCode:       1000,
			Message:         "Unexpected error occurred during fibonacci calculation",
			InputParameters: nParam,
		})
		return
	}

	c.JSON(http.StatusOK, response{N: n, Elems: fibelems.ToString()})
}
開發者ID:kmejka,項目名稱:fibonacci,代碼行數:26,代碼來源:fibonacci.go

示例7: update

func update(c *gin.Context) {

	var input Dog
	c.Bind(&input)
	log.Print(c)

	id := c.Param("id")
	log.Print(id)

	//check if valid id
	if bson.IsObjectIdHex(id) == false {
		c.JSON(400, gin.H{"error": "ID not valid"})
		return
	}

	bId := bson.ObjectIdHex(id)

	err := Collection.UpdateId(bId, &Dog{bId, input.Name, input.Owner})

	if err != nil {
		c.JSON(400, "id not found")
	} else {
		c.JSON(200, "dog updated")
	}
}
開發者ID:SHeidemueller,項目名稱:simple_go_rest_api,代碼行數:25,代碼來源:dogpark.go

示例8: showNote

func (p *Engine) showNote(c *gin.Context) (interface{}, error) {
	u := c.MustGet("user").(*platform.User)
	id := c.Param("id")
	var note Note
	err := p.Db.Where("id = ? AND user_id = ?", id, u.ID).First(&note).Error
	return note, err
}
開發者ID:itpkg,項目名稱:chaos,代碼行數:7,代碼來源:c_notes.go

示例9: UserOrgIndex

// UserOrgIndex retrieves all orgs related to a user.
func UserOrgIndex(c *gin.Context) {
	records, err := store.GetUserOrgs(
		c,
		&model.UserOrgParams{
			User: c.Param("user"),
		},
	)

	if err != nil {
		logrus.Warnf("Failed to fetch user orgs. %s", err)

		c.JSON(
			http.StatusInternalServerError,
			gin.H{
				"status":  http.StatusInternalServerError,
				"message": "Failed to fetch orgs",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		records,
	)
}
開發者ID:umschlag,項目名稱:umschlag-api,代碼行數:29,代碼來源:user.go

示例10: New

func (self *EnvController) New(c *gin.Context) {
	username := self.CurrentUser(c)

	if username == "" {
		c.Redirect(http.StatusFound, "/")

		return
	}

	appName := c.Param("appName")
	key := c.PostForm("key")
	value := c.PostForm("value")

	err := env.Create(self.etcd, username, appName, key, value)

	if err != nil {
		fmt.Fprintf(os.Stderr, "%+v\n", err)

		c.HTML(http.StatusInternalServerError, "app.tmpl", gin.H{
			"alert":   true,
			"error":   true,
			"message": "Failed to add environment variable.",
		})

		return
	}

	c.Redirect(http.StatusSeeOther, "/apps/"+appName)
}
開發者ID:dtan4,項目名稱:paus-frontend,代碼行數:29,代碼來源:env_controller.go

示例11: ViewCtr

func (fc *FrontController) ViewCtr(c *gin.Context) {
	id := c.Param("id")
	var blog VBlogItem
	CKey := fmt.Sprintf("blogitem-%d", id)
	val, ok := Cache.Get(CKey)
	if val != nil && ok == true {
		fmt.Println("Ok, we found cache, Cache Len: ", Cache.Len())
		blog = val.(VBlogItem)
	} else {
		rows, err := DB.Query("Select * from top_article where aid = ?", &id)
		if err != nil {
			log.Fatal(err)
		}
		defer rows.Close()
		var ()
		for rows.Next() {
			err := rows.Scan(&blog.aid, &blog.title, &blog.content, &blog.publish_time, &blog.publish_status)
			if err != nil {
				log.Fatal(err)
			}
		}
		err = rows.Err()
		if err != nil {
			log.Fatal(err)
		}
		Cache.Add(CKey, blog)
	}
	c.HTML(http.StatusOK, "view.html", gin.H{
		"aid":          blog.aid,
		"title":        blog.title.String,
		"content":      template.HTML(blog.content.String),
		"publish_time": blog.publish_time.String,
	})

}
開發者ID:rageshkrishna,項目名稱:gosense,代碼行數:35,代碼來源:front-controller.go

示例12: editReplicationController

func editReplicationController(c *gin.Context) {
	namespace := c.Param("ns")
	rcname := c.Param("rc")
	_, delete := c.GetQuery("delete")

	rc, err := kubeclient.Get().ReplicationControllers(namespace).Get(rcname)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	b, err := json.Marshal(rc)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	var out bytes.Buffer
	err = json.Indent(&out, b, "", "  ")
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	c.HTML(http.StatusOK, "replicationControllerEdit", gin.H{
		"title":     rcname,
		"namespace": namespace,
		"objname":   rcname,
		"json":      out.String(),
		"delete":    strconv.FormatBool(delete),
	})
}
開發者ID:aclisp,項目名稱:kubecon,代碼行數:32,代碼來源:main.go

示例13: readPodLog

func readPodLog(c *gin.Context) {
	namespace := c.Param("ns")
	podname := c.Param("po")
	_, previous := c.GetQuery("previous")

	readLog(c, namespace, podname, "", previous)
}
開發者ID:aclisp,項目名稱:kubecon,代碼行數:7,代碼來源:main.go

示例14: postDeleteNodeAction

func (pc *NodeController) postDeleteNodeAction(c *gin.Context) {

	id := c.Param("id")

	node, err := models.NodeMapper.FetchOneById(id)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
			"error": err,
		})
		return
	}

	if node == nil {
		c.HTML(http.StatusNotFound, "error_404.html", map[string]interface{}{
			"text": "Node not found",
		})
		return
	}

	if err := models.NodeMapper.Delete(node); err != nil {
		c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
			"error": err,
		})
		return
	}

	c.Redirect(http.StatusFound, "/nodes")
}
開發者ID:KarhuTeam,項目名稱:Karhu,代碼行數:28,代碼來源:node_controller.go

示例15: OpenWebsocket

// Status handler for the /status route
func OpenWebsocket(c *gin.Context) {
	userId := c.MustGet("request_user_id").(string)
	noteId := c.Param("note_id")
	in, note, err := db.GetNoteById(noteId)
	if log.Error(err) {
		c.Error(errors.NewISE())
		return
	}
	if !in {
		c.Error(errors.NewHttp(http.StatusNotFound, "The requested note was not found"))
		return
	}
	if userId != note.Owner {
		c.Error(errors.NewHttp(http.StatusUnauthorized, "Only owners can open websockets into their notes"))
		return
	}
	conn, err := websocketUpgrader.Upgrade(c.Writer, c.Request, nil)
	if log.Error(err) {
		c.Error(errors.NewISE())
		return
	}
	log.Info("Opening ws for user %v on %v", userId, note.Id)
	bundle := model.NewContext(userId, noteId)
	WrapWebsocket(conn, bundle)
	ws.ProcessMessages(bundle)
}
開發者ID:notion-app,項目名稱:api,代碼行數:27,代碼來源:route_v1_ws.go


注:本文中的github.com/gin-gonic/gin.Context.Param方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。