How to use RenderJSON method of render Package

Best Testkube code snippet using render.RenderJSON

app.go

Source:app.go Github

copy

Full Screen

...15func Route(engine *gin.RouterGroup) {16 save := func(c *gin.Context) {17 su, ok := c.Get(constant.SessionUser)18 if ok == false {19 util.RenderJSON(c, http.StatusInternalServerError, constant.SystemError)20 return21 }22 u := su.(*user.User)23 a := &app.App{}24 if err := c.ShouldBindJSON(a); err != nil {25 util.RenderJSON(c, http.StatusBadRequest, err.Error())26 return27 }28 ues, err := userEnvService.U.GetUserEnvsByUserId(u.Id)29 if err != nil {30 util.RenderJSON(c, http.StatusInternalServerError, err.Error())31 return32 }33 if ues == nil {34 util.RenderJSON(c, http.StatusOK, constant.Success)35 return36 }37 ok = false38 for _, ue := range ues {39 e, err := envService.E.GetEnvById(ue.EnvId)40 if err != nil {41 util.RenderJSON(c, http.StatusInternalServerError, err.Error())42 return43 }44 if e == nil {45 continue46 }47 if e.Name == a.Env {48 ok = true49 break50 }51 }52 if ok == false {53 util.RenderJSON(c, http.StatusOK, constant.Success)54 return55 }56 err = appService.A.Save(a)57 if err != nil {58 util.RenderJSON(c, http.StatusInternalServerError, err.Error())59 return60 }61 util.RenderJSONDetail(c, http.StatusOK, constant.Success, a)62 }63 engine.POST("/app", save)64 engine.PUT("/app", save)65 engine.GET("/apps", func(c *gin.Context) {66 su, ok := c.Get(constant.SessionUser)67 if ok == false {68 util.RenderJSON(c, http.StatusInternalServerError, constant.SystemError)69 return70 }71 u := su.(*user.User)72 apps, err := appService.A.GetAppsByUserId(u.Id)73 if err != nil {74 util.RenderJSON(c, http.StatusInternalServerError, err.Error())75 return76 }77 util.RenderJSONDetail(c, http.StatusOK, constant.Success, apps)78 })79 engine.GET("/app/:id", func(c *gin.Context) {80 su, ok := c.Get(constant.SessionUser)81 if ok == false {82 util.RenderJSON(c, http.StatusInternalServerError, constant.SystemError)83 return84 }85 u := su.(*user.User)86 n := c.Param("id")87 if n == "" {88 util.RenderJSON(c, http.StatusBadRequest, "id is required")89 return90 }91 id, err := strconv.ParseInt(n, 10, 64)92 if err != nil {93 util.RenderJSON(c, http.StatusBadRequest, err.Error())94 return95 }96 a, err := appService.A.GetAppById(id)97 if err != nil {98 util.RenderJSON(c, http.StatusInternalServerError, err.Error())99 return100 }101 ues, err := userEnvService.U.GetUserEnvsByUserId(u.Id)102 if err != nil {103 util.RenderJSON(c, http.StatusInternalServerError, err.Error())104 return105 }106 if ues == nil {107 util.RenderJSON(c, http.StatusOK, constant.Success)108 return109 }110 ok = false111 for _, ue := range ues {112 e, err := envService.E.GetEnvById(ue.EnvId)113 if err != nil {114 util.RenderJSON(c, http.StatusInternalServerError, err.Error())115 return116 }117 if e == nil {118 continue119 }120 if e.Name == a.Env {121 ok = true122 break123 }124 }125 if ok == false {126 util.RenderJSON(c, http.StatusOK, constant.Success)127 return128 }129 util.RenderJSONDetail(c, http.StatusOK, constant.Success, a)130 })131 engine.DELETE("/app/:id", func(c *gin.Context) {132 su, ok := c.Get(constant.SessionUser)133 if ok == false {134 util.RenderJSON(c, http.StatusInternalServerError, constant.SystemError)135 return136 }137 u := su.(*user.User)138 n := c.Param("id")139 if n == "" {140 util.RenderJSON(c, http.StatusBadRequest, "id is required")141 return142 }143 id, err := strconv.ParseInt(n, 10, 64)144 if err != nil {145 util.RenderJSON(c, http.StatusBadRequest, err.Error())146 return147 }148 a, err := appService.A.GetAppById(id)149 if err != nil {150 util.RenderJSON(c, http.StatusInternalServerError, err.Error())151 return152 }153 ues, err := userEnvService.U.GetUserEnvsByUserId(u.Id)154 if err != nil {155 util.RenderJSON(c, http.StatusInternalServerError, err.Error())156 return157 }158 if ues == nil {159 util.RenderJSON(c, http.StatusOK, constant.Success)160 return161 }162 ok = false163 for _, ue := range ues {164 e, err := envService.E.GetEnvById(ue.EnvId)165 if err != nil {166 util.RenderJSON(c, http.StatusInternalServerError, err.Error())167 return168 }169 if e == nil {170 continue171 }172 if e.Name == a.Env {173 ok = true174 break175 }176 }177 if ok == false {178 util.RenderJSON(c, http.StatusOK, constant.Success)179 return180 }181 err = appService.A.Delete(id)182 if err != nil {183 util.RenderJSON(c, http.StatusInternalServerError, err.Error())184 return185 }186 util.RenderJSON(c, http.StatusOK, constant.Success)187 })188 engine.GET("/app/:id/properties", func(c *gin.Context) {189 su, ok := c.Get(constant.SessionUser)190 if ok == false {191 util.RenderJSON(c, http.StatusInternalServerError, constant.SystemError)192 return193 }194 u := su.(*user.User)195 n := c.Param("id")196 if n == "" {197 util.RenderJSON(c, http.StatusBadRequest, "id is required")198 return199 }200 id, err := strconv.ParseInt(n, 10, 64)201 if err != nil {202 util.RenderJSON(c, http.StatusBadRequest, err.Error())203 return204 }205 a, err := appService.A.GetAppById(id)206 if err != nil {207 util.RenderJSON(c, http.StatusInternalServerError, err.Error())208 return209 }210 ues, err := userEnvService.U.GetUserEnvsByUserId(u.Id)211 if err != nil {212 util.RenderJSON(c, http.StatusInternalServerError, err.Error())213 return214 }215 if ues == nil {216 util.RenderJSON(c, http.StatusOK, constant.Success)217 return218 }219 ok = false220 for _, ue := range ues {221 e, err := envService.E.GetEnvById(ue.EnvId)222 if err != nil {223 util.RenderJSON(c, http.StatusInternalServerError, err.Error())224 return225 }226 if e == nil {227 continue228 }229 if e.Name == a.Env {230 ok = true231 break232 }233 }234 if ok == false {235 util.RenderJSON(c, http.StatusOK, constant.Success)236 return237 }238 props, err := appService.A.GetPropertiesById(id)239 if err != nil {240 util.RenderJSON(c, http.StatusInternalServerError, err.Error())241 return242 }243 if props == "" {244 util.RenderJSON(c, http.StatusOK, constant.Success)245 return246 }247 var m map[string]interface{}248 err = json.Unmarshal([]byte(props), &m)249 if err != nil {250 util.RenderJSON(c, http.StatusInternalServerError, err.Error())251 return252 }253 d, err := json.MarshalIndent(m, "", "\t")254 if err != nil {255 util.RenderJSON(c, http.StatusInternalServerError, err.Error())256 return257 }258 util.RenderJSONDetail(c, http.StatusOK, constant.Success, string(d))259 })260 saveProperties := func(c *gin.Context) {261 su, ok := c.Get(constant.SessionUser)262 if ok == false {263 util.RenderJSON(c, http.StatusInternalServerError, constant.SystemError)264 return265 }266 u := su.(*user.User)267 n := c.Param("id")268 if n == "" {269 util.RenderJSON(c, http.StatusBadRequest, "id is required")270 return271 }272 id, err := strconv.ParseInt(n, 10, 64)273 if err != nil {274 util.RenderJSON(c, http.StatusBadRequest, err.Error())275 return276 }277 a, err := appService.A.GetAppById(id)278 if err != nil {279 util.RenderJSON(c, http.StatusInternalServerError, err.Error())280 return281 }282 ues, err := userEnvService.U.GetUserEnvsByUserId(u.Id)283 if err != nil {284 util.RenderJSON(c, http.StatusInternalServerError, err.Error())285 return286 }287 if ues == nil {288 util.RenderJSON(c, http.StatusOK, constant.Success)289 return290 }291 ok = false292 for _, ue := range ues {293 e, err := envService.E.GetEnvById(ue.EnvId)294 if err != nil {295 util.RenderJSON(c, http.StatusInternalServerError, err.Error())296 return297 }298 if e == nil {299 continue300 }301 if e.Name == a.Env {302 ok = true303 break304 }305 }306 if ok == false {307 util.RenderJSON(c, http.StatusOK, constant.Success)308 return309 }310 var m map[string]interface{}311 if err := c.ShouldBindJSON(&m); err != nil {312 util.RenderJSON(c, http.StatusBadRequest, err.Error())313 return314 }315 d, err := json.Marshal(m)316 if err != nil {317 util.RenderJSON(c, http.StatusBadRequest, err.Error())318 }319 props, err := appService.A.SavePropertiesById(id, string(d))320 if err != nil {321 util.RenderJSON(c, http.StatusInternalServerError, err.Error())322 return323 }324 util.RenderJSONDetail(c, http.StatusOK, constant.Success, props)325 }326 engine.POST("/app/:id/properties", saveProperties)327 engine.PUT("/app/:id/properties", saveProperties)328}...

Full Screen

Full Screen

http.go

Source:http.go Github

copy

Full Screen

1package goappmonitor2import (3 "encoding/json"4 "fmt"5 "log"6 "net/http"7 _ "net/http/pprof" // pprof collector8 "strings"9)10// Start Http serever.11func startHttp(addr string, debug bool) {12 configCommonRoutes()13 configProcRoutes()14 if len(addr) >= 9 {15 s := &http.Server{16 Addr: addr,17 MaxHeaderBytes: 1 << 30,18 }19 go func() {20 if debug {21 log.Println("[goappmonitor] http server start, listening on", addr)22 }23 s.ListenAndServe()24 if debug {25 log.Println("[goappmonitor] http server stop,", addr)26 }27 }()28 }29}30// Routers config.31func configProcRoutes() {32 http.HandleFunc("/pfc/proc/metrics/json", func(w http.ResponseWriter, r *http.Request) {33 if !isLocalReq(r.RemoteAddr) {34 RenderJson(w, "no privilege")35 return36 }37 RenderJson(w, rawMetrics())38 })39 http.HandleFunc("/pfc/proc/metrics/falcon", func(w http.ResponseWriter, r *http.Request) {40 if !isLocalReq(r.RemoteAddr) {41 RenderJson(w, "no privilege")42 return43 }44 RenderJson(w, falconMetrics())45 })46 http.HandleFunc("/pfc/proc/metrics/influxdb", func(w http.ResponseWriter, r *http.Request) {47 if !isLocalReq(r.RemoteAddr) {48 RenderJson(w, "no privilege")49 return50 }51 InfluxDBJson(w, influxDBMetrics())52 })53 // url=/pfc/proc/metric/{json,falcon}54 http.HandleFunc("/pfc/proc/metrics/", func(w http.ResponseWriter, r *http.Request) {55 if !isLocalReq(r.RemoteAddr) {56 RenderJson(w, "no privilege")57 return58 }59 urlParam := r.URL.Path[len("/pfc/proc/metrics/"):]60 args := strings.Split(urlParam, "/")61 argsLen := len(args)62 if argsLen != 2 {63 RenderJson(w, "")64 return65 }66 types := []string{}67 typeslice := strings.Split(args[0], ",")68 for _, t := range typeslice {69 nt := strings.TrimSpace(t)70 if nt != "" {71 types = append(types, nt)72 }73 }74 if args[1] == "json" {75 RenderJson(w, rawMetric(types))76 return77 }78 if args[1] == "falcon" {79 RenderJson(w, falconMetric(types))80 return81 }82 if args[1] == "influxdb" {83 InfluxDBJson(w, influxDBMetric(types))84 return85 }86 })87 http.HandleFunc("/pfc/proc/metrics/size", func(w http.ResponseWriter, r *http.Request) {88 if !isLocalReq(r.RemoteAddr) {89 RenderJson(w, "no privilege")90 return91 }92 RenderJson(w, rawSizes())93 })94}95// Common router config.96func configCommonRoutes() {97 http.HandleFunc("/pfc/health", func(w http.ResponseWriter, r *http.Request) {98 if !isLocalReq(r.RemoteAddr) {99 RenderJson(w, "no privilege")100 return101 }102 w.Write([]byte("ok"))103 })104 http.HandleFunc("/pfc/version", func(w http.ResponseWriter, r *http.Request) {105 if !isLocalReq(r.RemoteAddr) {106 RenderJson(w, "no privilege")107 return108 }109 w.Write([]byte(fmt.Sprintf("%s\n", VERSION)))110 })111 http.HandleFunc("/pfc/config", func(w http.ResponseWriter, r *http.Request) {112 if !isLocalReq(r.RemoteAddr) {113 RenderJson(w, "no privilege")114 return115 }116 RenderJson(w, config())117 })118 http.HandleFunc("/pfc/config/reload", func(w http.ResponseWriter, r *http.Request) {119 if !isLocalReq(r.RemoteAddr) {120 RenderJson(w, "no privilege")121 return122 }123 loadConfig()124 RenderJson(w, "ok")125 })126}127func isLocalReq(raddr string) bool {128 return strings.HasPrefix(raddr, "127.0.0.1")129}130// RenderJson json131func RenderJson(w http.ResponseWriter, data interface{}) {132 renderJson(w, Response{Msg: "success", Data: data})133}134// RenderString string135func RenderString(w http.ResponseWriter, msg string) {136 renderJson(w, map[string]string{"msg": msg})137}138func renderJson(w http.ResponseWriter, v interface{}) {139 bs, err := json.Marshal(v)140 if err != nil {141 http.Error(w, err.Error(), http.StatusInternalServerError)142 return143 }144 w.Header().Set("Content-Type", "application/json; charset=UTF-8")145 w.Write(bs)146}147// Response http struct148type Response struct {149 Msg string `json:"msg"`150 Data interface{} `json:"data"`151}152// Render json153func InfluxDBJson(w http.ResponseWriter, data interface{}) {154 influxDBJson(w, InfluxDBResponse{155 "success",156 endpoint,157 []string{158 "metric",159 "counterType",160 "tags",161 "value",162 "step",163 "timestamp",164 },165 data,166 })167}168// Render string169func InfluxDBString(w http.ResponseWriter, msg string) {170 influxDBJson(w, map[string]string{"msg": msg})171}172func influxDBJson(w http.ResponseWriter, v interface{}) {173 bs, err := json.Marshal(v)174 if err != nil {175 http.Error(w, err.Error(), http.StatusInternalServerError)176 return177 }178 w.Header().Set("Content-Type", "application/json; charset=UTF-8")179 w.Write(bs)180}181type InfluxDBResponse struct {182 Msg string `json:"msg"`183 Name string `json:"name"`184 Columns []string `json:"columns"`185 Points interface{} `json:"points"`186}...

Full Screen

Full Screen

render.go

Source:render.go Github

copy

Full Screen

1package base2import (3 "encoding/json"4 "fmt"5 "github.com/myksc/ksc-base/golib/zlog"6 "net/http"7 "strconv"8 "strings"9 "time"10 "github.com/gin-gonic/gin"11 "github.com/pkg/errors"12)13// default render14type DefaultRender struct {15 ErrNo int `json:"errNo"`16 ErrMsg string `json:"errMsg"`17 Data interface{} `json:"data"`18}19func SetUpsErr(ctx *gin.Context, code int, msg string) {20 ctx.Header("X_BD_UPS_ERR_NO", strconv.Itoa(code))21 ctx.Header("X_BD_UPS_ERR_MSG", msg)22}23func RenderJson(ctx *gin.Context, code int, msg string, data interface{}) {24 SetUpsErr(ctx, code, msg)25 renderJson := DefaultRender{code, msg, data}26 ctx.JSON(http.StatusOK, renderJson)27 //ctx.Set("render", renderJson)28 return29}30func RenderJsonSucc(ctx *gin.Context, data interface{}) {31 SetUpsErr(ctx, 0, "succ")32 renderJson := DefaultRender{0, "succ", data}33 ctx.JSON(http.StatusOK, renderJson)34 //ctx.Set("render", renderJson)35 return36}37func RenderJsonFail(ctx *gin.Context, err error) {38 var renderJson DefaultRender39 switch errors.Cause(err).(type) {40 case Error:41 renderJson.ErrNo = errors.Cause(err).(Error).ErrNo42 renderJson.ErrMsg = errors.Cause(err).(Error).ErrMsg43 renderJson.Data = gin.H{}44 default:45 renderJson.ErrNo = -146 renderJson.ErrMsg = errors.Cause(err).Error()47 renderJson.Data = gin.H{}48 }49 SetUpsErr(ctx, renderJson.ErrNo, renderJson.ErrMsg)50 ctx.JSON(http.StatusOK, renderJson)51 //ctx.Set("render", renderJson)52 // 打印错误栈53 StackLogger(ctx, err)54 return55}56func RenderJsonAbort(ctx *gin.Context, err error) {57 var renderJson DefaultRender58 switch errors.Cause(err).(type) {59 case Error:60 renderJson.ErrNo = errors.Cause(err).(Error).ErrNo61 renderJson.ErrMsg = errors.Cause(err).(Error).ErrMsg62 renderJson.Data = gin.H{}63 default:64 renderJson.ErrNo = -165 renderJson.ErrMsg = errors.Cause(err).Error()66 renderJson.Data = gin.H{}67 }68 SetUpsErr(ctx, renderJson.ErrNo, renderJson.ErrMsg)69 ctx.AbortWithStatusJSON(http.StatusOK, renderJson)70 //ctx.Set("render", renderJson)71 return72}73// 打印错误栈74func StackLogger(ctx *gin.Context, err error) {75 if !strings.Contains(fmt.Sprintf("%+v", err), "\n") {76 return77 }78 var info []byte79 if ctx != nil {80 info, _ = json.Marshal(map[string]interface{}{"time": time.Now().Format("2006-01-02 15:04:05"), "level": "error", "module": "errorstack", "requestId": zlog.GetRequestID(ctx)})81 } else {82 info, _ = json.Marshal(map[string]interface{}{"time": time.Now().Format("2006-01-02 15:04:05"), "level": "error", "module": "errorstack"})83 }84 fmt.Printf("%s\n-------------------stack-start-------------------\n%+v\n-------------------stack-end-------------------\n", string(info), err)85}...

Full Screen

Full Screen

RenderJSON

Using AI Code Generation

copy

Full Screen

1import (2type MainController struct {3}4func (this *MainController) Get() {5 this.Ctx.WriteString("Hello World")6}7func (this *MainController) Hello() {8 this.Ctx.WriteString("Hello World")9}10func (this *MainController) HelloJson() {11 this.Data["json"] = map[string]interface{}{"hello": "world"}12 this.ServeJson()13}14func main() {15 beego.Router("/", &MainController{})16 beego.Router("/hello", &MainController{}, "get:Hello")17 beego.Router("/hellojson", &MainController{}, "get:HelloJson")18 beego.Run()19}20import (21type MainController struct {22}23func (this *MainController) Get() {24 this.Ctx.WriteString("Hello World")25}26func (this *MainController) Hello() {27 this.Ctx.WriteString("Hello World")28}29func (this *MainController) HelloJson() {30 this.Data["json"] = map[string]interface{}{"hello": "world"}31 this.ServeJson()32}33func main() {34 beego.Router("/", &MainController{})35 beego.Router("/hello", &MainController{}, "get:Hello")36 beego.Router("/hellojson", &MainController{}, "get:HelloJson")37 beego.Run()38}39import (40type MainController struct {41}42func (this *MainController) Get() {43 this.Ctx.WriteString("Hello World")44}45func (this *MainController) Hello() {46 this.Ctx.WriteString("Hello World")47}48func (this *MainController) HelloJson() {49 this.Data["json"] = map[string]interface{}{"hello": "world"}50 this.ServeJson()51}52func main() {53 beego.Router("/", &MainController{})54 beego.Router("/hello", &MainController{}, "get:Hello")55 beego.Router("/hellojson", &MainController{}, "get:HelloJson")56 beego.Run()57}58import (

Full Screen

Full Screen

RenderJSON

Using AI Code Generation

copy

Full Screen

1func (c *AppController) Index() {2 c.RenderJSON(c.Txn.All(&models.Post{}))3}4func (c *AppController) Index() {5 c.RenderJSON(c.Txn.All(&models.Post{}))6}7func (c *AppController) Index() {8 c.RenderJSON(c.Txn.All(&models.Post{}))9}10func (c *AppController) Index() {11 c.RenderJSON(c.Txn.All(&models.Post{}))12}13func (c *AppController) Index() {14 c.RenderJSON(c.Txn.All(&models.Post{}))15}16func (c *AppController) Index() {17 c.RenderJSON(c.Txn.All(&models.Post{}))18}19func (c *AppController) Index() {20 c.RenderJSON(c.Txn.All(&models.Post{}))21}22func (c *AppController) Index() {23 c.RenderJSON(c.Txn.All(&models.Post{}))24}25func (c *AppController) Index() {26 c.RenderJSON(c.Txn.All(&models.Post{}))27}28func (c *AppController) Index() {29 c.RenderJSON(c.Txn.All(&models.Post{}))30}31func (c *AppController) Index() {32 c.RenderJSON(c.Txn.All(&models.Post{}))33}34func (c *AppController) Index() {35 c.RenderJSON(c.Txn.All(&models.Post{}))36}

Full Screen

Full Screen

RenderJSON

Using AI Code Generation

copy

Full Screen

1func (c *AppController) Index() revel.Result {2 return c.RenderJSON(struct {3 }{"Bob"})4}5func (c *AppController) Index() revel.Result {6 return c.RenderJSON(struct {7 }{"Bob"})8}9func (c *AppController) Index() revel.Result {10 return c.RenderJSON(struct {11 }{"Bob"})12}13func (c *AppController) Index() revel.Result {14 return c.RenderJSON(struct {15 }{"Bob"})16}17func (c *AppController) Index() revel.Result {18 return c.RenderJSON(struct {19 }{"Bob"})20}21func (c *AppController) Index() revel.Result {22 return c.RenderJSON(struct {23 }{"Bob"})24}25func (c *AppController) Index() revel.Result {26 return c.RenderJSON(struct {27 }{"Bob"})28}29func (c *AppController) Index() revel.Result {30 return c.RenderJSON(struct {31 }{"Bob"})32}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful