How to use MarshalJSON method of types Package

Best K6 code snippet using types.MarshalJSON

room_master.go

Source:room_master.go Github

copy

Full Screen

...22 }23 event := types.Event{}24 err := event.UnmarshalJSON(message)25 if err != nil {26 response, _ := types.ErrorMessage("error while parsing first level: " + err.Error()).MarshalJSON()27 response, _ = types.Event{28 Method: "error_message",29 Parameter: response,30 }.MarshalJSON()31 if role == 0 {32 r.Messaging.User0To <- response33 } else {34 r.Messaging.User1To <- response35 }36 continue37 }38 if event.Method == "upload_map" {39 err := r.UploadMap(role, event.Parameter)40 if err != nil {41 response, _ := types.ErrorMessage("error while process 'upload_map': " + err.Error()).MarshalJSON()42 response, _ = types.Event{43 Method: "error_message",44 Parameter: response,45 }.MarshalJSON()46 if role == 0 {47 r.Messaging.User0To <- response48 } else {49 r.Messaging.User1To <- response50 }51 if r.User0UploadedCharacters && r.User1UploadedCharacters {52 r.DownloadMap(role)53 }54 }55 continue56 }57 if event.Method == "attempt_go_to_cell" {58 gameover, err := r.AttemptGoToCell(role, event.Parameter)59 if err != nil {60 response, _ := types.ErrorMessage("error while process 'attempt_go_to_cell': " + err.Error()).MarshalJSON()61 response, _ = types.Event{62 Method: "error_message",63 Parameter: response,64 }.MarshalJSON()65 if role == 0 {66 r.Messaging.User0To <- response67 } else {68 r.Messaging.User1To <- response69 }70 if r.User0UploadedCharacters && r.User1UploadedCharacters {71 r.DownloadMap(role)72 }73 }74 if gameover {75 // к этому моменту эже все данные должны быть отправлены. только сетевые вопросы и остановка всех 5-и горутин.76 r.StopRoom()77 // отрегистирует в Rooms.78 r.RemoveRoom()79 break80 }81 continue82 }83 if event.Method == "reassign_weapons" {84 err = r.ReassignWeapons(role, event.Parameter)85 if err != nil {86 response, _ := types.ErrorMessage("error while process 'reassign_weapons': " + err.Error()).MarshalJSON()87 response, _ = types.Event{88 Method: "error_message",89 Parameter: response,90 }.MarshalJSON()91 if role == 0 {92 r.Messaging.User0To <- response93 } else {94 r.Messaging.User1To <- response95 }96 if r.User0UploadedCharacters && r.User1UploadedCharacters {97 r.DownloadMap(role)98 }99 }100 continue101 }102 // если ни один из трёх методов не отработал, прислали меверный метод, кидаем ошибку103 response, _ := types.Event{104 Method: "error_message",105 Parameter: easyjson.RawMessage("unknown method '" + event.Method + "', " +106 "available only ['attempt_go_to_cell', 'upload_map', 'reassign_weapons']."),107 }.MarshalJSON()108 if role == 0 {109 r.Messaging.User0To <- response110 } else {111 r.Messaging.User1To <- response112 }113 }114 log.Print("GameMaster for room = " + r.OwnNumber.String() + " correctly completed.")115 return116}117// ответственность: загружает данные от пользователя, начинает игру118func (r *Room) UploadMap(role RoleId, message easyjson.RawMessage) (err error) {119 var uploadedMap types.UploadMap120 err = uploadedMap.UnmarshalJSON(message)121 if err != nil {122 err = errors.Wrap(err, "in json.Unmarshal message into types.UploadMap: ")123 return124 }125 if role == 0 {126 if !r.User0UploadedCharacters {127 // uploadedMap.Weapons для клеток 13 12 11 10 9 8 7 6 5 4 3 2 1 0128 var numberOfFlags int129 for i := 0; i < 14; i++ {130 j := 13 - i131 var weapon Weapon132 weapon, err = NewWeapon(uploadedMap.Weapons[i])133 if err != nil {134 err = errors.Wrap(err, "in NewWeapon: ")135 return136 }137 if weapon == "flag" {138 numberOfFlags++139 }140 r.Map[j] = &Сharacter{141 Role: role,142 Weapon: weapon,143 }144 }145 if numberOfFlags != 1 {146 err = errors.New("map must contain exactly one flag, but " +147 strconv.Itoa(numberOfFlags) + " found")148 return149 }150 r.User0UploadedCharacters = true151 } else {152 err = errors.New("characters already loaded")153 return154 }155 } else {156 if !r.User1UploadedCharacters {157 // 28 29 30 31 32 33 34 35 36 37 38 39 40 41158 var numberOfFlags int159 for i := 0; i < 14; i++ {160 j := 28 + i161 var weapon Weapon162 weapon, err = NewWeapon(uploadedMap.Weapons[i])163 if err != nil {164 err = errors.Wrap(err, "in NewWeapon: ")165 return166 }167 if weapon == "flag" {168 numberOfFlags++169 }170 r.Map[j] = &Сharacter{171 Role: role,172 Weapon: weapon,173 }174 }175 if numberOfFlags != 1 {176 err = errors.New("map must contain exactly one flag, but " +177 strconv.Itoa(int(numberOfFlags)) + " found")178 return179 }180 r.User1UploadedCharacters = true181 } else {182 err = errors.New("characters already loaded")183 return184 }185 }186 if r.User0UploadedCharacters && r.User1UploadedCharacters {187 // Отсылает карту188 r.DownloadMap(0)189 r.DownloadMap(1)190 // Отсылает логин соперника191 r.YourRival(0)192 r.YourRival(1)193 // Отправляет чей ход194 r.YourTurn(0)195 r.YourTurn(1)196 }197 return198}199// ответственность: отправляет карту на клиент, не изменяет карту.200func (r *Room) DownloadMap(role RoleId) {201 downloadMap := types.DownloadMap{}202 for i := 0; i < len(r.Map); i++ {203 if r.Map[i] == nil {204 continue205 }206 var cell = &types.MapCell{}207 // true, если собственный персонаж208 cell.User = r.Map[i].Role == role209 // оружие видно только если это собственный игрок или противник показал оружие.210 if r.Map[i].Role == role || r.Map[i].ShowedWeapon {211 weapon := string(r.Map[i].Weapon)212 cell.Weapon = &weapon213 }214 downloadMap[i] = cell215 }216 if role == 0 {217 downloadMap.Rotate()218 }219 parameter, _ := downloadMap.MarshalJSON()220 response, _ := types.Event{221 Method: "download_map",222 Parameter: parameter,223 }.MarshalJSON()224 if role == 0 {225 r.Messaging.User0To <- response226 } else {227 r.Messaging.User1To <- response228 }229 return230}231// ответственность: отправляет описание соперника, не изменяет карту.232func (r *Room) YourRival(role RoleId) {233 if role == 0 {234 response, _ := types.YourRival(r.User1.Login).MarshalJSON()235 response, _ = types.Event{236 Method: "your_rival",237 Parameter: []byte(response),238 }.MarshalJSON()239 r.Messaging.User1To <- response240 } else {241 response, _ := types.YourRival(r.User0.Login).MarshalJSON()242 response, _ = types.Event{243 Method: "your_rival",244 Parameter: []byte(response),245 }.MarshalJSON()246 r.Messaging.User0To <- response247 }248 return249}250// ответственность: отправляет стат чей ход, не изменяет карту.251func (r *Room) YourTurn(role RoleId) {252 var response []byte253 if types.YourTurn(r.UserTurnNumber == role) {254 response = []byte("true")255 } else {256 response = []byte("false")257 }258 response, _ = types.Event{259 Method: "your_turn",260 Parameter: response,261 }.MarshalJSON()262 if role == 0 {263 r.Messaging.User0To <- response264 } else {265 r.Messaging.User1To <- response266 }267 return268}269// ответственность: принимает данные от пользователя, обрабатывает с учётом состояния,270// изменяет согласно игровой механике карту (фактически содержит всю игру в себе 😮)271// вызывает функции, отправляющие запросы.272func (r *Room) AttemptGoToCell(role RoleId, message easyjson.RawMessage) (gameOver bool, err error) {273 var attemptGoToCell types.AttemptGoToCell274 err = attemptGoToCell.UnmarshalJSON(message)275 if err != nil {276 err = errors.Wrap(err, "in json.Unmarshal message into types.attemptGoToCell: ")277 return278 }279 err = attemptGoToCell.Check()280 if err != nil {281 err = errors.Wrap(err, "invalid coordinates: ")282 return283 }284 if role == 0 {285 attemptGoToCell.Rotate()286 }287 gameOver, err = r.AttemptGoToCellLogic(role, attemptGoToCell.From, attemptGoToCell.To)288 return289}290func (r *Room) AttemptGoToCellLogic(role RoleId, from int, to int) (gameOver bool, err error) {291 // Что бы пользователю можно было сделать ход, нужно,292 // что бы персонажи были загружены обоими игроками,293 // не было спора про перевыбор оружия в данный момент неоконченного294 // и был ход этого игрока.295 if r.UserTurnNumber != role {296 err = errors.New("it's not your turn now")297 return298 }299 if !r.User0UploadedCharacters || !r.User1UploadedCharacters {300 err = errors.New("The map is not loaded yet. Wait for it.")301 return302 }303 if r.WeaponReElection.WaitingForIt {304 err = errors.New("At that moment you still need to reassign the weapon.")305 return306 }307 if r.Map[from] == nil {308 err = errors.New("there is no character at " + strconv.Itoa(from))309 return310 }311 if r.Map[from].Role != role {312 err = errors.New("this is not your character at " + strconv.Itoa(from))313 return314 }315 // Тут точно существующий персонаж, принадлежащий игроку.316 // Сервер смотрит, куда перемещается персонаж и, если целевая клетка пуста,317 // перемещает персонажа на сервере и клиентах.318 if r.Map[to] == nil {319 r.Map[to], r.Map[from] = r.Map[from], nil320 if r.UserTurnNumber == 0 {321 r.UserTurnNumber = 1322 } else {323 r.UserTurnNumber = 0324 }325 r.MoveCharacter(0, from, to)326 r.MoveCharacter(1, from, to)327 r.YourTurn(0)328 r.YourTurn(1)329 return330 }331 // если в целевой клетке ты332 if r.Map[to].Role == role {333 err = errors.New("attempt to attack yourself")334 return335 }336 // проверяем, нет ли там флага337 if r.Map[to].Weapon == "flag" {338 log.Print("game over in room = " + r.OwnNumber.String())339 r.Gameover(0, role, from, to)340 r.Gameover(1, role, from, to)341 gameOver = true342 // TODO: каскадный деструктор всего, но не раньше, чем отработают отправляющие сообщения горутины.343 // TODO: запись в базу о конце игры.344 return345 }346 // проверяем победу над обычным оружием.347 if r.Map[from].Weapon.IsExceed(r.Map[to].Weapon) {348 winnerWeapon := r.Map[from].Weapon349 loserWeapon := r.Map[to].Weapon350 // двигаем персонажа351 r.Map[to] = r.Map[from]352 r.Map[from] = nil353 // ставим, что оружие победителя спалилось.354 r.Map[to].ShowedWeapon = true355 // меняем ход // TODO: Возможно, стоит использовать bool в качестве роли.356 if r.UserTurnNumber == 0 {357 r.UserTurnNumber = 1358 } else {359 r.UserTurnNumber = 0360 }361 // отсылаем изменения.362 r.Attack(0, from, winnerWeapon, to, loserWeapon)363 r.Attack(1, from, winnerWeapon, to, loserWeapon)364 // отсылаем смену хода365 r.YourTurn(0)366 r.YourTurn(1)367 return368 }369 // проверяем поражение370 if r.Map[to].Weapon.IsExceed(r.Map[from].Weapon) {371 winnerWeapon := r.Map[to].Weapon372 loserWeapon := r.Map[from].Weapon373 // убираем проигравшего нападавшего персонажа, победитель передвигается на клетку проигравшего.374 r.Map[from] = nil375 // ставим, что оружие победителя спалилось.376 r.Map[to].ShowedWeapon = true377 // меняем ход378 if r.UserTurnNumber == 0 {379 r.UserTurnNumber = 1380 } else {381 r.UserTurnNumber = 0382 }383 // отсылаем изменения.384 r.Attack(0, to, winnerWeapon, from, loserWeapon)385 r.Attack(1, to, winnerWeapon, from, loserWeapon)386 // отсылаем смену хода387 r.YourTurn(0)388 r.YourTurn(1)389 return390 }391 // проверяем, что одинаковое оружие392 if r.Map[to].Weapon == r.Map[from].Weapon {393 fmt.Print(r.Map)394 // запускаем процедуру перевыбора.395 r.WeaponReElection.WaitingForIt = true396 r.WeaponReElection.User0ReElect = false397 r.WeaponReElection.User1ReElect = false398 r.WeaponReElection.AttackingCharacter = from399 r.WeaponReElection.AttackedCharacter = to400 // просим игроков перевыбрать оружие для своего персонажа, ход не меняется.401 if r.UserTurnNumber == 0 {402 r.WeaponChangeRequest(0, from)403 r.WeaponChangeRequest(1, to)404 } else {405 r.WeaponChangeRequest(1, from)406 r.WeaponChangeRequest(0, to)407 }408 return409 }410 return411}412// ответственность: проводит загружает перевыбранное оружие,413// вызывает AttemptGoToCell снова, как бужто перевыбора небыло.414func (r *Room) ReassignWeapons(role RoleId, message easyjson.RawMessage) (err error) {415 reassignWeapons := types.ReassignWeapons{}416 err = reassignWeapons.UnmarshalJSON(message)417 if err != nil {418 err = errors.Wrap(err, "parsing error: ")419 return420 }421 weapon, err := NewWeapon(reassignWeapons.NewWeapon)422 if err != nil {423 err = errors.Wrap(err, "incorrect weapon: ")424 return425 }426 if weapon == "flag" {427 err = errors.New("'flag' cannot be assigned during re-election.")428 return429 }430 // загрузка произойдёт, если сервер ждёт её, и этот игрок ещё не загрузил ничего.431 if !r.WeaponReElection.WaitingForIt {432 err = errors.New("there is no requirement to re-select a weapon at the moment.")433 return434 }435 if role == 0 {436 reassignWeapons.Rotate()437 if !r.WeaponReElection.User0ReElect {438 if r.UserTurnNumber == 0 {439 r.Map[r.WeaponReElection.AttackingCharacter].Weapon = weapon440 } else {441 r.Map[r.WeaponReElection.AttackedCharacter].Weapon = weapon442 }443 r.WeaponReElection.User0ReElect = true444 } else {445 err = errors.New("You have already downloaded the re-selection.")446 return447 }448 } else {449 if !r.WeaponReElection.User1ReElect {450 if r.UserTurnNumber != 0 {451 r.Map[r.WeaponReElection.AttackingCharacter].Weapon = weapon452 } else {453 r.Map[r.WeaponReElection.AttackedCharacter].Weapon = weapon454 }455 r.WeaponReElection.User1ReElect = true456 } else {457 err = errors.New("You have already downloaded the re-selection.")458 return459 }460 }461 if r.WeaponReElection.User0ReElect && r.WeaponReElection.User1ReElect {462 // то мы как будто бы проводим ход снова, как будто бы небыло перевыбора.463 r.WeaponReElection.WaitingForIt = false464 _, err = r.AttemptGoToCellLogic(r.UserTurnNumber, r.WeaponReElection.AttackingCharacter, r.WeaponReElection.AttackedCharacter)465 if err != nil {466 // Тут точно не должно быть ошибки, которую можно обработать кодом.467 fmt.Print(r.Map)468 panic(err)469 }470 }471 return472}473// ответственность: сформировать изменение для клиента, не изменяет карту.474// считает, что карта уже изменена. Вращает для нулевого игрока.475func (r *Room) MoveCharacter(role RoleId, from int, to int) {476 moveCharacter := types.MoveCharacter{477 From: from,478 To: to,479 }480 if role == 0 {481 moveCharacter.Rotate()482 }483 response, _ := moveCharacter.MarshalJSON()484 response, _ = types.Event{485 Method: "move_character",486 Parameter: response,487 }.MarshalJSON()488 if role == 0 {489 r.Messaging.User0To <- response490 } else {491 r.Messaging.User1To <- response492 }493 return494}495// ответственность: сборка изменения для клиента, не изменяет карту.496// считает, что карта уже изменена, поэтому не берёт ничего оттуда, там nil в качестве проигравшего.497// Вращает для нулевого игрока.498func (r *Room) Attack(role RoleId, winner int, winnerWeapon Weapon, loser int, loserWeapon Weapon) {499 attack := types.Attack{500 Winner: types.AttackingСharacter{501 Coordinates: winner,502 Weapon: string(winnerWeapon),503 },504 Loser: types.AttackingСharacter{505 Coordinates: loser,506 Weapon: string(loserWeapon),507 },508 }509 if role == 0 {510 attack.Rotate()511 }512 response, _ := attack.MarshalJSON()513 response, _ = types.Event{514 Method: "attack",515 Parameter: response,516 }.MarshalJSON()517 if role == 0 {518 r.Messaging.User0To <- response519 } else {520 r.Messaging.User1To <- response521 }522 return523}524// ответственность: сборка изменения для клиента, не изменяет карту.525// считает, что карта уже изменена. вращает для нулевого526func (r *Room) AddWeapon(role RoleId, coordinates int, weapon Weapon) {527 addWeapon := types.AddWeapon{528 Coordinates: coordinates,529 Weapon: string(weapon),530 }531 if role == 0 {532 addWeapon.Rotate()533 }534 response, _ := addWeapon.MarshalJSON()535 response, _ = types.Event{536 Method: "add_weapon",537 Parameter: response,538 }.MarshalJSON()539 if role == 0 {540 r.Messaging.User0To <- response541 } else {542 r.Messaging.User1To <- response543 }544 return545}546// ответственность: отправка запроса на перевыбор клиенту, не изменяет карту и состояния.547func (r *Room) WeaponChangeRequest(role RoleId, characterOfPlayer int) {548 weaponChangeRequest := types.WeaponChangeRequest{549 CharacterPosition: characterOfPlayer,550 }551 if role == 0 {552 weaponChangeRequest.Rotate()553 }554 response, _ := weaponChangeRequest.MarshalJSON()555 response, _ = types.Event{556 Method: "weapon_change_request",557 Parameter: response,558 }.MarshalJSON()559 if role == 0 {560 r.Messaging.User0To <- response561 } else {562 r.Messaging.User1To <- response563 }564 return565}566// ответственность: сборка изменения для клиента, не изменяет карту и не прекращает игру.567// считает, что карта уже изменена.568func (r *Room) Gameover(role RoleId, winnerRole RoleId, from int, to int) {569 gameover := types.GameOver{570 Winner: role == winnerRole,571 From: from,572 To: to,573 }574 if role == 0 {575 gameover.Rotate()576 }577 response, _ := gameover.MarshalJSON()578 response, _ = types.Event{579 Method: "gameover",580 Parameter: response,581 }.MarshalJSON()582 if role == 0 {583 r.Messaging.User0To <- response584 } else {585 r.Messaging.User1To <- response586 }587 return588}589// проблемы, почему не используются библиотеки:590// Stateful сервер: необходимо помнить роль, в которой работает пользователь,591// комнату, в которой присутствует пользователь.592// решено делать всё на событиях - клиет пересылает действия пользвателя,593// сервер декларативно присылает изменения, в такой форме, что бы они прямо вызывали анимации.594// сервер получает из одного из двух каналов запись.595// добавляет номер игрока....

Full Screen

Full Screen

handlers.go

Source:handlers.go Github

copy

Full Screen

...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}...

Full Screen

Full Screen

encoding.go

Source:encoding.go Github

copy

Full Screen

...44 leg.ArrivalTime = x.EncArrivalTime.Time()45 leg.DepartureTime = x.EncDepartureTime.Time()46 return nil47}48// MarshalJSON implements json.Marshaler for Leg. This encodes Go types back to49// the API representation.50func (leg *Leg) MarshalJSON() ([]byte, error) {51 x := encodedLeg{}52 x.safeLeg = safeLeg(*leg)53 x.EncDuration = internal.NewDuration(leg.Duration)54 x.EncDurationInTraffic = internal.NewDuration(leg.DurationInTraffic)55 x.EncArrivalTime = internal.NewDateTime(leg.ArrivalTime)56 x.EncDepartureTime = internal.NewDateTime(leg.DepartureTime)57 return json.Marshal(x)58}59// safeStep is a raw version of Step that does not have custom encoding or60// decoding methods applied.61type safeStep Step62// encodedStep is the actual encoded version of Step as per the Maps APIs.63type encodedStep struct {64 safeStep65 EncDuration *internal.Duration `json:"duration"`66}67// UnmarshalJSON implements json.Unmarshaler for Step. This decodes the API68// representation into types useful for Go developers.69func (step *Step) UnmarshalJSON(data []byte) error {70 x := encodedStep{}71 err := json.Unmarshal(data, &x)72 if err != nil {73 return err74 }75 *step = Step(x.safeStep)76 step.Duration = x.EncDuration.Duration()77 return nil78}79// MarshalJSON implements json.Marshaler for Step. This encodes Go types back to80// the API representation.81func (step *Step) MarshalJSON() ([]byte, error) {82 x := encodedStep{}83 x.safeStep = safeStep(*step)84 x.EncDuration = internal.NewDuration(step.Duration)85 return json.Marshal(x)86}87// safeTransitDetails is a raw version of TransitDetails that does not have88// custom encoding or decoding methods applied.89type safeTransitDetails TransitDetails90// encodedTransitDetails is the actual encoded version of TransitDetails as per91// the Maps APIs92type encodedTransitDetails struct {93 safeTransitDetails94 EncArrivalTime *internal.DateTime `json:"arrival_time"`95 EncDepartureTime *internal.DateTime `json:"departure_time"`96}97// UnmarshalJSON implements json.Unmarshaler for TransitDetails. This decodes98// the API representation into types useful for Go developers.99func (transitDetails *TransitDetails) UnmarshalJSON(data []byte) error {100 x := encodedTransitDetails{}101 err := json.Unmarshal(data, &x)102 if err != nil {103 return err104 }105 *transitDetails = TransitDetails(x.safeTransitDetails)106 transitDetails.ArrivalTime = x.EncArrivalTime.Time()107 transitDetails.DepartureTime = x.EncDepartureTime.Time()108 return nil109}110// MarshalJSON implements json.Marshaler for TransitDetails. This encodes Go111// types back to the API representation.112func (transitDetails *TransitDetails) MarshalJSON() ([]byte, error) {113 x := encodedTransitDetails{}114 x.safeTransitDetails = safeTransitDetails(*transitDetails)115 x.EncArrivalTime = internal.NewDateTime(transitDetails.ArrivalTime)116 x.EncDepartureTime = internal.NewDateTime(transitDetails.DepartureTime)117 return json.Marshal(x)118}119// safeTransitLine is the raw version of TransitLine that does not have custom120// encoding or decoding methods applied.121type safeTransitLine TransitLine122// encodedTransitLine is the actual encoded version of TransitLine as per the123// Maps APIs124type encodedTransitLine struct {125 safeTransitLine126 EncURL string `json:"url"`127 EncIcon string `json:"icon"`128}129// UnmarshalJSON imlpements json.Unmarshaler for TransitLine. This decodes the130// API representation into types useful for Go developers.131func (transitLine *TransitLine) UnmarshalJSON(data []byte) error {132 x := encodedTransitLine{}133 err := json.Unmarshal(data, &x)134 if err != nil {135 return err136 }137 *transitLine = TransitLine(x.safeTransitLine)138 transitLine.URL, err = url.Parse(x.EncURL)139 if err != nil {140 return err141 }142 transitLine.Icon, err = url.Parse(x.EncIcon)143 if err != nil {144 return err145 }146 return nil147}148// MarshalJSON implements json.Marshaler for TransitLine. This encodes Go149// types back to the API representation.150func (transitLine *TransitLine) MarshalJSON() ([]byte, error) {151 x := encodedTransitLine{}152 x.safeTransitLine = safeTransitLine(*transitLine)153 x.EncURL = transitLine.URL.String()154 x.EncIcon = transitLine.Icon.String()155 return json.Marshal(x)156}157// safeTransitAgency is the raw version of TransitAgency that does not have158// custom encoding or decoding methods applied.159type safeTransitAgency TransitAgency160// encodedTransitAgency is the actual encoded version of TransitAgency as per the161// Maps APIs162type encodedTransitAgency struct {163 safeTransitAgency164 EncURL string `json:"url"`165}166// UnmarshalJSON imlpements json.Unmarshaler for TransitAgency. This decodes the167// API representation into types useful for Go developers.168func (transitAgency *TransitAgency) UnmarshalJSON(data []byte) error {169 x := encodedTransitAgency{}170 err := json.Unmarshal(data, &x)171 if err != nil {172 return err173 }174 *transitAgency = TransitAgency(x.safeTransitAgency)175 transitAgency.URL, err = url.Parse(x.EncURL)176 if err != nil {177 return err178 }179 return nil180}181// MarshalJSON implements json.Marshaler for TransitAgency. This encodes Go182// types back to the API representation.183func (transitAgency *TransitAgency) MarshalJSON() ([]byte, error) {184 x := encodedTransitAgency{}185 x.safeTransitAgency = safeTransitAgency(*transitAgency)186 x.EncURL = transitAgency.URL.String()187 return json.Marshal(x)188}189// safeTransitLineVehicle is the raw version of TransitLineVehicle that does not190// have custom encoding or decoding methods applied.191type safeTransitLineVehicle TransitLineVehicle192// encodedTransitLineVehicle is the actual encoded version of TransitLineVehicle193// as per the Maps APIs194type encodedTransitLineVehicle struct {195 safeTransitLineVehicle196 EncIcon string `json:"icon"`197}198// UnmarshalJSON imlpements json.Unmarshaler for TransitLineVehicle. This199// decodes the API representation into types useful for Go developers.200func (transitLineVehicle *TransitLineVehicle) UnmarshalJSON(data []byte) error {201 x := encodedTransitLineVehicle{}202 err := json.Unmarshal(data, &x)203 if err != nil {204 return err205 }206 *transitLineVehicle = TransitLineVehicle(x.safeTransitLineVehicle)207 transitLineVehicle.Icon, err = url.Parse(x.EncIcon)208 if err != nil {209 return err210 }211 return nil212}213// MarshalJSON implements json.Marshaler for TransitLineVehicle. This encodes214// Go types back to the API representation.215func (transitLineVehicle *TransitLineVehicle) MarshalJSON() ([]byte, error) {216 x := encodedTransitLineVehicle{}217 x.safeTransitLineVehicle = safeTransitLineVehicle(*transitLineVehicle)218 x.EncIcon = transitLineVehicle.Icon.String()219 return json.Marshal(x)220}221// safeDistanceMatrixElement is a raw version of DistanceMatrixElement that222// does not have custom encoding or decoding methods applied.223type safeDistanceMatrixElement DistanceMatrixElement224// encodedDistanceMatrixElement is the actual encoded version of225// DistanceMatrixElement as per the Maps APIs.226type encodedDistanceMatrixElement struct {227 safeDistanceMatrixElement228 EncDuration *internal.Duration `json:"duration"`229 EncDurationInTraffic *internal.Duration `json:"duration_in_traffic"`230}231// UnmarshalJSON implements json.Unmarshaler for DistanceMatrixElement. This232// decodes the API representation into types useful for Go developers.233func (dme *DistanceMatrixElement) UnmarshalJSON(data []byte) error {234 x := encodedDistanceMatrixElement{}235 err := json.Unmarshal(data, &x)236 if err != nil {237 return err238 }239 *dme = DistanceMatrixElement(x.safeDistanceMatrixElement)240 dme.Duration = x.EncDuration.Duration()241 dme.DurationInTraffic = x.EncDurationInTraffic.Duration()242 return nil243}244// MarshalJSON implements json.Marshaler for DistanceMatrixElement. This encodes245// Go types back to the API representation.246func (dme *DistanceMatrixElement) MarshalJSON() ([]byte, error) {247 x := encodedDistanceMatrixElement{}248 x.safeDistanceMatrixElement = safeDistanceMatrixElement(*dme)249 x.EncDuration = internal.NewDuration(dme.Duration)250 return json.Marshal(x)251}252// safeSnappedPoint is a raw version of SnappedPoint that does not have custom253// encoding or decoding methods applied.254type safeSnappedPoint SnappedPoint255// encodedSnappedPoint is the actual encoded version of SnappedPoint as per the256// Roads API.257type encodedSnappedPoint struct {258 safeSnappedPoint259 EncLocation internal.Location `json:"location"`260}261// UnmarshalJSON implements json.Unmarshaler for SnappedPoint. This decode the262// API representation into types useful for Go developers.263func (sp *SnappedPoint) UnmarshalJSON(data []byte) error {264 x := encodedSnappedPoint{}265 err := json.Unmarshal(data, &x)266 if err != nil {267 return err268 }269 *sp = SnappedPoint(x.safeSnappedPoint)270 sp.Location.Lat = x.EncLocation.Latitude271 sp.Location.Lng = x.EncLocation.Longitude272 return nil273}274// MarshalJSON implements json.Marshaler for SnappedPoint. This encodes Go275// types back to the API representation.276func (sp *SnappedPoint) MarshalJSON() ([]byte, error) {277 x := encodedSnappedPoint{}278 x.safeSnappedPoint = safeSnappedPoint(*sp)279 x.EncLocation.Latitude = sp.Location.Lat280 x.EncLocation.Longitude = sp.Location.Lng281 return json.Marshal(x)282}...

Full Screen

Full Screen

MarshalJSON

Using AI Code Generation

copy

Full Screen

1import (2type Person struct {3}4func (p Person) MarshalJSON() ([]byte, error) {5 return json.Marshal(struct {6 }{7 })8}9func main() {10 p := Person{11 }12 b, err := json.Marshal(p)13 if err != nil {14 fmt.Println(err)15 }16 fmt.Println(string(b))17}18{"Name":"John","Age":30}19import (20type Person struct {21}22func (p *Person) UnmarshalJSON(data []byte) error {23 var v struct {

Full Screen

Full Screen

MarshalJSON

Using AI Code Generation

copy

Full Screen

1import (2type User struct {3}4func (u User) MarshalJSON() ([]byte, error) {5 return json.Marshal(struct {6 }{7 })8}9func main() {10 u := User{Name: "John", Age: 30}11 b, err := json.Marshal(u)12 if err != nil {13 fmt.Println(err)14 }15 fmt.Println(string(b))16}17{"Name":"John","Age":30}18Example 2: UnmarshalJSON() method19import (20type User struct {21}22func (u *User) UnmarshalJSON(b []byte) error {23 aux := &struct {24 }{25 Alias: (*Alias)(u),26 }27 return json.Unmarshal(b, &aux)28}29func main() {30 u := User{}31 b := []byte(`{"Name":"John","Age":30}`)32 err := json.Unmarshal(b, &u)33 if err != nil {34 fmt.Println(err)35 }36 fmt.Println(u)37}38{John 30}39Example 3: MarshalText() method40import (41type User struct {42}43func (u User) MarshalText() ([]byte, error) {44 return []byte(fmt.Sprintf("%s is %d years old", u.Name, u.Age)), nil45}46func main() {47 u := User{Name: "John", Age: 30}48 b, err := json.Marshal(u)49 if err != nil {50 fmt.Println(err)51 }52 fmt.Println(string(b))53}54Example 4: UnmarshalText() method

Full Screen

Full Screen

MarshalJSON

Using AI Code Generation

copy

Full Screen

1func main() {2 s := Student{3 }4 b, err := json.Marshal(s)5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(string(b))9}10func main() {11 err := json.Unmarshal([]byte(`{"Name":"John","Age":23}`), &s)12 if err != nil {13 fmt.Println(err)14 }15 fmt.Println(s)16}17func main() {18 s := Student{19 }20 b, err := json.Marshal(s)21 if err != nil {22 fmt.Println(err)23 }24 fmt.Println(string(b))25}26func main() {27 err := json.Unmarshal([]byte(`{"Name":"John","Age":23}`), &s)28 if err != nil {29 fmt.Println(err)30 }31 fmt.Println(s)32}33func main() {34 s := Student{35 }36 b, err := json.Marshal(s)37 if err != nil {38 fmt.Println(err)39 }40 fmt.Println(string(b))41}42func main() {43 err := json.Unmarshal([]byte(`{"Name":"John","Age":23}`), &s)44 if err != nil {45 fmt.Println(err)46 }47 fmt.Println(s)48}49func main() {50 s := Student{51 }52 b, err := json.Marshal(s)53 if err != nil {54 fmt.Println(err)55 }56 fmt.Println(string(b))57}

Full Screen

Full Screen

MarshalJSON

Using AI Code Generation

copy

Full Screen

1data, err = json.Marshal(types)2if err != nil {3 fmt.Println("error:", err)4}5fmt.Println(string(data))6err = json.Unmarshal([]byte(data), &types)7if err != nil {8 fmt.Println("error:", err)9}10fmt.Println(types)11data, err = json.Marshal(type)12if err != nil {13 fmt.Println("error:", err)14}15fmt.Println(string(data))16err = json.Unmarshal([]byte(data), &type)17if err != nil {18 fmt.Println("error:", err)19}20fmt.Println(type)21data, err = json.Marshal(type)22if err != nil {23 fmt.Println("error:", err)24}25fmt.Println(string(data))26err = json.Unmarshal([]byte(data), &type)27if err != nil {28 fmt.Println("error:", err)29}30fmt.Println(type)31data, err = json.Marshal(type)32if err != nil {33 fmt.Println("error:", err)34}35fmt.Println(string(data))36err = json.Unmarshal([]byte(data), &type)37if err != nil {38 fmt.Println("error:", err)39}40fmt.Println(type)41data, err = json.Marshal(type)42if err != nil {43 fmt.Println("error:", err)44}45fmt.Println(string(data))

Full Screen

Full Screen

MarshalJSON

Using AI Code Generation

copy

Full Screen

1import (2type Person struct {3}4func main() {5 p := Person{"John", 21}6 fmt.Println(string(p.MarshalJSON()))7 fmt.Println(string(json.Marshal(p)))8}9{"Name":"John","Age":21}10{"Name":"John","Age":

Full Screen

Full Screen

MarshalJSON

Using AI Code Generation

copy

Full Screen

1func main() {2 p1 := Person{3 }4 bs, _ := json.Marshal(p1)5 fmt.Println(string(bs))6}7{"FirstName":"John","LastName":"Smith","Age":25}

Full Screen

Full Screen

MarshalJSON

Using AI Code Generation

copy

Full Screen

1func main() {2 types := &types{3 }4 jsonStr, _ := json.Marshal(types)5 fmt.Println(string(jsonStr))6}7{"name":"test","age":10}8func main() {9 types := &types{10 }11 jsonStr, _ := json.MarshalIndent(types, "", " ")12 fmt.Println(string(jsonStr))13}14{15}16func main() {17 types := &types{18 }19 jsonStr, _ := json.Marshal(types)20 fmt.Println(string(jsonStr))21}22{"name":"test","age":10}23func main() {24 types := &types{25 }

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful