Best K6 code snippet using log.MarshalJSON
handlers.go
Source:handlers.go
...66 w.WriteHeader(http.StatusBadRequest)67 response, _ := types.ServerResponse{68 Status: http.StatusText(http.StatusBadRequest),69 Message: "invalid_request_format",70 }.MarshalJSON()71 _, _ = w.Write(response)72 return73 }74 if registrationInfo.Login == "" {75 w.WriteHeader(http.StatusUnprocessableEntity)76 response, _ := types.ServerResponse{77 Status: http.StatusText(http.StatusUnprocessableEntity),78 Message: "empty_login",79 }.MarshalJSON()80 _, _ = w.Write(response)81 return82 }83 if len(registrationInfo.Password) < 5 {84 w.WriteHeader(http.StatusUnprocessableEntity)85 response, _ := types.ServerResponse{86 Status: http.StatusText(http.StatusUnprocessableEntity),87 Message: "weak_password",88 }.MarshalJSON()89 _, _ = w.Write(response)90 return91 }92 userID, isDuplicate, err := e.DB.InsertIntoUser(registrationInfo.Login, defaultAvatarURL, false)93 if isDuplicate {94 w.WriteHeader(http.StatusConflict)95 response, _ := types.ServerResponse{96 Status: http.StatusText(http.StatusConflict),97 Message: "login_is_not_unique",98 }.MarshalJSON()99 _, _ = w.Write(response)100 return101 }102 if err != nil {103 w.WriteHeader(http.StatusInternalServerError)104 response, _ := types.ServerResponse{105 Status: http.StatusText(http.StatusInternalServerError),106 Message: "database_error",107 }.MarshalJSON()108 _, _ = w.Write(response)109 return110 }111 err = e.DB.InsertIntoRegularLoginInformation(userID, sha256hash(registrationInfo.Password))112 if err != nil {113 log.Print(err)114 w.WriteHeader(http.StatusInternalServerError)115 response, _ := types.ServerResponse{116 Status: http.StatusText(http.StatusInternalServerError),117 Message: "database_error",118 }.MarshalJSON()119 _, _ = w.Write(response)120 return121 }122 err = e.DB.InsertIntoGameStatistics(userID, 0, 0)123 if err != nil {124 log.Print(err)125 w.WriteHeader(http.StatusInternalServerError)126 response, _ := types.ServerResponse{127 Status: http.StatusText(http.StatusInternalServerError),128 Message: "database_error",129 }.MarshalJSON()130 _, _ = w.Write(response)131 return132 }133 // ÑоздаÑм ÑÐ¾ÐºÐµÐ½Ñ Ð°Ð²ÑоÑизаÑии.134 authorizationToken := randomToken()135 err = e.DB.UpsertIntoCurrentLogin(userID, authorizationToken)136 if err != nil {137 log.Print(err)138 w.WriteHeader(http.StatusInternalServerError)139 response, _ := types.ServerResponse{140 Status: http.StatusText(http.StatusInternalServerError),141 Message: "database_error",142 }.MarshalJSON()143 _, _ = w.Write(response)144 return145 }146 // ÐÑÑÑлаем ноÑмалÑнÑй оÑвеÑ.147 http.SetCookie(w, &http.Cookie{148 Name: "SessionId",149 Value: authorizationToken,150 Path: "/",151 Expires: time.Now().AddDate(0, 0, 7),152 Secure: true,153 HttpOnly: true,154 SameSite: http.SameSiteLaxMode,155 })156 w.WriteHeader(http.StatusCreated)157 response, _ := types.ServerResponse{158 Status: http.StatusText(http.StatusCreated),159 Message: "successful_reusable_registration",160 }.MarshalJSON()161 _, _ = w.Write(response)162}163// RegistrationTemporary godoc164// @Summary Temporary user registration.165// @Description Сreates user without statistics and password, stub so that you can play 1 session without creating an account.166// @Tags user167// @Accept application/json168// @Produce application/json169// @Param registrationInfo body types.NewUserRegistration true "login password"170// @Success 200 {object} types.ServerResponse171// @Failure 500 {object} types.ServerResponse172// @Router /api/v1/user&temporary=true [post]173func (e *Environment) RegistrationTemporary(w http.ResponseWriter, r *http.Request) {174 w.Header().Set("Content-Type", "application/json")175 bodyBytes, err := ioutil.ReadAll(r.Body)176 _ = r.Body.Close()177 registrationInfo := types.NewUserRegistration{}178 err = registrationInfo.UnmarshalJSON(bodyBytes)179 if err != nil {180 w.WriteHeader(http.StatusBadRequest)181 response, _ := types.ServerResponse{182 Status: http.StatusText(http.StatusBadRequest),183 Message: "invalid_request_format",184 }.MarshalJSON()185 _, _ = w.Write(response)186 return187 }188 if registrationInfo.Login == "" {189 w.WriteHeader(http.StatusUnprocessableEntity)190 response, _ := types.ServerResponse{191 Status: http.StatusText(http.StatusUnprocessableEntity),192 Message: "empty_login",193 }.MarshalJSON()194 _, _ = w.Write(response)195 return196 }197 userID, isDuplicate, err := e.DB.InsertIntoUser(registrationInfo.Login, defaultAvatarURL, true)198 if isDuplicate {199 w.WriteHeader(http.StatusConflict)200 response, _ := types.ServerResponse{201 Status: http.StatusText(http.StatusConflict),202 Message: "login_is_not_unique",203 }.MarshalJSON()204 _, _ = w.Write(response)205 return206 }207 if err != nil {208 log.Print(err)209 w.WriteHeader(http.StatusInternalServerError)210 response, _ := types.ServerResponse{211 Status: http.StatusText(http.StatusInternalServerError),212 Message: "database_error",213 }.MarshalJSON()214 _, _ = w.Write(response)215 return216 }217 // ÑоздаÑм ÑÐ¾ÐºÐµÐ½Ñ Ð°Ð²ÑоÑизаÑии.218 authorizationToken := randomToken()219 err = e.DB.UpsertIntoCurrentLogin(userID, authorizationToken)220 if err != nil {221 log.Print(err)222 w.WriteHeader(http.StatusInternalServerError)223 response, _ := types.ServerResponse{224 Status: http.StatusText(http.StatusInternalServerError),225 Message: "database_error",226 }.MarshalJSON()227 _, _ = w.Write(response)228 return229 }230 http.SetCookie(w, &http.Cookie{231 Name: "SessionId",232 Value: authorizationToken,233 Path: "/",234 Expires: time.Now().AddDate(0, 0, 7),235 Secure: true,236 HttpOnly: true,237 SameSite: http.SameSiteLaxMode,238 })239 w.WriteHeader(http.StatusCreated)240 response, _ := types.ServerResponse{241 Status: http.StatusText(http.StatusCreated),242 Message: "successful_disposable_registration",243 }.MarshalJSON()244 _, _ = w.Write(response)245}246// LeaderBoard godoc247// @Summary Get liderboard with best user information.248// @Description Return login, avatarAddress, gamesPlayed and wins information for earch user.249// @Tags users250// @Accept application/json251// @Produce application/json252// @Param limit query int false "Lenth of returning user list."253// @Param offset query int false "Offset relative to the leader."254// @Success 200 {array} accessor.PublicUserInformation255// @Failure 500 {object} types.ServerResponse256// @Router /api/v1/users [get]257func (e *Environment) LeaderBoard(w http.ResponseWriter, r *http.Request) {258 w.Header().Set("Content-Type", "application/json")259 getParams := r.URL.Query()260 _ = r.Body.Close()261 limit := 20262 if customLimitStrings, ok := getParams["limit"]; ok {263 if len(customLimitStrings) == 1 {264 if customLimitInt, err := strconv.Atoi(customLimitStrings[0]); err == nil {265 limit = customLimitInt266 }267 }268 }269 offset := 0270 if customOffsetStrings, ok := getParams["offset"]; ok {271 if len(customOffsetStrings) == 1 {272 if customOffsetInt, err := strconv.Atoi(customOffsetStrings[0]); err == nil {273 offset = customOffsetInt274 }275 }276 }277 LeaderBoard, err := e.DB.SelectLeaderBoard(limit, offset)278 if err != nil {279 log.Print(err)280 w.WriteHeader(http.StatusInternalServerError)281 response, _ := types.ServerResponse{282 Status: http.StatusText(http.StatusInternalServerError),283 Message: "database_error",284 }.MarshalJSON()285 _, _ = w.Write(response)286 return287 }288 w.WriteHeader(http.StatusOK)289 response, _ := LeaderBoard.MarshalJSON()290 _, _ = w.Write(response)291}292// UserProfile godoc293// @Summary Get user information.294// @Description Return login, avatarAddress, gamesPlayed, wins, information.295// @Tags user296// @Accept application/json297// @Produce application/json298// @Param login query string true "login password"299// @Success 200 {object} accessor.PublicUserInformation300// @Failure 422 {object} types.ServerResponse301// @Failure 500 {object} types.ServerResponse302// @Router /api/v1/user [get]303func (e *Environment) UserProfile(w http.ResponseWriter, r *http.Request) {304 getParams := r.URL.Query()305 _ = r.Body.Close()306 login := ""307 if loginStrings, ok := getParams["login"]; ok {308 if len(loginStrings) == 1 {309 login = loginStrings[0]310 if login != "" {311 // just working on312 } else {313 w.WriteHeader(http.StatusUnprocessableEntity)314 response, _ := types.ServerResponse{315 Status: http.StatusText(http.StatusUnprocessableEntity),316 Message: "empty_login_field",317 }.MarshalJSON()318 _, _ = w.Write(response)319 return320 }321 } else {322 w.WriteHeader(http.StatusUnprocessableEntity)323 response, _ := types.ServerResponse{324 Status: http.StatusText(http.StatusUnprocessableEntity),325 Message: "login_must_be_only_1",326 }.MarshalJSON()327 _, _ = w.Write(response)328 return329 }330 } else {331 w.WriteHeader(http.StatusUnprocessableEntity)332 response, _ := types.ServerResponse{333 Status: http.StatusText(http.StatusUnprocessableEntity),334 Message: "field_login_required",335 }.MarshalJSON()336 _, _ = w.Write(response)337 return338 }339 userProfile, err := e.DB.SelectUserByLogin(login)340 if err != nil {341 log.Print(err)342 w.WriteHeader(http.StatusInternalServerError)343 response, _ := types.ServerResponse{344 Status: http.StatusText(http.StatusInternalServerError),345 Message: "database_error",346 }.MarshalJSON()347 _, _ = w.Write(response)348 return349 }350 w.WriteHeader(http.StatusOK)351 response, _ := userProfile.MarshalJSON()352 _, _ = w.Write(response)353}354// Login godoc355// @Summary Login into account.356// @Description Set cookie on client and save them in database.357// @Tags session358// @Accept application/json359// @Produce application/json360// @Param registrationInfo body types.NewUserRegistration true "login password"361// @Success 202 {object} types.ServerResponse362// @Failure 400 {object} types.ServerResponse363// @Failure 403 {object} types.ServerResponse364// @Failure 500 {object} types.ServerResponse365// @Router /api/v1/session [post]366func (e *Environment) Login(w http.ResponseWriter, r *http.Request) {367 w.Header().Set("Content-Type", "application/json")368 bodyBytes, err := ioutil.ReadAll(r.Body)369 _ = r.Body.Close()370 registrationInfo := types.NewUserRegistration{}371 err = registrationInfo.UnmarshalJSON(bodyBytes)372 if err != nil {373 w.WriteHeader(http.StatusBadRequest)374 response, _ := types.ServerResponse{375 Status: http.StatusText(http.StatusBadRequest),376 Message: "invalid_request_format",377 }.MarshalJSON()378 _, _ = w.Write(response)379 return380 }381 exists, userId, err := e.DB.SelectUserIdByLoginPasswordHash(registrationInfo.Login, sha256hash(registrationInfo.Password))382 if err != nil {383 log.Print(err)384 w.WriteHeader(http.StatusInternalServerError)385 response, _ := types.ServerResponse{386 Status: http.StatusText(http.StatusInternalServerError),387 Message: "database_error",388 }.MarshalJSON()389 _, _ = w.Write(response)390 return391 }392 if exists {393 authorizationToken := randomToken()394 err = e.DB.UpsertIntoCurrentLogin(userId, authorizationToken)395 if err != nil {396 log.Print(err)397 w.WriteHeader(http.StatusInternalServerError)398 response, _ := types.ServerResponse{399 Status: http.StatusText(http.StatusInternalServerError),400 Message: "database_error",401 }.MarshalJSON()402 _, _ = w.Write(response)403 return404 }405 // Уже ноÑмалÑнÑй оÑÐ²ÐµÑ Ð¾ÑÑÑлаем.406 http.SetCookie(w, &http.Cookie{407 Name: "SessionId",408 Value: authorizationToken,409 Path: "/",410 Expires: time.Now().AddDate(0, 0, 7),411 Secure: true,412 HttpOnly: true,413 SameSite: http.SameSiteLaxMode,414 })415 w.WriteHeader(http.StatusAccepted)416 response, _ := types.ServerResponse{417 Status: http.StatusText(http.StatusAccepted),418 Message: "successful_password_login",419 }.MarshalJSON()420 _, _ = w.Write(response)421 } else {422 w.WriteHeader(http.StatusForbidden)423 response, _ := types.ServerResponse{424 Status: http.StatusText(http.StatusFailedDependency),425 Message: "wrong_login_or_password",426 }.MarshalJSON()427 _, _ = w.Write(response)428 }429}430// Logout godoc431// @Summary Log registered user out.432// @Description Delete cookie in client and database.433// @Tags session434// @Accept application/json435// @Produce application/json436// @Success 200 {object} types.ServerResponse437// @Failure 404 {object} types.ServerResponse438// @Failure 401 {object} types.ServerResponse439// @Router /api/v1/session [delete]440func (e *Environment) Logout(w http.ResponseWriter, r *http.Request) {441 //get sid from cookies442 inCookie, err := r.Cookie("SessionId")443 if err != nil {444 log.Print(err)445 w.WriteHeader(http.StatusUnauthorized)446 response, _ := types.ServerResponse{447 Status: http.StatusText(http.StatusUnauthorized),448 Message: "unauthorized_user",449 }.MarshalJSON()450 _, _ = w.Write(response)451 return452 }453 err = e.DB.DropUsersSession(inCookie.Value)454 if err != nil {455 log.Print(err)456 w.WriteHeader(http.StatusNotFound)457 response, _ := types.ServerResponse{458 Status: http.StatusText(http.StatusNotFound),459 Message: "target_session_not_found",460 }.MarshalJSON()461 _, _ = w.Write(response)462 return463 }464 http.SetCookie(w, &http.Cookie{465 Name: "SessionId",466 Expires: time.Unix(0, 0),467 Secure: true,468 HttpOnly: true,469 SameSite: http.SameSiteLaxMode,470 })471 w.WriteHeader(http.StatusOK)472 response, _ := types.ServerResponse{473 Status: http.StatusText(http.StatusOK),474 Message: "successful_logout",475 }.MarshalJSON()476 _, _ = w.Write(response)477}478// Logout godoc479// @Summary Upload user avatar.480// @Description Upload avatar from \<form enctype='multipart/form-data' action='/api/v1/avatar'>\<input type="file" name="avatar"></form>.481// @Tags avatar482// @Accept multipart/form-data483// @Produce application/json484// @Success 201 {object} types.ServerResponse485// @Failure 400 {object} types.ServerResponse486// @Failure 401 {object} types.ServerResponse487// @Failure 500 {object} types.ServerResponse488// @Router /api/v1/avatar [post]489func (e *Environment) SetAvatar(w http.ResponseWriter, r *http.Request) {490 defer func() { _ = r.Body.Close() }()491 w.Header().Set("Content-Type", "application/json")492 //get SessionId from cookies493 cookie, err := r.Cookie("SessionId")494 if err != nil || cookie.Value == "" {495 log.Print(err)496 w.WriteHeader(http.StatusForbidden)497 response, _ := types.ServerResponse{498 Status: http.StatusText(http.StatusForbidden),499 Message: "unauthorized_user",500 }.MarshalJSON()501 _, _ = w.Write(response)502 return503 }504 exist, user, err := e.DB.SelectUserBySessionId(cookie.Value)505 if err != nil {506 log.Print(err)507 w.WriteHeader(http.StatusInternalServerError)508 response, _ := types.ServerResponse{509 Status: http.StatusText(http.StatusInternalServerError),510 Message: "cannot_create_file",511 }.MarshalJSON()512 _, _ = w.Write(response)513 return514 }515 if !exist {516 w.WriteHeader(http.StatusForbidden)517 response, _ := types.ServerResponse{518 Status: http.StatusText(http.StatusForbidden),519 Message: "unauthorized_user",520 }.MarshalJSON()521 _, _ = w.Write(response)522 return523 }524 err = r.ParseMultipartForm(0)525 if err != nil {526 log.Print("handlers SetAvatar ParseMultipartForm: " + err.Error())527 return528 }529 file, handler, err := r.FormFile("avatar")530 if err != nil {531 fmt.Println(err)532 w.WriteHeader(http.StatusBadRequest)533 response, _ := types.ServerResponse{534 Status: http.StatusText(http.StatusBadRequest),535 Message: "cannot_get_file",536 }.MarshalJSON()537 _, _ = w.Write(response)538 return539 }540 defer func() { _ = file.Close() }()541 // /var/www/media/images/login.jpeg542 fileName := user.Login + filepath.Ext(handler.Filename)543 f, err := os.Create(*e.Config.ImagesRoot + "/" + fileName)544 if err != nil {545 fmt.Println(err)546 w.WriteHeader(http.StatusInternalServerError)547 response, _ := types.ServerResponse{548 Status: http.StatusText(http.StatusInternalServerError),549 Message: "cannot_create_file",550 }.MarshalJSON()551 _, _ = w.Write(response)552 return553 }554 defer func() { _ = f.Close() }()555 //put avatar path to db556 err = e.DB.UpdateUsersAvatarByLogin(user.Login, "/media/images/"+fileName)557 if err != nil {558 log.Print(err)559 w.WriteHeader(http.StatusInternalServerError)560 response, _ := types.ServerResponse{561 Status: http.StatusText(http.StatusInternalServerError),562 Message: "database_error",563 }.MarshalJSON()564 _, _ = w.Write(response)565 return566 }567 _, _ = io.Copy(f, file)568 w.WriteHeader(http.StatusCreated)569 response, _ := types.ServerResponse{570 Status: http.StatusText(http.StatusCreated),571 Message: "successful_avatar_uploading",572 }.MarshalJSON()573 _, _ = w.Write(response)574}575func (e *Environment) ErrorMethodNotAllowed(w http.ResponseWriter, r *http.Request) {576 _ = r.Body.Close()577 w.WriteHeader(http.StatusMethodNotAllowed)578 response, _ := types.ServerResponse{579 Status: http.StatusText(http.StatusMethodNotAllowed),580 Message: "this_method_is_not_supported",581 }.MarshalJSON()582 _, _ = w.Write(response)583}584func (e *Environment) ErrorRequiredField(w http.ResponseWriter, r *http.Request) {585 _ = r.Body.Close()586 w.WriteHeader(http.StatusBadRequest)587 response, _ := types.ServerResponse{588 Status: http.StatusText(http.StatusBadRequest),589 Message: "field_'temporary'_required",590 }.MarshalJSON()591 _, _ = w.Write(response)592}...
movie_test.go
Source:movie_test.go
...14}`15 expectedTouchLvl = []int{5, 19}16 expectedTouchNodes = 2417 stmt := Execute("Movies", input)18 result := stmt.MarshalJSON()19 t.Log(stmt.String())20 validate(t, result)21}22func TestMovieCrusade(t *testing.T) {23 input := `{24 me(func: allofterms(title, "jones indiana crusade")) {25 title26 film.genre {27 name28 }29 }30}`31 expectedTouchLvl = []int{1, 4}32 expectedTouchNodes = 533 stmt := Execute("Movies", input)34 result := stmt.MarshalJSON()35 t.Log(stmt.String())36 validate(t, result)37}38func TestMovieEq(t *testing.T) {39 input := `{40 me(func:eq(title, "Poison")) {41 title42 film.genre {43 name44 }45 }46}`47 expectedTouchLvl = []int{1, 7}48 expectedTouchNodes = 849 stmt := Execute("Movies", input)50 result := stmt.MarshalJSON()51 t.Log(stmt.String())52 validate(t, result)53}54func TestMovie1a(t *testing.T) {55 input := `{56 me(func: eq(name, "Steven Spielberg")) @filter(has(director.film)) {57 name58 director.film {59 title60 }61 }62}`63 expectedTouchLvl = []int{1, 30}64 expectedTouchNodes = 3165 stmt := Execute("Movies", input)66 result := stmt.MarshalJSON()67 t.Log(stmt.String())68 validate(t, result)69}70func TestMovie1b(t *testing.T) {71 input := `{72 me(func: eq(name, "Steven Spielberg")) @filter(has(director.film)) {73 name74 director.film @filter(anyofterms(title,"War Minority") {75 title76 }77 }78}`79 expectedTouchLvl = []int{1, 3}80 expectedTouchNodes = 481 stmt := Execute("Movies", input)82 result := stmt.MarshalJSON()83 t.Log(stmt.String())84 validate(t, result)85}86func TestMovie1c(t *testing.T) {87 input := `{88 me(func: eq(count(film.genre), 13)) {89 title90 film.genre {91 name92 }93 }94}`95 expectedTouchLvl = []int{6, 78}96 expectedTouchNodes = 8497 stmt := Execute("Movies", input)98 result := stmt.MarshalJSON()99 t.Log(stmt.String())100 validate(t, result)101}102func TestMovie1d(t *testing.T) {103 input := `{104 me(func: eq(count(film.genre), 13)) {105 title106 film.director {107 name108 }109 }110}`111 expectedTouchLvl = []int{6, 6}112 expectedTouchNodes = 12113 stmt := Execute("Movies", input)114 result := stmt.MarshalJSON()115 t.Log(stmt.String())116 validate(t, result)117}118func TestMovie1e(t *testing.T) {119 input := `{120 me(func: eq(count(film.genre), 13)) {121 title122 film.director {123 name124 }125 film.genre {126 name127 }128 }129}`130 expectedTouchLvl = []int{6, 84}131 expectedTouchNodes = 90132 stmt := Execute("Movies", input)133 t.Log(stmt.String())134 result := stmt.MarshalJSON()135 t.Log(stmt.String())136 validate(t, result)137}138func TestMovie1g(t *testing.T) {139 input := `{140 me(func: eq(count(film.genre), 13)) {141 title142 film.genre @filter( anyofterms(name, "Musical comedy" )) {143 name144 }145 film.director {146 name147 }148 }149}`150 expectedTouchLvl = []int{6, 20}151 expectedTouchNodes = 26152 stmt := Execute("Movies", input)153 t.Log(stmt.String())154 result := stmt.MarshalJSON()155 t.Log(stmt.String())156 validate(t, result)157}158func TestMoviePS0(t *testing.T) {159 input := `{160 me(func: eq(name,"Peter Sellers") ) {161 name162 actor.performance {163 performance.film {164 title165 }166 performance.character {167 name168 }169 performance.actor {170 name171 }172 }173}174}`175 expectedTouchLvl = []int{1, 15, 45}176 expectedTouchNodes = 61177 stmt := Execute("Movies", input)178 t.Log(stmt.String())179 result := stmt.MarshalJSON()180 t.Log(stmt.String())181 validate(t, result)182}183func TestMoviePS2(t *testing.T) {184 input := `{185 me(func: eq(name,"Peter Sellers") ) {186 name187 actor.performance {188 performance.film {189 title190 film.director {191 name192 }193 }194 }195}196}`197 expectedTouchLvl = []int{1, 15, 15, 19}198 expectedTouchNodes = 50199 stmt := Execute("Movies", input)200 t.Log(stmt.String())201 result := stmt.MarshalJSON()202 t.Log(stmt.String())203 validate(t, result)204}205func TestMoviePS3a(t *testing.T) {206 input := `{207 me(func: eq(name,"Peter Sellers") ) {208 name209 actor.performance {210 performance.film {211 title212 film.director {213 name214 }215 film.performance {216 performance.actor {217 name218 }219 performance.character {220 name221 }222 }223 }224 }225}226}`227 expectedTouchLvl = []int{1, 15, 15, 391, 744}228 expectedTouchNodes = 1166229 stmt := Execute("Movies", input)230 t0 := time.Now()231 result := stmt.MarshalJSON()232 t1 := time.Now()233 t.Log("Marshal elapsedTime; ", t1.Sub(t0))234 t.Log(stmt.String())235 validate(t, result)236}237func TestMoviePS3b(t *testing.T) {238 input := `{239 me(func: eq(name,"Peter Sellers") ) {240 name241 actor.performance {242 performance.film {243 title244 film.director @filter(eq(name,"Stanley Kubrick") ) {245 name246 }247 }248 }249}250}`251 expectedTouchLvl = []int{1, 15, 15, 4}252 expectedTouchNodes = 35253 stmt := Execute("Movies", input)254 t.Log(stmt.String())255 result := stmt.MarshalJSON()256 t.Log(stmt.String())257 validate(t, result)258}259func TestMoviePS3c(t *testing.T) {260 input := `{261 me(func: eq(name,"Peter Sellers") ) {262 name263 actor.performance {264 performance.film {265 title266 film.director {267 name268 }269 }270 performance.character {271 name272 }273 performance.actor {274 name275 }276 }277}278}`279 expectedTouchLvl = []int{1, 15, 45, 19}280 expectedTouchNodes = 80281 stmt := Execute("Movies", input)282 t.Log(stmt.String())283 result := stmt.MarshalJSON()284 t.Log(stmt.String())285 validate(t, result)286}287func TestMoviePS3d(t *testing.T) {288 input := `{289 me(func: eq(name,"Peter Sellers") ) {290 name291 actor.performance {292 performance.character {293 name294 }295 }296}297}`298 expectedTouchLvl = []int{1, 15, 15}299 expectedTouchNodes = 31300 stmt := Execute("Movies", input)301 t.Log(stmt.String())302 result := stmt.MarshalJSON()303 t.Log(stmt.String())304 validate(t, result)305}306func TestMoviePS3e(t *testing.T) {307 input := `{308 me(func: eq(name,"Peter Sellers") ) {309 name310 actor.performance {311 performance.film {312 title313 }314 performance.character {315 name316 }317 performance.actor {318 name319 }320 }321}322}`323 expectedTouchLvl = []int{1, 15, 45}324 expectedTouchNodes = 61325 stmt := Execute("Movies", input)326 t.Log(stmt.String())327 result := stmt.MarshalJSON()328 t.Log(stmt.String())329 validate(t, result)330}331// func TestMoviePS4(t *testing.T) {332// input := `{333// me(func: eq(name,"Peter Sellers") ) {334// name335// actor.performance {336// performance.film @filter( eq(film.director,variable(<stanley-kubrick-uid>) ) {337// title338// film.director ) {339// name340// }341// }342// }343// }344// }`345// expectedTouchLvl = []int{1, 15, 15, 4}346// expectedTouchNodes = 35347// stmt := Execute("Movies", input)348// t.Log(stmt.String())349// result := stmt.MarshalJSON()350// t.Log(stmt.String())351// validate(t, result)352// }353func TestMovieFilms(t *testing.T) {354 input := `{355 Mackenzie(func:allofterms(name, "crook mackenzie")) {356 name357 actor.performance {358 performance.film {359 title360 }361 performance.character {362 name363 }364 }365 }366}`367 expectedTouchLvl = []int{1, 8, 16}368 expectedTouchNodes = 25369 stmt := Execute("Movies", input)370 t0 := time.Now()371 result := stmt.MarshalJSON()372 t1 := time.Now()373 t.Log("Marshal elapsedTime; ", t1.Sub(t0))374 t.Log(stmt.String())375 validate(t, result)376}...
ingredients.go
Source:ingredients.go
...11func Ingredients_All(ctx *fasthttp.RequestCtx) {12 log.Println("Ingredients All: " + string(ctx.Method()) + (" ") + string(ctx.Path()))13 ingredients_ := make(models.IngredientArr, 0, common.Limit)14 code, message := ingredients.All(&ingredients_)15 ingredientsJSON, _ := ingredients_.MarshalJSON()16 switch code {17 case fasthttp.StatusOK:18 ctx.SetStatusCode(fasthttp.StatusOK)19 ctx.SetBody(ingredientsJSON)20 case fasthttp.StatusInternalServerError:21 ctx.SetStatusCode(fasthttp.StatusInternalServerError)22 m := &models.Msg{}23 m.Message = message24 mJSON, _ := m.MarshalJSON()25 ctx.SetBody(mJSON)26 }27}28func Ingredients_All(ctx *fasthttp.RequestCtx) {29 log.Println("Ingredients All: " + string(ctx.Method()) + (" ") + string(ctx.Path()))30 ingredients_ := make(models.IngredientArr, 0, common.Limit)31 code, message := ingredients.All(&ingredients_)32 ingredientsJSON, _ := ingredients_.MarshalJSON()33 switch code {34 case fasthttp.StatusOK:35 ctx.SetStatusCode(fasthttp.StatusOK)36 ctx.SetBody(ingredientsJSON)37 case fasthttp.StatusInternalServerError:38 ctx.SetStatusCode(fasthttp.StatusInternalServerError)39 m := &models.Msg{}40 m.Message = message41 mJSON, _ := m.MarshalJSON()42 ctx.SetBody(mJSON)43 }44}45*/46func Ingredients_About(ctx *fasthttp.RequestCtx) {47 log.Println("Ingredients About: " + string(ctx.Method()) + (" ") + string(ctx.Path()))48 ingredientName, ingredientID := common.NameOrID(ctx)49 var code int50 var message string51 i := &models.Ingredient{}52 if ingredientID != 0 {53 code, message = ingredients.About("", ingredientID, i)54 } else {55 code, message = ingredients.About(ingredientName, 0, i)56 }57 iJSON, _ := i.MarshalJSON()58 switch code {59 case fasthttp.StatusOK:60 ctx.SetStatusCode(fasthttp.StatusOK)61 ctx.SetBody(iJSON)62 case fasthttp.StatusNotFound:63 ctx.SetStatusCode(fasthttp.StatusNotFound)64 m := &models.Msg{}65 m.Message = message66 mJSON, _ := m.MarshalJSON()67 ctx.SetBody(mJSON)68 case fasthttp.StatusInternalServerError:69 ctx.SetStatusCode(fasthttp.StatusInternalServerError)70 m := &models.Msg{}71 m.Message = message72 mJSON, _ := m.MarshalJSON()73 ctx.SetBody(mJSON)74 }75}76func Ingredients_Search_Paginated(ctx *fasthttp.RequestCtx) {77 log.Println("Ingredients Search: " + string(ctx.Method()) + (" ") + string(ctx.Path()))78 ingredientName, _ := common.NameOrID(ctx)79 count, _ := strconv.Atoi(ctx.UserValue("count").(string))80 page, _ := strconv.Atoi(ctx.UserValue("page").(string))81 if count > 50 {82 count = 5083 } else if count < 1 {84 count = 185 }86 if page > 50 {87 page = 5088 } else if page < 0 {89 page = 090 }91 offset := count * page92 var code int93 var message string94 ings := models.IngredientArr{}95 code, message = ingredients.Search(ingredientName, count, offset, &ings)96 iJSON, _ := ings.MarshalJSON()97 switch code {98 case fasthttp.StatusOK:99 ctx.SetStatusCode(fasthttp.StatusOK)100 ctx.SetBody(iJSON)101 case fasthttp.StatusNotFound:102 ctx.SetStatusCode(fasthttp.StatusNotFound)103 m := &models.Msg{}104 m.Message = message105 mJSON, _ := m.MarshalJSON()106 ctx.SetBody(mJSON)107 case fasthttp.StatusInternalServerError:108 ctx.SetStatusCode(fasthttp.StatusInternalServerError)109 m := &models.Msg{}110 m.Message = message111 mJSON, _ := m.MarshalJSON()112 ctx.SetBody(mJSON)113 }114}115func Ingredients_Search(ctx *fasthttp.RequestCtx) {116 log.Println("Ingredients Search: " + string(ctx.Method()) + (" ") + string(ctx.Path()))117 ingredientName, _ := common.NameOrID(ctx)118 count := 10119 page := 0120 offset := count * page121 var code int122 var message string123 ings := models.IngredientArr{}124 code, message = ingredients.Search(ingredientName, count, offset, &ings)125 iJSON, _ := ings.MarshalJSON()126 switch code {127 case fasthttp.StatusOK:128 ctx.SetStatusCode(fasthttp.StatusOK)129 ctx.SetBody(iJSON)130 case fasthttp.StatusNotFound:131 ctx.SetStatusCode(fasthttp.StatusNotFound)132 m := &models.Msg{}133 m.Message = message134 mJSON, _ := m.MarshalJSON()135 ctx.SetBody(mJSON)136 case fasthttp.StatusInternalServerError:137 ctx.SetStatusCode(fasthttp.StatusInternalServerError)138 m := &models.Msg{}139 m.Message = message140 mJSON, _ := m.MarshalJSON()141 ctx.SetBody(mJSON)142 }143}144func Ingredients_Top(ctx *fasthttp.RequestCtx) {145 log.Println("Ingredients Top: " + string(ctx.Method()) + (" ") + string(ctx.Path()))146 count, _ := strconv.Atoi(ctx.UserValue("count").(string))147 page, _ := strconv.Atoi(ctx.UserValue("page").(string))148 if count > 50 {149 count = 50150 } else if count < 1 {151 count = 1152 }153 if page > 50 {154 page = 50155 } else if page < 0 {156 page = 0157 }158 offset := count * page159 var code int160 var message string161 ings := models.IngredientArr{}162 code, message = ingredients.Top(count, offset, &ings)163 iJSON, _ := ings.MarshalJSON()164 switch code {165 case fasthttp.StatusOK:166 ctx.SetStatusCode(fasthttp.StatusOK)167 ctx.SetBody(iJSON)168 case fasthttp.StatusNotFound:169 ctx.SetStatusCode(fasthttp.StatusNotFound)170 m := &models.Msg{}171 m.Message = message172 mJSON, _ := m.MarshalJSON()173 ctx.SetBody(mJSON)174 case fasthttp.StatusInternalServerError:175 ctx.SetStatusCode(fasthttp.StatusInternalServerError)176 m := &models.Msg{}177 m.Message = message178 mJSON, _ := m.MarshalJSON()179 ctx.SetBody(mJSON)180 }181}182func Ingredients_GroupAll(ctx *fasthttp.RequestCtx) {183 log.Println("Ingredients About: " + string(ctx.Method()) + (" ") + string(ctx.Path()))184 groupName, groupID := common.NameOrID(ctx)185 ingredients_ := make(models.IngredientArr, 0, common.Limit)186 var code int187 var message string188 if groupID != 0 {189 code, message = ingredients.GroupAll("", groupID, &ingredients_)190 } else {191 code, message = ingredients.GroupAll(groupName, 0, &ingredients_)192 }193 ingredientsJSON, _ := ingredients_.MarshalJSON()194 switch code {195 case fasthttp.StatusOK:196 ctx.SetStatusCode(fasthttp.StatusOK)197 ctx.SetBody(ingredientsJSON)198 case fasthttp.StatusInternalServerError:199 ctx.SetStatusCode(fasthttp.StatusInternalServerError)200 m := &models.Msg{}201 m.Message = message202 mJSON, _ := m.MarshalJSON()203 ctx.SetBody(mJSON)204 }205}...
MarshalJSON
Using AI Code Generation
1import (2type Log struct {3}4func (l *Log) MarshalJSON() ([]byte, error) {5 return json.Marshal(map[string]interface{}{6 })7}8func main() {9 l := &Log{10 }11 enc := json.NewEncoder(os.Stdout)12 enc.SetEscapeHTML(false)13 if err := enc.Encode(l); err != nil {14 log.Fatal(err)15 }16}17{"message":"hello"}
MarshalJSON
Using AI Code Generation
1import (2type log struct {3}4func (l log) MarshalJSON() ([]byte, error) {5 return []byte(`"hello"`), nil6}7func main() {8 l := log{Level: "info"}9 b, err := json.Marshal(l)10 if err != nil {11 fmt.Println(err)12 }13 fmt.Println(string(b))14}15import (16type log struct {17}18func (l log) MarshalJSON() ([]byte, error) {19 return []byte(`"hello"`), nil20}21func main() {22 l := log{Level: "info"}23 b, err := json.Marshal(l)24 if err != nil {25 fmt.Println(err)26 }27 fmt.Println(string(b))28}29import (30type log struct {31}32func (l log) MarshalJSON() ([]byte, error) {33 return []byte(`"hello"`), nil34}35func main() {36 l := log{Level: "info"}37 b, err := json.Marshal(l)38 if err != nil {39 fmt.Println(err)40 }41 fmt.Println(string(b))42}43import (44type log struct {45}46func (l log) MarshalJSON() ([]byte, error) {47 return []byte(`"hello"`), nil48}49func main() {50 l := log{Level: "info"}51 b, err := json.Marshal(l)52 if err != nil {53 fmt.Println(err)54 }55 fmt.Println(string(b))56}57import (
MarshalJSON
Using AI Code Generation
1import (2type Log struct {3}4func (log Log) MarshalJSON() ([]byte, error) {5 json := fmt.Sprintf(`{"message": "%s", "time": "%d"}`, log.Message, log.Time)6 return []byte(json), nil7}8func main() {9 log := Log{10 }11 bytes, _ := json.Marshal(log)12 fmt.Println(string(bytes))13}14{"message": "Hello", "time": "100"}
MarshalJSON
Using AI Code Generation
1import (2type Log struct {3}4func (l Log) MarshalJSON() ([]byte, error) {5 return json.Marshal(struct {6 }{7 })8}9func main() {10 log := Log{"Hello, playground"}11 b, _ := json.Marshal(log)12 fmt.Println(string(b))13}14{"message":"Hello, playground"}15import (16type Log struct {17}18func (l Log) MarshalJSON() ([]byte, error) {19 return json.Marshal(struct {20 }{21 })22}23func main() {24 log := Log{"Hello, playground"}25 b, _ := json.MarshalIndent(log, "", " ")26 fmt.Println(string(b))27}28{29}30import (31type Log struct {32}33func (l Log) MarshalJSON() ([]byte, error) {34 return json.Marshal(struct {35 }{36 })37}38func main() {39 log := Log{"Hello, playground"}40 b, _ := json.MarshalIndent(log, "", " ")41 fmt.Println(string(b))42}43{44}45import (46type Log struct {47}48func (l Log) MarshalJSON() ([]byte, error) {49 return json.Marshal(struct {50 }{51 })52}53func main() {54 log := Log{"Hello, playground"}55 b, _ := json.MarshalIndent(log, "", " ")56 fmt.Println(string(b))57}58{59}
MarshalJSON
Using AI Code Generation
1import (2func main() {3 f, err := os.OpenFile("log.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)4 if err != nil {5 fmt.Println("Error creating file")6 }7 defer f.Close()8 l := log.New(f, "prefix", log.LstdFlags)9 l.Println("This is a log message")10 l.SetPrefix("newprefix")11 l.Println("This is another log message")12}
MarshalJSON
Using AI Code Generation
1import (2type log struct {3}4func main() {5 l := log{6 }7 b, err := json.Marshal(l)8 if err != nil {9 fmt.Println(err)10 }11 fmt.Println(string(b))12}13{"level":"info","message":"this is an info message"}14import (15type log struct {16}17func (l log) MarshalJSON() ([]byte, error) {18 return json.Marshal(&struct {19 }{20 Alias: (*Alias)(&l),21 })22}23func main() {24 l := log{25 }26 b, err := json.Marshal(l)27 if err != nil {28 fmt.Println(err)29 }30 fmt.Println(string(b))31}32{"level":"info","message":"this is an info message"}33import (34type log struct {35}36func (l log) MarshalJSON() ([]byte, error) {37 return json.Marshal(&struct {38 }{39 Alias: (*Alias)(&l),40 })41}42func main() {43 l := log{44 }45 b, err := json.Marshal(l)46 if err != nil {47 fmt.Println(err)48 }49 fmt.Println(string(b))50}51{"level":"info","message":"this is an info message"}
MarshalJSON
Using AI Code Generation
1func main() {2 log = Log{"test", "test", "test", "test"}3 file, err := os.Create("log.json")4 if err != nil {5 log.Fatal(err)6 }7 b, err := json.Marshal(log)8 if err != nil {9 log.Fatal(err)10 }11 file.Write(b)12}13{14}15func main() {16 log = Log{"test", "test", "test", "test"}17 file, err := os.Create("log.json")18 if err != nil {19 log.Fatal(err)20 }21 b, err := json.MarshalIndent(log, "", " ")22 if err != nil {23 log.Fatal(err)24 }25 file.Write(b)26}27{28}29func (l *Log) MarshalJSON() ([]byte, error) {30 return json.Marshal(*l)31}32func main() {33 log = Log{"test", "test", "test", "test"}34 file, err := os.Create("log.json")35 if err != nil {36 log.Fatal(err)37 }38 b, err := log.MarshalJSON()39 if err != nil {40 log.Fatal(err)41 }42 file.Write(b)43}44{
MarshalJSON
Using AI Code Generation
1import (2type Log struct {3}4func (l Log) MarshalJSON() ([]byte, error) {5 return []byte(fmt.Sprintf(`{"Name":"%s","Value":%d}`, l.Name, l.Value)), nil6}7func main() {8 l := Log{"A", 1}9 b, _ := json.Marshal(l)10 fmt.Println(string(b))11}12{"Name":"A","Value":1}13UnmarshalJSON() method14import (15type Log struct {16}17func (l *Log) UnmarshalJSON(b []byte) error {18 fmt.Println("UnmarshalJSON is called")19}20func main() {21 l := Log{}22 json.Unmarshal([]byte(`{"Name":"A","Value":1}`), &l)23}24MarshalXML() method25import (
MarshalJSON
Using AI Code Generation
1log := log{Time: time.Now(), Message: "message"}2bytes, _ := json.Marshal(log)3log := log{Time: time.Now(), Message: "message"}4bytes, _ := json.Marshal(log)5log := log{Time: time.Now(), Message: "message"}6bytes, _ := json.Marshal(log)7log := log{Time: time.Now(), Message: "message"}8bytes, _ := json.Marshal(log)9log := log{Time: time.Now(), Message: "message"}10bytes, _ := json.Marshal(log)11log := log{Time: time.Now(), Message: "message"}12bytes, _ := json.Marshal(log)13log := log{Time: time.Now(), Message: "message"}14bytes, _ := json.Marshal(log)
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!