Best Gauge code snippet using validation.DataTable
projects.go
Source:projects.go
1package handlers2import (3 "context"4 "fmt"5 "net/http"6 "strings"7 "geeks-accelerator/oss/saas-starter-kit/internal/platform/auth"8 "geeks-accelerator/oss/saas-starter-kit/internal/platform/datatable"9 "geeks-accelerator/oss/saas-starter-kit/internal/platform/web"10 "geeks-accelerator/oss/saas-starter-kit/internal/platform/web/webcontext"11 "geeks-accelerator/oss/saas-starter-kit/internal/platform/web/weberror"12 "geeks-accelerator/oss/saas-starter-kit/internal/project"13 "github.com/gorilla/schema"14 "github.com/pkg/errors"15 "gopkg.in/DataDog/dd-trace-go.v1/contrib/go-redis/redis"16)17// Projects represents the Projects API method handler set.18type Projects struct {19 ProjectRepo *project.Repository20 Redis *redis.Client21 Renderer web.Renderer22}23func urlProjectsIndex() string {24 return fmt.Sprintf("/projects")25}26func urlProjectsCreate() string {27 return fmt.Sprintf("/projects/create")28}29func urlProjectsView(projectID string) string {30 return fmt.Sprintf("/projects/%s", projectID)31}32func urlProjectsUpdate(projectID string) string {33 return fmt.Sprintf("/projects/%s/update", projectID)34}35// Index handles listing all the projects for the current account.36func (h *Projects) Index(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {37 claims, err := auth.ClaimsFromContext(ctx)38 if err != nil {39 return err40 }41 statusOpts := web.NewEnumResponse(ctx, nil, project.ProjectStatus_ValuesInterface()...)42 statusFilterItems := []datatable.FilterOptionItem{}43 for _, opt := range statusOpts.Options {44 statusFilterItems = append(statusFilterItems, datatable.FilterOptionItem{45 Display: opt.Title,46 Value: opt.Value,47 })48 }49 fields := []datatable.DisplayField{50 datatable.DisplayField{Field: "id", Title: "ID", Visible: false, Searchable: true, Orderable: true, Filterable: false},51 datatable.DisplayField{Field: "name", Title: "Project", Visible: true, Searchable: true, Orderable: true, Filterable: true, FilterPlaceholder: "filter Name"},52 datatable.DisplayField{Field: "status", Title: "Status", Visible: true, Searchable: true, Orderable: true, Filterable: true, FilterPlaceholder: "All Statuses", FilterItems: statusFilterItems},53 datatable.DisplayField{Field: "updated_at", Title: "Last Updated", Visible: true, Searchable: true, Orderable: true, Filterable: false},54 datatable.DisplayField{Field: "created_at", Title: "Created", Visible: true, Searchable: true, Orderable: true, Filterable: false},55 }56 mapFunc := func(q *project.Project, cols []datatable.DisplayField) (resp []datatable.ColumnValue, err error) {57 for i := 0; i < len(cols); i++ {58 col := cols[i]59 var v datatable.ColumnValue60 switch col.Field {61 case "id":62 v.Value = fmt.Sprintf("%s", q.ID)63 case "name":64 v.Value = q.Name65 v.Formatted = fmt.Sprintf("<a href='%s'>%s</a>", urlProjectsView(q.ID), v.Value)66 case "status":67 v.Value = q.Status.String()68 var subStatusClass string69 var subStatusIcon string70 switch q.Status {71 case project.ProjectStatus_Active:72 subStatusClass = "text-green"73 subStatusIcon = "far fa-dot-circle"74 case project.ProjectStatus_Disabled:75 subStatusClass = "text-orange"76 subStatusIcon = "far fa-circle"77 }78 v.Formatted = fmt.Sprintf("<span class='cell-font-status %s'><i class='%s mr-1'></i>%s</span>", subStatusClass, subStatusIcon, web.EnumValueTitle(v.Value))79 case "created_at":80 dt := web.NewTimeResponse(ctx, q.CreatedAt)81 v.Value = dt.Local82 v.Formatted = fmt.Sprintf("<span class='cell-font-date'>%s</span>", v.Value)83 case "updated_at":84 dt := web.NewTimeResponse(ctx, q.UpdatedAt)85 v.Value = dt.Local86 v.Formatted = fmt.Sprintf("<span class='cell-font-date'>%s</span>", v.Value)87 default:88 return resp, errors.Errorf("Failed to map value for %s.", col.Field)89 }90 resp = append(resp, v)91 }92 return resp, nil93 }94 loadFunc := func(ctx context.Context, sorting string, fields []datatable.DisplayField) (resp [][]datatable.ColumnValue, err error) {95 res, err := h.ProjectRepo.Find(ctx, claims, project.ProjectFindRequest{96 Where: "account_id = ?",97 Args: []interface{}{claims.Audience},98 Order: strings.Split(sorting, ","),99 })100 if err != nil {101 return resp, err102 }103 for _, a := range res {104 l, err := mapFunc(a, fields)105 if err != nil {106 return resp, errors.Wrapf(err, "Failed to map project for display.")107 }108 resp = append(resp, l)109 }110 return resp, nil111 }112 dt, err := datatable.New(ctx, w, r, h.Redis, fields, loadFunc)113 if err != nil {114 return err115 }116 if dt.HasCache() {117 return nil118 }119 if ok, err := dt.Render(); ok {120 if err != nil {121 return err122 }123 return nil124 }125 data := map[string]interface{}{126 "datatable": dt.Response(),127 "urlProjectsCreate": urlProjectsCreate(),128 }129 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "projects-index.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)130}131// Create handles creating a new project for the account.132func (h *Projects) Create(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {133 ctxValues, err := webcontext.ContextValues(ctx)134 if err != nil {135 return err136 }137 claims, err := auth.ClaimsFromContext(ctx)138 if err != nil {139 return err140 }141 //142 req := new(project.ProjectCreateRequest)143 data := make(map[string]interface{})144 f := func() (bool, error) {145 if r.Method == http.MethodPost {146 err := r.ParseForm()147 if err != nil {148 return false, err149 }150 decoder := schema.NewDecoder()151 decoder.IgnoreUnknownKeys(true)152 if err := decoder.Decode(req, r.PostForm); err != nil {153 return false, err154 }155 req.AccountID = claims.Audience156 usr, err := h.ProjectRepo.Create(ctx, claims, *req, ctxValues.Now)157 if err != nil {158 switch errors.Cause(err) {159 default:160 if verr, ok := weberror.NewValidationError(ctx, err); ok {161 data["validationErrors"] = verr.(*weberror.Error)162 return false, nil163 } else {164 return false, err165 }166 }167 }168 // Display a success message to the project.169 webcontext.SessionFlashSuccess(ctx,170 "Project Created",171 "Project successfully created.")172 return true, web.Redirect(ctx, w, r, urlProjectsView(usr.ID), http.StatusFound)173 }174 return false, nil175 }176 end, err := f()177 if err != nil {178 return web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)179 } else if end {180 return nil181 }182 data["form"] = req183 if verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(project.ProjectCreateRequest{})); ok {184 data["validationDefaults"] = verr.(*weberror.Error)185 }186 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "projects-create.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)187}188// View handles displaying a project.189func (h *Projects) View(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {190 projectID := params["project_id"]191 ctxValues, err := webcontext.ContextValues(ctx)192 if err != nil {193 return err194 }195 claims, err := auth.ClaimsFromContext(ctx)196 if err != nil {197 return err198 }199 data := make(map[string]interface{})200 f := func() (bool, error) {201 if r.Method == http.MethodPost {202 err := r.ParseForm()203 if err != nil {204 return false, err205 }206 switch r.PostForm.Get("action") {207 case "archive":208 err = h.ProjectRepo.Archive(ctx, claims, project.ProjectArchiveRequest{209 ID: projectID,210 }, ctxValues.Now)211 if err != nil {212 return false, err213 }214 webcontext.SessionFlashSuccess(ctx,215 "Project Archive",216 "Project successfully archive.")217 return true, web.Redirect(ctx, w, r, urlProjectsIndex(), http.StatusFound)218 }219 }220 return false, nil221 }222 end, err := f()223 if err != nil {224 return web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)225 } else if end {226 return nil227 }228 prj, err := h.ProjectRepo.ReadByID(ctx, claims, projectID)229 if err != nil {230 return err231 }232 data["project"] = prj.Response(ctx)233 data["urlProjectsView"] = urlProjectsView(projectID)234 data["urlProjectsUpdate"] = urlProjectsUpdate(projectID)235 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "projects-view.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)236}237// Update handles updating a project for the account.238func (h *Projects) Update(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {239 projectID := params["project_id"]240 ctxValues, err := webcontext.ContextValues(ctx)241 if err != nil {242 return err243 }244 claims, err := auth.ClaimsFromContext(ctx)245 if err != nil {246 return err247 }248 //249 req := new(project.ProjectUpdateRequest)250 data := make(map[string]interface{})251 f := func() (bool, error) {252 if r.Method == http.MethodPost {253 err := r.ParseForm()254 if err != nil {255 return false, err256 }257 decoder := schema.NewDecoder()258 decoder.IgnoreUnknownKeys(true)259 if err := decoder.Decode(req, r.PostForm); err != nil {260 return false, err261 }262 req.ID = projectID263 err = h.ProjectRepo.Update(ctx, claims, *req, ctxValues.Now)264 if err != nil {265 switch errors.Cause(err) {266 default:267 if verr, ok := weberror.NewValidationError(ctx, err); ok {268 data["validationErrors"] = verr.(*weberror.Error)269 return false, nil270 } else {271 return false, err272 }273 }274 }275 // Display a success message to the project.276 webcontext.SessionFlashSuccess(ctx,277 "Project Updated",278 "Project successfully updated.")279 return true, web.Redirect(ctx, w, r, urlProjectsView(req.ID), http.StatusFound)280 }281 return false, nil282 }283 end, err := f()284 if err != nil {285 return web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)286 } else if end {287 return nil288 }289 prj, err := h.ProjectRepo.ReadByID(ctx, claims, projectID)290 if err != nil {291 return err292 }293 data["project"] = prj.Response(ctx)294 data["urlProjectsView"] = urlProjectsView(projectID)295 if req.ID == "" {296 req.Name = &prj.Name297 req.Status = &prj.Status298 }299 data["form"] = req300 if verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(project.ProjectUpdateRequest{})); ok {301 data["validationDefaults"] = verr.(*weberror.Error)302 }303 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "projects-update.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)304}...
subjects.go
Source:subjects.go
1package handlers2import (3 "context"4 "fmt"5 "net/http"6 "strings"7 "remoteschool/smarthead/internal/subject"8 "remoteschool/smarthead/internal/platform/auth"9 "remoteschool/smarthead/internal/platform/datatable"10 "remoteschool/smarthead/internal/platform/web"11 "remoteschool/smarthead/internal/platform/web/webcontext"12 "remoteschool/smarthead/internal/platform/web/weberror"13 "github.com/gorilla/schema"14 "github.com/pkg/errors"15 "gopkg.in/DataDog/dd-trace-go.v1/contrib/go-redis/redis"16)17// Subjects represents the Subjects API method handler set.18type Subjects struct {19 Repo *subject.Repository20 Redis *redis.Client21 Renderer web.Renderer22}23 24func urlSubjectsIndex() string {25 return fmt.Sprintf("/admin/subjects")26}27func urlSubjectsCreate() string {28 return fmt.Sprintf("/admin/subjects/create")29}30func urlSubjectsView(subjectID string) string {31 return fmt.Sprintf("/admin/subjects/%s", subjectID) 32}33 34func urlSubjectsUpdate(subjectID string) string {35 return fmt.Sprintf("/admin/subjects/%s/update", subjectID)36}37// Index handles listing all the subjects for the current account.38func (h *Subjects) Index(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {39 claims, err := auth.ClaimsFromContext(ctx)40 if err != nil {41 return err42 }43 fields := []datatable.DisplayField{44 {Field: "id", Title: "ID", Visible: false, Searchable: true, Orderable: true, Filterable: false},45 {Field: "name", Title: "Subject", Visible: true, Searchable: true, Orderable: true, Filterable: true, FilterPlaceholder: "filter Name"},46 {Field: "school_order", Title: "School(s)", Visible: true, Searchable: true, Orderable: true, Filterable: true, FilterPlaceholder: "filter Name"},47 }48 mapFunc := func(q *subject.Response, cols []datatable.DisplayField) (resp []datatable.ColumnValue, err error) {49 for i := 0; i < len(cols); i++ {50 col := cols[i]51 var v datatable.ColumnValue52 switch col.Field {53 case "id":54 v.Value = fmt.Sprintf("%s", q.ID)55 case "name":56 v.Value = q.Name57 v.Formatted = fmt.Sprintf("<a href='%s'>%s</a>", urlSubjectsView(q.ID), v.Value)58 case "school_order":59 v.Value = fmt.Sprintf("%v", q.SchoolOrders)60 v.Formatted = v.Value61 default:62 return resp, errors.Errorf("Failed to map value for %s.", col.Field)63 }64 resp = append(resp, v)65 }66 return resp, nil67 }68 loadFunc := func(ctx context.Context, sorting string, fields []datatable.DisplayField) (resp [][]datatable.ColumnValue, err error) {69 res, err := h.Repo.Find(ctx, claims, subject.FindRequest{70 Order: strings.Split(sorting, ","),71 })72 if err != nil {73 return resp, err74 }75 for _, a := range res {76 l, err := mapFunc(a.Response(ctx), fields)77 if err != nil {78 return resp, errors.Wrapf(err, "Failed to map checklist for display.")79 }80 resp = append(resp, l)81 }82 return resp, nil83 }84 dt, err := datatable.New(ctx, w, r, h.Redis, fields, loadFunc)85 if err != nil {86 return err87 }88 if dt.HasCache() {89 return nil90 }91 if ok, err := dt.Render(); ok {92 if err != nil {93 return err94 }95 return nil96 }97 data := map[string]interface{}{98 "datatable": dt.Response(),99 "urlSubjectsCreate": urlSubjectsCreate(),100 "urlSubjectsIndex": urlSubjectsIndex(),101 }102 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "admin-subjects-index.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)103}104// Create handles creating a new subject.105func (h *Subjects) Create(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {106 claims, err := auth.ClaimsFromContext(ctx)107 if err != nil {108 return err109 }110 //111 req := new(subject.CreateRequest)112 data := make(map[string]interface{})113 f := func() (bool, error) {114 if r.Method == http.MethodPost {115 err := r.ParseForm()116 if err != nil {117 return false, err118 }119 decoder := schema.NewDecoder()120 decoder.IgnoreUnknownKeys(true)121 if err := decoder.Decode(req, r.PostForm); err != nil {122 return false, err123 }124 sub, err := h.Repo.Create(ctx, claims, *req)125 if err != nil {126 switch errors.Cause(err) {127 default:128 if verr, ok := weberror.NewValidationError(ctx, err); ok {129 data["validationErrors"] = verr.(*weberror.Error)130 return false, nil131 } else {132 return false, err133 }134 }135 }136 // Display a success message to the checklist.137 webcontext.SessionFlashSuccess(ctx,138 "Subject Created",139 "Subject successfully created.")140 return true, web.Redirect(ctx, w, r, urlSubjectsView(sub.ID), http.StatusFound)141 }142 return false, nil143 }144 end, err := f()145 if err != nil {146 return web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)147 } else if end {148 return nil149 }150 data["form"] = req151 data["urlSubjectsIndex"] = urlSubjectsIndex() 152 if verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(subject.CreateRequest{})); ok {153 data["validationDefaults"] = verr.(*weberror.Error)154 }155 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "admin-subjects-create.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)156}157// View handles displaying a subjects.158func (h *Subjects) View(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {159 subjectID := params["subject_id"]160 claims, err := auth.ClaimsFromContext(ctx)161 if err != nil {162 return err163 }164 data := make(map[string]interface{})165 f := func() (bool, error) {166 if r.Method == http.MethodPost {167 err := r.ParseForm()168 if err != nil {169 return false, err170 }171 switch r.PostForm.Get("action") {172 case "archive":173 err = h.Repo.Delete(ctx, claims, subject.DeleteRequest{174 ID: subjectID,175 })176 if err != nil {177 return false, err178 }179 webcontext.SessionFlashSuccess(ctx,180 "Subject Archive",181 "Subject successfully archive.")182 return true, web.Redirect(ctx, w, r, urlSubjectsIndex(), http.StatusFound)183 }184 }185 return false, nil186 }187 end, err := f()188 if err != nil {189 return web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)190 } else if end {191 return nil192 }193 sub, err := h.Repo.ReadByID(ctx, claims, subjectID)194 if err != nil {195 return err196 }197 data["subject"] = sub.Response(ctx)198 data["urlSubjectsIndex"] = urlSubjectsIndex()199 data["urlSubjectsView"] = urlSubjectsView(subjectID)200 data["urlSubjectsUpdate"] = urlSubjectsUpdate(subjectID)201 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "admin-subjects-view.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)202}203// Update handles updating a subject.204func (h *Subjects) Update(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {205 subjectID := params["subject_id"]206 claims, err := auth.ClaimsFromContext(ctx)207 if err != nil {208 return err209 } 210 req := new(subject.UpdateRequest)211 data := make(map[string]interface{})212 f := func() (bool, error) {213 if r.Method == http.MethodPost {214 err := r.ParseForm()215 if err != nil {216 return false, err217 }218 decoder := schema.NewDecoder()219 decoder.IgnoreUnknownKeys(true)220 if err := decoder.Decode(req, r.PostForm); err != nil {221 return false, err222 }223 req.ID = subjectID224 err = h.Repo.Update(ctx, claims, *req)225 if err != nil {226 switch errors.Cause(err) {227 default:228 if verr, ok := weberror.NewValidationError(ctx, err); ok {229 data["validationErrors"] = verr.(*weberror.Error)230 return false, nil231 } else {232 return false, err233 }234 }235 }236 // Display a success message to the checklist.237 webcontext.SessionFlashSuccess(ctx,238 "Subject Updated",239 "Subject successfully updated.")240 return true, web.Redirect(ctx, w, r, urlSubjectsView(req.ID), http.StatusFound)241 }242 return false, nil243 }244 end, err := f()245 if err != nil {246 return web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)247 } else if end {248 return nil249 }250 sub, err := h.Repo.ReadByID(ctx, claims, subjectID)251 if err != nil {252 return err253 }254 data["subject"] = sub.Response(ctx)255 data["urlSubjectsIndex"] = urlSubjectsIndex()256 data["urlSubjectsView"] = urlSubjectsView(subjectID)257 if req.ID == "" {258 req.Name = &sub.Name259 var schoolOrders []string260 for _, s := range sub.SchoolOrders {261 schoolOrders = append(schoolOrders, fmt.Sprintf("%d", s))262 }263 s := strings.Join(schoolOrders, ", ")264 req.SchoolOrder = &s265 }266 data["form"] = req267 if verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(subject.UpdateRequest{})); ok {268 data["validationDefaults"] = verr.(*weberror.Error)269 }270 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "admin-subjects-update.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)271}...
classes.go
Source:classes.go
1package handlers2import (3 "context"4 "fmt"5 "net/http"6 "strings"7 "remoteschool/smarthead/internal/class"8 "remoteschool/smarthead/internal/platform/auth"9 "remoteschool/smarthead/internal/platform/datatable"10 "remoteschool/smarthead/internal/platform/web"11 "remoteschool/smarthead/internal/platform/web/webcontext"12 "remoteschool/smarthead/internal/platform/web/weberror"13 "github.com/davecgh/go-spew/spew"14 "github.com/gorilla/schema"15 "github.com/pkg/errors"16 "gopkg.in/DataDog/dd-trace-go.v1/contrib/go-redis/redis"17)18// Classes represents the Classes API method handler set.19type Classes struct {20 Repo *class.Repository21 Redis *redis.Client22 Renderer web.Renderer23}24func urlClassesIndex() string {25 return fmt.Sprintf("/admin/classes")26}27func urlClassesCreate() string {28 return fmt.Sprintf("/admin/classes/create")29}30func urlClassesView(classID string) string {31 return fmt.Sprintf("/admin/classes/%s", classID)32}33func urlClassesUpdate(classID string) string {34 return fmt.Sprintf("/admin/classes/%s/update", classID)35}36// Index handles listing all the classes for the current account.37func (h *Classes) Index(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {38 fields := []datatable.DisplayField{39 {Field: "id", Title: "ID", Visible: false, Searchable: true, Orderable: true, Filterable: false},40 {Field: "name", Title: "Class", Visible: true, Searchable: true, Orderable: true, Filterable: true, FilterPlaceholder: "filter Name"},41 }42 mapFunc := func(q *class.Class, cols []datatable.DisplayField) (resp []datatable.ColumnValue, err error) {43 for i := 0; i < len(cols); i++ {44 col := cols[i]45 var v datatable.ColumnValue46 switch col.Field {47 case "id":48 v.Value = fmt.Sprintf("%s", q.ID)49 case "name":50 v.Value = q.Name51 v.Formatted = fmt.Sprintf("<a href='%s'>%s</a>", urlClassesView(q.ID), v.Value)52 default:53 return resp, errors.Errorf("Failed to map value for %s.", col.Field)54 }55 resp = append(resp, v)56 }57 return resp, nil58 }59 loadFunc := func(ctx context.Context, sorting string, fields []datatable.DisplayField) (resp [][]datatable.ColumnValue, err error) {60 res, err := h.Repo.Find(ctx, class.FindRequest{61 Order: strings.Split(sorting, ","),62 })63 if err != nil {64 return resp, err65 }66 for _, a := range res {67 l, err := mapFunc(a, fields)68 if err != nil {69 return resp, errors.Wrapf(err, "Failed to map class for display.")70 }71 resp = append(resp, l)72 }73 return resp, nil74 }75 dt, err := datatable.New(ctx, w, r, h.Redis, fields, loadFunc)76 if err != nil {77 return err78 }79 if dt.HasCache() {80 return nil81 }82 if ok, err := dt.Render(); ok {83 if err != nil {84 return err85 }86 return nil87 }88 data := map[string]interface{}{89 "datatable": dt.Response(),90 "urlClassesCreate": urlClassesCreate(),91 "urlClassesIndex": urlClassesIndex(),92 }93 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "admin-classes-index.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)94}95// Create handles creating a new class.96func (h *Classes) Create(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {97 claims, err := auth.ClaimsFromContext(ctx)98 if err != nil {99 return err 100 }101 //102 req := new(class.CreateRequest)103 data := make(map[string]interface{})104 f := func() (bool, error) {105 if r.Method == http.MethodPost {106 err := r.ParseForm()107 if err != nil {108 return false, err109 }110 decoder := schema.NewDecoder()111 decoder.IgnoreUnknownKeys(true)112 if err := decoder.Decode(req, r.PostForm); err != nil {113 return false, err114 }115 sub, err := h.Repo.Create(ctx, claims, *req)116 if err != nil {117 switch errors.Cause(err) {118 default:119 if verr, ok := weberror.NewValidationError(ctx, err); ok {120 data["validationErrors"] = verr.(*weberror.Error)121 return false, nil122 } else {123 return false, err124 }125 }126 }127 // Display a success message to the checklist.128 webcontext.SessionFlashSuccess(ctx,129 "Class Created",130 "Class successfully created.")131 return true, web.Redirect(ctx, w, r, urlClassesView(sub.ID), http.StatusFound)132 }133 return false, nil134 }135 end, err := f()136 if err != nil {137 return web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)138 } else if end {139 return nil140 }141 data["form"] = req142 data["urlClassesIndex"] = urlClassesIndex()143 spew.Dump(req)144 if verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(class.CreateRequest{})); ok {145 data["validationDefaults"] = verr.(*weberror.Error)146 }147 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "admin-classes-create.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)148}149// View handles displaying a classes.150func (h *Classes) View(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {151 classID := params["class_id"]152 claims, err := auth.ClaimsFromContext(ctx)153 if err != nil {154 return err155 }156 data := make(map[string]interface{})157 f := func() (bool, error) {158 if r.Method == http.MethodPost {159 err := r.ParseForm()160 if err != nil {161 return false, err162 }163 switch r.PostForm.Get("action") {164 case "archive":165 err = h.Repo.Delete(ctx, claims, class.DeleteRequest{166 ID: classID,167 })168 if err != nil {169 return false, err170 }171 webcontext.SessionFlashSuccess(ctx,172 "Class Archive",173 "Class successfully archive.")174 return true, web.Redirect(ctx, w, r, urlClassesIndex(), http.StatusFound)175 }176 }177 return false, nil178 }179 end, err := f()180 if err != nil {181 return web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)182 } else if end {183 return nil184 }185 sub, err := h.Repo.ReadByID(ctx, claims, classID)186 if err != nil {187 return err188 }189 data["class"] = sub.Response(ctx)190 data["urlClassesIndex"] = urlClassesIndex()191 data["urlClassesView"] = urlClassesView(classID)192 data["urlClassesUpdate"] = urlClassesUpdate(classID)193 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "admin-classes-view.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)194}195// Update handles updating a class.196func (h *Classes) Update(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {197 classID := params["class_id"]198 claims, err := auth.ClaimsFromContext(ctx)199 if err != nil {200 return err201 }202 //203 req := new(class.UpdateRequest)204 data := make(map[string]interface{})205 f := func() (bool, error) {206 if r.Method == http.MethodPost {207 err := r.ParseForm()208 if err != nil {209 return false, err210 }211 decoder := schema.NewDecoder()212 decoder.IgnoreUnknownKeys(true)213 if err := decoder.Decode(req, r.PostForm); err != nil {214 return false, err215 }216 req.ID = classID217 err = h.Repo.Update(ctx, claims, *req)218 if err != nil {219 switch errors.Cause(err) {220 default:221 if verr, ok := weberror.NewValidationError(ctx, err); ok {222 data["validationErrors"] = verr.(*weberror.Error)223 return false, nil224 } else {225 return false, err226 }227 }228 }229 // Display a success message to the class.230 webcontext.SessionFlashSuccess(ctx,231 "Class Updated",232 "Class successfully updated.")233 return true, web.Redirect(ctx, w, r, urlClassesView(req.ID), http.StatusFound)234 }235 return false, nil236 }237 end, err := f()238 if err != nil {239 return web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)240 } else if end {241 return nil242 }243 sub, err := h.Repo.ReadByID(ctx, claims, classID)244 if err != nil {245 return err246 }247 data["class"] = sub.Response(ctx)248 data["urlClassesIndex"] = urlClassesIndex()249 data["urlClassesView"] = urlClassesView(classID)250 if req.ID == "" {251 req.Name = &sub.Name252 req.SchoolOrder = &sub.SchoolOrder253 }254 data["form"] = req255 if verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(class.UpdateRequest{})); ok {256 data["validationDefaults"] = verr.(*weberror.Error)257 }258 return h.Renderer.Render(ctx, w, r, TmplLayoutBase, "admin-classes-update.gohtml", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)259}...
DataTable
Using AI Code Generation
1import (2func main() {3 xlFile, err := xlsx.OpenFile("C:/Users/HP/Desktop/Book1.xlsx")4 if err != nil {5 fmt.Println("Failed to open the excel file")6 }7 fmt.Println(cell.Value)8 fmt.Println(sheet.MaxRow)9 fmt.Println(sheet.MaxCol)10 fmt.Println(sheet.Cell(0, 0).Value)11 fmt.Println(sheet.Cell(1, 1).Value)12 fmt.Println(sheet.Cell(2, 2).Value)13 fmt.Println(sheet.Cell(3, 3).Value)14 fmt.Println(sheet.Cell(4, 4).Value)15 fmt.Println(sheet.Cell(5, 5).Value)16 fmt.Println(sheet.Cell(6, 6).Value)17 fmt.Println(sheet.Cell(7, 7).Value)18 fmt.Println(sheet.Cell(8, 8).Value)19 fmt.Println(sheet.Cell(9, 9).Value)20 fmt.Println(sheet.Cell(10, 10).Value)21 fmt.Println(sheet.Cell(11, 11).Value)22 fmt.Println(sheet.Cell(12, 12).Value)23 fmt.Println(sheet.Cell(13, 13).Value)24 fmt.Println(sheet.Cell(14,
DataTable
Using AI Code Generation
1import (2func main() {3 file := xlsx.NewFile()4 sheet, err := file.AddSheet("Sheet1")5 if err != nil {6 fmt.Printf(err.Error())7 }8 row := sheet.AddRow()9 cell := row.AddCell()10 style := xlsx.NewStyle()11 style.Font = *xlsx.NewFont(10, "Verdana")12 alignment := *xlsx.NewAlignment()13 border := *xlsx.NewBorder("thin", "thin", "thin", "thin")14 fill := *xlsx.NewFill("solid", "00FF0000", "FF000000")15 protection := *xlsx.NewProtection()16 cell.SetStyle(style)17 sheet.Col(0).Width = 2018 sheet.Row(0).SetHeightCM(1)19 sheet.Row(0).Hidden = true20 sheet.Row(0).OutlineLevel = 121 sheet.Row(0).Collapsed = true22 sheet.Col(0).Hidden = true23 sheet.Col(0).OutlineLevel = 124 sheet.Col(0).Collapsed = true25 sheet.Col(
DataTable
Using AI Code Generation
1import (2func main() {3 validation := Validation{}4 dt := DataTable{}5 dt = validation.DataTable("test.xlsx", "Sheet1")6 row := dt.Rows()7 column := dt.Columns()8 for i := 0; i < row; i++ {9 for j := 0; j < column; j++ {10 data := dt.Data(i, j)11 fmt.Println(data)12 }13 }14}15import (16func main() {17 validation := Validation{}18 dt := DataTable{}19 dt = validation.DataTable("test.xlsx", "Sheet1")20 row := dt.Rows()21 column := dt.Columns()22 for i := 0; i < row; i++ {23 for j := 0; j < column; j++ {24 data := dt.Data(i, j)25 fmt.Println(data)26 }27 }28}29import (30func main() {31 validation := Validation{}32 dt := DataTable{}33 dt = validation.DataTable("test.xlsx", "Sheet1")34 row := dt.Rows()35 column := dt.Columns()36 for i := 0; i < row; i++ {
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!!