Example #1
1
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()})
}
Example #2
0
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)
}
Example #3
0
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
	})
}
Example #4
0
//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
	})
}
Example #5
0
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})
}
Example #6
0
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)
}
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")
	}
}
Example #8
0
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
}
Example #9
0
// 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,
	)
}
Example #10
0
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)
}
Example #11
0
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,
	})

}
Example #12
0
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),
	})
}
Example #13
0
func readPodLog(c *gin.Context) {
	namespace := c.Param("ns")
	podname := c.Param("po")
	_, previous := c.GetQuery("previous")

	readLog(c, namespace, podname, "", previous)
}
Example #14
0
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")
}
Example #15
0
// 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)
}
Example #16
0
func (p *Engine) deleteNote(c *gin.Context) (interface{}, error) {

	u := c.MustGet("user").(*platform.User)
	id := c.Param("id")
	err := p.Db.Where("id = ? AND user_id = ?", id, u.ID).Delete(Note{}).Error
	return web.OK, err
}
Example #17
0
func EditReviewFormR(c *gin.Context) {
	// dependency injection
	var (
		reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
		user        = GetUser(c)
	)

	// only authenticated users can perform this action
	if !user.Authenticated() {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}

	// fetch review
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	review, err := reviewStore.GetReview(id)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.HTML(http.StatusOK, "review-form.html", gin.H{
		"Action": "Edit",
		"User":   user,
		"Form":   review,
		"Errors": map[string]string{},
	})
}
Example #18
0
// View handles the file views
func View(c *gin.Context) {
	var err error

	id := c.Param("uniuri")
	re := models.Resource{}

	if err = re.Get(id); err != nil || re.Key == "" {
		logger.InfoC(c, "server", "Not found", id)
		c.AbortWithStatus(http.StatusNotFound)
		return
	}
	re.LogFetched(c)
	f, err := os.Open(path.Join(conf.C.UploadDir, re.Key))
	if err != nil {
		logger.ErrC(c, "server", fmt.Sprintf("Couldn't open %s", re.Key), err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	if conf.C.AlwaysDownload {
		c.Header("Content-Type", "application/octet-stream")
	}
	c.Header("Content-Disposition", "filename=\""+re.Name+"\"")
	io.Copy(c.Writer, f)
	if re.Once {
		re.Delete()
		re.LogDeleted(c)
	}
}
Example #19
0
func handleClaimantsClaimsDelete(c *gin.Context) {
	claimantID := c.Param("id")
	if strings.TrimSpace(claimantID) == "" {
		c.JSON(http.StatusBadRequest, "Bad Request")
		return
	}
	var claim stake.Claim
	decoder := json.NewDecoder(c.Request.Body)
	err := decoder.Decode(&claim)
	if err != nil {
		c.JSON(http.StatusBadRequest, "Bad Request")
		return
	}
	if strings.TrimSpace(claim.Claim) == "" || strings.TrimSpace(claim.Subject) == "" {
		c.JSON(http.StatusBadRequest, "Bad Request")
		return
	}

	if strings.TrimSpace(claimantID) == "" || strings.TrimSpace(claim.Claim) == "" || strings.TrimSpace(claim.Subject) == "" {
		c.JSON(http.StatusBadRequest, "Bad Request")
		return
	}
	result := deleteClaimantsClaimAboutSubject(claimantID, claim.Subject, claim.Claim)
	if result == success {
		c.JSON(http.StatusOK, result)
	} else {
		c.JSON(http.StatusNotFound, result)
	}
}
Example #20
0
/**
 * 1 - Show a deployment
 */
func (ctl *DeploymentController) getDeploymentAction(c *gin.Context) {

	appId := c.Param("app_id")
	deployId := c.Param("deploy_id")

	application := ctl.getApplication(c, appId)
	if application == nil {
		return
	}

	deployment := ctl.getDeployment(c, application, deployId)
	if deployment == nil {
		return
	}

	karhuURL, _ := url.Parse(env.GetDefault("PUBLIC_HOST", "http://127.0.0.1:8080"))
	webSocketProto := "ws"
	if karhuURL.Scheme == "https" {
		webSocketProto = "wss"
	}

	c.HTML(http.StatusOK, "deployment_show.html", map[string]interface{}{
		"application":     application,
		"deployment":      deployment,
		"public_host":     karhuURL.Host,
		"websocket_proto": webSocketProto,
	})
}
Example #21
0
/**
 * 2 - Create a deployment
 */
func (ctl *DeploymentController) postDeploymentAction(c *gin.Context) {

	appId := c.Param("app_id")
	buildId := c.Param("build_id")

	resp, err := http.Post(fmt.Sprintf("http://localhost:8080/api/apps/%s/builds/%s/deploy", appId, buildId), "json/application", nil)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
			"error": err,
		})
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
			"error": err,
		})
		return
	}
	var deployment models.Deployment
	if err := json.Unmarshal(body, &deployment); err != nil {
		c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
			"error": err,
		})
		return
	}

	c.Redirect(http.StatusFound, fmt.Sprintf("/application/deployment/%s/%s", appId, deployment.Id.Hex()))
}
Example #22
0
func GetDeviceCountOfAppLatestConfig(c *gin.Context) {
	memConfMux.RLock()
	app := memConfApps[c.Param("app_key")]
	memConfMux.RUnlock()

	if app == nil {
		Error(c, BAD_REQUEST, "app not found for app key: "+c.Param("app_key"))
		return
	}

	q := fmt.Sprintf("SELECT COUNT(DISTINCT(deviceid)) FROM client_request where app = '%s' AND time >= %d", app.Key, app.LastUpdateUTC*int(secondUnit))
	resp, err := queryInflux(q)
	if err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}
	if resp.Error() != nil {
		Error(c, SERVER_ERROR, resp.Error().Error())
		return
	}

	if len(resp.Results[0].Series) == 0 {
		Success(c, 0)
		return
	}

	Success(c, resp.Results[0].Series[0].Values[0][1])
}
Example #23
0
func EditWhiskyFormR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		user        = GetUser(c)
	)

	// only authenticated users can perform this action
	if !user.Authenticated() {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}

	// fetch whisky to edit
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	whisky, err := whiskyStore.GetWhisky(id)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.HTML(http.StatusOK, "whisky-form.html", gin.H{
		"Action": "Edit",
		"User":   user,
		"Form":   whisky,
		"Errors": map[string]string{},
	})
}
Example #24
0
// GroupDelete is used to delete one specific group with a `id`
func GroupDelete(c *gin.Context) {
	var group models.Group
	database.DBCon.First(&group, c.Param("id"))
	database.DBCon.Delete(&group)

	c.JSON(http.StatusOK, gin.H{"success": true})
}
Example #25
0
func UserR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
		user        = GetUser(c)
	)

	// parse id
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	// fetch whiksy
	whisky, err := whiskyStore.GetWhisky(id)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// fetch reviews
	reviews, err := reviewStore.GetAllReviews(id, 30)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.HTML(http.StatusOK, "whisky.html", gin.H{
		"User":    user,
		"Whisky":  whisky,
		"Reviews": reviews,
	})
}
Example #26
0
func editNode(c *gin.Context) {
	nodename := c.Param("no")
	_, delete := c.GetQuery("delete")

	node, err := kubeclient.Get().Nodes().Get(nodename)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	b, err := json.Marshal(node)
	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, "nodeEdit", gin.H{
		"title":   nodename,
		"objname": nodename,
		"json":    out.String(),
		"delete":  strconv.FormatBool(delete),
	})
}
Example #27
0
func (pc *NodeController) postNodeAction(c *gin.Context) {

	id := c.Param("id")

	var form models.NodeUpdateForm
	if err := c.Bind(&form); err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	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
	}

	node.Tags = form.Tags
	node.Description = form.Description
	models.NodeMapper.Update(node)

	c.Redirect(http.StatusFound, "/nodes")
}
Example #28
0
func editEndpoints(c *gin.Context) {
	namespace := c.Param("ns")
	epname := c.Param("ep")
	_, delete := c.GetQuery("delete")

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

	b, err := json.Marshal(ep)
	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, "endpointsEdit", gin.H{
		"title":     epname,
		"namespace": namespace,
		"objname":   epname,
		"json":      out.String(),
		"delete":    strconv.FormatBool(delete),
	})
}
Example #29
0
/*
删除文章

DELETE /api/topic/{id}
*/
func deleteTopic(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		c.JSON(200, RespResult{ErrCodeParam, "param id is empty", nil})
		return
	}
	// todo: 鉴权
	user := getCurrent(c)
	if user == nil {
		c.JSON(200, RespResult{ErrCodeNeePerm, "need permission", nil})
		return
	}

	post, err := getPostById(id, true)
	if err != nil {
		c.JSON(200, RespResult{ErrCodeDBQuery, err.Error(), nil})
		return
	}
	err = deletePost(post, user, true)
	if err != nil {
		c.JSON(200, RespResult{ErrCodeDBQuery, "delete post " + id + " failed: " + err.Error(), nil})
		return
	}
	c.JSON(200, RespResult{0, "ok", nil})
}
Example #30
-1
File: web.go Project: adriamb/gopad
func doGETCache(c *gin.Context) {

	hash := normalize(c.Param("hash"))

	file := store.GetCachePath(hash)
	c.File(file)
}