func executeAction(c *gin.Context) { var args []string for i := 0; i < 10; i++ { operation := c.Query(strconv.Itoa(i)) if len(operation) > 0 { args = append(args, operation) } else { break } } fmt.Println(args) //Turn LED Blue to Indicate event. setRGB([]string{"0", "255", "255"}) time.Sleep(1 * time.Second) statusCode := 200 out, err := exec.Command(command, args...).Output() if err != nil { statusCode = 500 //Flash LED red to indicate Error setRGB([]string{"255", "0", "0"}) time.Sleep(1 * time.Second) } //Turn LED back to green setRGB([]string{"0", "255", "0"}) c.JSON(statusCode, gin.H{ "status": "received", "output": string(out[:]), }) }
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, }) }
func delete(c *gin.Context) { series := c.Query("series") if series == "" { c.JSON(http.StatusOK, gin.H{ "status": "error", "message": "series need", }) return } err := db.Batch(func(tx *bolt.Tx) error { err := tx.DeleteBucket([]byte(series)) if err != nil { return err } return nil }) if err != nil { c.JSON(http.StatusOK, gin.H{ "status": "error", "message": err.Error(), }) return } c.JSON(http.StatusOK, gin.H{ "status": "ok", }) }
func deployReplicasModify(ginCtx *gin.Context) { name := ginCtx.Params.ByName("name") num := ginCtx.Params.ByName("num") force := ginCtx.Query("force") fs := false if force == "true" { fs = true } glog.Info("scaling %s to %d instances", name, num) replicas, err := strconv.Atoi(num) if err != nil { glog.Errorf("Could not change instances for %s, caused by %s", name, err) ginCtx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) ginCtx.Error(err) return } var beReq = &ScaleRequest{Name: name, Replicas: replicas, Force: fs} _, err = se.Backend.Scale(beReq) if err != nil { glog.Errorf("Could not change instances for %s, caused by: %s", name, err.Error()) ginCtx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) ginCtx.Error(err) return } ginCtx.JSON(http.StatusOK, gin.H{}) }
func (this *CCEvent) Post(c *gin.Context) { this.Load() c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type,Token") program_id := c.Query("program_id") user_id := c.Query("created_by") if user_id != "" { _, err := userHandler.FetchUserById(user_id) if err != nil { fmt.Println("User id not exist: ") panic(err) return } } if program_id != "" { _, err := programHandler.FetchProgram(program_id) if err != nil { fmt.Println("Program id not exist: ") panic(err) return } } err := eventHandler.AddEvent(c) if err != nil { fmt.Println("Data insertion failed ", err.Error()) return } fmt.Println("Data Inserted Successfully: ") }
func (ctr *AuthController) Show(c *gin.Context) { email := c.Query("email") c.JSON(200, gin.H{ "status": "posted", "email": email, }) }
func GetCommit(c *gin.Context) { repo := session.Repo(c) parsed, err := token.ParseRequest(c.Request, func(t *token.Token) (string, error) { return repo.Hash, nil }) if err != nil { c.AbortWithError(http.StatusBadRequest, err) return } if parsed.Text != repo.FullName { c.AbortWithStatus(http.StatusUnauthorized) return } commit := c.Param("sha") branch := c.Query("branch") if len(branch) == 0 { branch = repo.Branch } build, err := store.GetBuildCommit(c, repo, commit, branch) if err != nil { c.AbortWithError(http.StatusNotFound, err) return } c.JSON(http.StatusOK, build) }
// 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) }
func handleRequestBalance(context *gin.Context) { user_id := context.Query("user") if user_id == "" { context.String(422, "User is empty!") return } id, err := strconv.ParseUint(user_id, 10, 64) if err != nil { context.String(422, "User is not valid!") return } var u User db := context.MustGet("DBM").(*sql.DB) tx, err := db.Begin() checkErr(err) defer tx.Rollback() user := u.Get(id, tx) if user.Id == 0 { context.String(422, "User is not valid!") return } tx.Commit() context.JSON(200, gin.H{ "balance": user.Amount, }) }
// convertByURLHandler is the main v1 API handler for converting a HTML to a PDF // via a GET request. It can either return a JSON string indicating that the // output of the conversion has been uploaded or it can return the output of // the conversion to the client (raw bytes). func convertByURLHandler(c *gin.Context) { s := c.MustGet("statsd").(*statsd.Client) r, ravenOk := c.Get("sentry") url := c.Query("url") if url == "" { c.AbortWithError(http.StatusBadRequest, ErrURLInvalid).SetType(gin.ErrorTypePublic) s.Increment("invalid_url") return } ext := c.Query("ext") source, err := converter.NewConversionSource(url, nil, ext) if err != nil { s.Increment("conversion_error") if ravenOk { r.(*raven.Client).CaptureError(err, map[string]string{"url": url}) } c.Error(err) return } conversionHandler(c, *source) }
func convertByFileHandler(c *gin.Context) { s := c.MustGet("statsd").(*statsd.Client) r, ravenOk := c.Get("sentry") file, header, err := c.Request.FormFile("file") if err != nil { c.AbortWithError(http.StatusBadRequest, ErrFileInvalid).SetType(gin.ErrorTypePublic) s.Increment("invalid_file") return } ext := c.Query("ext") source, err := converter.NewConversionSource("", file, ext) if err != nil { s.Increment("conversion_error") if ravenOk { r.(*raven.Client).CaptureError(err, map[string]string{"url": header.Filename}) } c.Error(err) return } conversionHandler(c, *source) }
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) }
func (ctrl *Controller) GetArticles(c *gin.Context) { id := repository.MaxArticleID if c.Query("olderthan") != "" { olderthan, err := strconv.Atoi(c.Query("olderthan")) if err != nil { ctrl.Logger.Log("msg", "Can't convert olderthan id to int", "err", err.Error()) c.AbortWithStatus(http.StatusInternalServerError) } id = olderthan } articles, err := ctrl.Repository.FindArticlesOlderThan(id, ArticlesPerPage) if err != nil { if err == repository.ErrArticleNotFound { ctrl.Logger.Log("msg", "Can't find olderthan article", "id", id) status := http.StatusNotFound c.JSON(status, gin.H{ "message": http.StatusText(status), "status_code": status, }) } ctrl.Logger.Log("msg", "Failed to get olderthan articles", "id", id, "err", err) c.AbortWithStatus(http.StatusInternalServerError) } c.JSON(http.StatusOK, marshaller.Articles(articles)) }
func Home(c *gin.Context) { ac := getAppConfig(c) hostPortList := make([]string, 0, 100) for k, _ := range ac.Instances { hostPortList = append(hostPortList, k) } instanceID := c.Query("instance") if _, ok := ac.Instances[instanceID]; ok == false { instanceID = hostPortList[0] } targetSource := ac.Instances[instanceID].Source infoErr := "" hasInfoErr := false statsInfo, err := getStatsInfo(targetSource) if err != nil { infoErr = err.Error() hasInfoErr = true } structedStatsInfo := statsMap2Struct(statsInfo) structedStatsInfo.InstanceID = instanceID structedStatsInfo.Source = targetSource c.HTML(http.StatusOK, "index.html", gin.H{ "HasInfoErr": hasInfoErr, "InfoErr": infoErr, "Instances": ac.Instances, "StatsInfo": structedStatsInfo, }) }
func ParseRGB(c *gin.Context) (colorful.Color, error) { rgb := map[string]float64{ "r": 0, "g": 0, "b": 0, } var err error for k, v := range rgb { if v, err = strconv.ParseFloat(c.Query(k), 64); err != nil { err = errors.New("failed to parse color") return colorful.Color{}, err } if v < 0 || v > 255 { err = errors.New("invalid color value. must be <= 0 or >= 255") return colorful.Color{}, err } rgb[k] = v } color := colorful.Color{ rgb["r"] / 255.0, rgb["g"] / 255.0, rgb["b"] / 255.0, } return color, nil }
func read(c *gin.Context) { db := session.DB("fs") if err := db.Login("user", "pwd"); err != nil { c.AbortWithError(403, err) } grid := db.GridFS(c.Query("user")) log.Println(c.Request.URL.Path) gridFile, err := grid.Open(c.Request.URL.Path) if err != nil { c.AbortWithError(404, err) return } defer gridFile.Close() var b []byte buf := bytes.NewBuffer(b) if _, err := io.Copy(buf, gridFile); err != nil { log.Println(err) c.AbortWithError(500, err) } c.Writer.WriteHeader(200) c.Writer.Write(buf.Bytes()) }
func ParseColor(c *gin.Context) (uint8, error) { Colors := map[string]uint8{ "violet": 0x00, "blue": 0x10, "baby_blue": 0x20, "aqua": 0x30, "mint": 0x40, "seafoam_green": 0x50, "green": 0x60, "lime_green": 0x70, "yellow": 0x80, "yellow_orange": 0x90, "orange": 0xA0, "red": 0xB0, "pink": 0xC0, "fusia": 0xD0, "purple": 0xE0, "lavendar": 0xF0, } color := c.Query("color") colorHex, ok := Colors[color] if !ok { err := errors.New("invalid color name") return 0, err } return colorHex, nil }
func chatEndPoint(c *gin.Context) { roomID := c.Query("roomID") peerID := c.Query("peerID") // create the room if not yet room, exists := rooms[roomID] if !exists { room = NewRoom(roomID) } ws, err := upgrader.Upgrade(c.Writer, c.Request, nil) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ "ERROR": "INTERNAL_SERVER_ERROR", }) return } peer := &Peer{ sendChan: make(chan []byte), ws: ws, ID: peerID, roomID: room.ID, } room.registerChan <- peer go peer.read() peer.talk() }
func GetClientSymbols(c *gin.Context) { memConfClientMux.RLock() defer memConfClientMux.RUnlock() res := []string{} var t map[string]bool switch c.Param("symbol") { case GLISP_SYMBOL_TYPE_LANG: t = memConfClientLang case GLISP_SYMBOL_TYPE_OS_TYPE: t = memConfClientOSType case GLISP_SYMBOL_TYPE_OS_VERSION: t = memConfClientOSV case GLISP_SYMBOL_TYPE_TIMEZONE: t = memConfClientTimezone case GLISP_SYMBOL_TYPE_NETWORK: t = memConfClientNetwork case GLISP_SYMBOL_TYPE_APP_VERSION: t = memConfClientAppVersion[c.Query("app_key")] default: Error(c, BAD_REQUEST, "unknown symbol type: "+c.Query("symbol")) return } for v, _ := range t { res = append(res, v) } sort.Strings(res) Success(c, res) }
func websocketUpgradeEndPoint(c *gin.Context) { roomID := c.Query("roomID") room := rooms[roomID] if room == nil { c.JSON(http.StatusBadRequest, gin.H{ "ERROR": "ROOM_AVALIABLE", }) } ws, err := upgrader.Upgrade(c.Writer, c.Request, nil) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ "ERROR": "INTERNAL_SERVER_ERROR", }) return } peer := &Peer{ sendChan: make(chan []byte), ws: ws, ID: GUID(16), roomID: room.ID, } room.registerChan <- peer go peer.read() peer.talk() }
func pluginByHostID(c *gin.Context) { host_id := c.Param("id") var cnt int mydb.Table("host").Where("id = ?", host_id).Count(&cnt) if cnt == 0 { c.JSON(http.StatusOK, gin.H{"code": http.StatusNotFound, "message": "the specified host is not found"}) return } page, err1 := strconv.Atoi(c.DefaultQuery("page", "1")) pageSize, err2 := strconv.Atoi(c.DefaultQuery("pageSize", DefaultPageSize)) if err1 != nil || err2 != nil { c.JSON(http.StatusOK, gin.H{"code": http.StatusBadRequest, "message": "invalid parameters"}) return } db := mydb.Table("plugin"). Joins("LEFT JOIN host_plugin ON plugin.id = host_plugin.plugin_id"). Where("host_plugin.host_id = ?", host_id) q := c.Query("q") if len(q) > 0 { q := fmt.Sprintf("%%%s%%", q) db = db.Where("name like ?", q) } var total int db.Count(&total) offset := (page - 1) * pageSize plugins := []types.Plugin{} db.Offset(offset).Limit(pageSize).Find(&plugins) c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "plugins": plugins, "total": total}) }
func (nr *NewsResource) SearchNews(c *gin.Context) { var news api.News var multipleNews []api.News params := []string{"patient_id", "spell_id", "location_id", "user_id"} for index, param := range params { id, err := nr.getParamId(c, param) if err != nil { c.JSON(400, api.NewError("problem decoding query parameter sent")) return } if id > 0 { switch { case index == 0: news.PatientId = int32(id) case index == 1: news.SpellId = int32(id) case index == 2: news.LocationId = int32(id) case index == 3: news.UserId = int32(id) } } } if risk := c.Query("risk"); risk != "" { risk := strings.Title(risk) news.Risk = risk } nr.db.Where(&news).Find(&multipleNews) c.JSON(200, multipleNews) }
func (m *Mongo) GetAllTest(c *gin.Context) { tokenReceived := c.Query("token") subject, err := utils.AuthenticateTokenGetSubject(tokenReceived) if err != nil { utils.ErrorResponse(c, http.StatusForbidden, "Log In Again") return } var test models.Test test.Subject = subject tests, err := test.GetAllTest(m.Database) if err != nil { utils.ErrorResponse(c, http.StatusInternalServerError, "Could not retreive test") return } c.JSON(http.StatusOK, gin.H{ "err": nil, "tests": tests, }) }
// http://127.0.0.1:6789/pure/22.jpg func imageHandler(context *gin.Context) { imgPath := context.Param("path") size := context.Query("s") if doSkip(imgPath, context) { context.Status(http.StatusOK) return } if size != "" { imgPath = imgPath + "?s=" + size } else { if isSpider(context) { imgPath = imgPath + "?s=" + util.ExtImgSize } else { if !util.ReferAllow(context.Request.Referer()) { if util.DoAd(context) { adImgPath := util.GetRandomAdPath() if adImgPath != "" { imgPath = adImgPath } } else { imgPath = imgPath + "?s=" + util.ExtImgSize } } } } rspImg(util.RedirectUrl+imgPath, context) return }
func apiDB(c *gin.Context) { userId := c.Query("user") db, err := sql.Open("mysql", "root@/test") if err != nil { panic(err.Error()) } defer db.Close() stmt, err := db.Prepare("SELECT content FROM testtable WHERE idtesttable = ?") res, err := stmt.Query(userId) if err != nil { panic(err.Error()) } var col1 string res.Next() err = res.Scan(&col1) if err != nil { panic(err.Error()) } defer res.Close() c.String(http.StatusOK, "Response: %s", col1) }
//SignHandler Sign AWS reqwest func SignHandler(context *gin.Context) { fileName := context.Query("filename") fileType := context.Query("filetype") fmt.Println(fileName, fileType) accessKey := os.Getenv("AWS_ACCESS_KEY_ID") secretKey := os.Getenv("AWS_SECRET_ACCESS_KEY") bucket := os.Getenv("S3_BUCKET_NAME") fileName = url.QueryEscape(fileName) expires := time.Now().AddDate(0, 0, 1).Unix() amzHeaders := "x-amz-acl:public-read" stringToSign := fmt.Sprintf("PUT\n\n%s\n%d\n%s\n/%s/%s", fileType, expires, amzHeaders, bucket, fileName) hasher := hmac.New(sha1.New, []byte(secretKey)) hasher.Write([]byte(stringToSign)) signature := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) query := url.Values{ "AWSAccessKeyId": []string{accessKey}, "Expires": []string{strconv.FormatInt(expires, 10)}, "Signature": []string{signature}, } url := fmt.Sprintf("https://%s.s3-eu-west-1.amazonaws.com/%s", bucket, fileName) context.JSON(http.StatusOK, gin.H{"signedRequest": url + "?" + query.Encode(), "url": url}) }
func ApiGetPassphraseRoute(c *gin.Context) { // extracting length of password from query parameters var length int = 5 if len(c.Query("parts")) > 0 { parts, _ := strconv.ParseInt(c.Query("parts"), 10, 64) length = int(parts) // if its not matching number range, throw 400 error request if length <= 0 || 99 < length { c.JSON(400, gin.H{ "meta": gin.H{ "message": "Parts need to be integer in range <1,99>.", }, }) return } } // generate password passphrase := diceware.GeneratePassphrase(length) // send success response c.JSON(200, gin.H{ "meta": gin.H{ "message": "Ok.", }, "data": gin.H{ "passphrase": gin.H{ "text": strings.Join(passphrase, ""), "parts": passphrase, }, }, }) }
func (a *Api) SearchSMS(c *gin.Context) { log.Debug("Searching...") query := c.Query("q") start := c.Query("start") limit := c.Query("limit") if query == "" { jsonWebError(c, 400, "Bad request, missing query") return } if start == "" { start = "0" } if limit == "" { limit = "50" } smss := make([]*Sms, 0) a.db.Offset(start).Limit(limit).Where("message ILIKE ?", fmt.Sprintf("%% %s %%", query)).Find(&smss) log.Infof("Search for '%s' returned %d results, returning up to %s to client from offset %s", query, len(smss), limit, start) c.JSON(200, smss) return }
func (page *Tenant) Get(c *gin.Context) { fmt.Println("Tenant.Get") tenants := make([]model.Tenant, 0) idstr := c.Query("id") //id:=c.Param("id") //fmt.Println("Params:",idstr) id, err := strconv.Atoi(idstr) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "Params err"}) } where := "" if id > 0 { where = "Id=" + idstr } else { where = "Id>0" } err = vars.Db.Where(where).Find(&tenants) if err != nil { log.Println(err) } //fmt.Println(tenants) // tenant:=model.Tenant{Id:10,Name:"hefju520",Phone:"13929961332",Desc:"测试返回json"} c.JSON(http.StatusOK, tenants) }
func (s *Sensorserver) GetChart(c *gin.Context) { // Load Template // Can't use c.HTML(), because the html template function escape " t, _ := template.ParseFiles(s.conf.TemplateDir + "/chart.js") s.conf.Type = c.Param("type") durationInSeconds := s.duration(c.Query("duration")) f := make(map[string]interface{}) for _, sensor := range s.conf.Sensors { data, err := s.fetchLastData(sensor, durationInSeconds) if err != nil { log.Println(err.Error()) c.String(http.StatusInternalServerError, err.Error()) return } if s.conf.Type == "single" { f[sensor] = s.reduceData(data) } else { f[sensor] = s.getMinMaxPerDay(data) } } f["plotBands"] = s.GetSunriseAndSunset() f["type"] = s.conf.Type c.Header("Content-Type", "application/javascript; charset=utf-8") t.Execute(c.Writer, f) }