Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add code from previous repository #1

Merged
merged 2 commits into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Test build

on:
pull_request:
branches:
- main

jobs:
main:
name: Build and run
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v3

- name: Run tests
run: |
go test

- name: Check if binary builds
run: |
go build .

2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
BSD 2-Clause License

Copyright (c) 2024, Go Phings
Copyright (c) 2024, Mikolaj Gasior <m@gasior.dev>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Expand Down
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
# crud-ui
Run administrative panel for struct instances in the database

[![Go Reference](https://pkg.go.dev/badge/github.com/go-phings/crud-ui.svg)](https://pkg.go.dev/github.com/go-phings/crud-ui) [![Go Report Card](https://goreportcard.com/badge/github.com/go-phings/crud-ui)](https://goreportcard.com/report/github.com/go-phings/crud-ui)

Package CRUD UI allows you to run a simple administration panel for struct instances stored in the database. The idea is that you define structs, attach ORM and run a simple function.

## Example usage

Real life example is yet to come but please navigate to `main_test.go` to see a simple usage.
27 changes: 27 additions & 0 deletions access.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package crudui

import (
"fmt"
"net/http"
)

const OpsCreate = 8
const OpsRead = 16
const OpsUpdate = 32
const OpsDelete = 64
const OpsList = 128

func (c *Controller) isStructOperationAllowed(r *http.Request, structName string, op int) bool {
allowedTypes := r.Context().Value(ContextValue(fmt.Sprintf("AllowedTypes_%d", op)))
if allowedTypes != nil {
v, ok := allowedTypes.(map[string]bool)[structName]
if !ok || !v {
v2, ok2 := allowedTypes.(map[string]bool)["all"]
if !ok2 || !v2 {
return false
}
}
}

return true
}
3 changes: 3 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Package ui creates a simple UI that allows managing data defined with struct and backed by PostgreSQL.

package crudui
30 changes: 30 additions & 0 deletions err.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package crudui

// ErrController wraps original error that occurred in Err with name of the operation/step that failed, which is
// in Op field
type ErrController struct {
Op string
Err error
}

func (e ErrController) Error() string {
return e.Err.Error()
}

func (e ErrController) Unwrap() error {
return e.Err
}

// ErrValidation wraps error occurring during object validation
type ErrValidation struct {
Fields map[string]int
Err error
}

func (e ErrValidation) Error() string {
return e.Err.Error()
}

func (e ErrValidation) Unwrap() error {
return e.Err
}
183 changes: 183 additions & 0 deletions fields_html.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
package crudui

import (
"fmt"
"html"
"reflect"
"regexp"
"strconv"
"strings"

validator "github.com/go-phings/struct-validator"
)

func (c *Controller) getStructItemFieldsHTML(u interface{}, values map[string]string) string {
fieldHTMLs := validator.GenerateHTML(u, &validator.HTMLOptions{
OverwriteTagName: c.tagName,
ExcludeFields: map[string]bool{
"ID": true,
},
OverwriteValues: values,
FieldValues: true,
})

htm := ""

reName := regexp.MustCompile(`name="[A-Za-z0-9\-_]+"`)

v := reflect.ValueOf(u)
elem := v.Elem()
i := reflect.Indirect(v)
s := i.Type()
structName := s.Name()

for j := 0; j < s.NumField(); j++ {
field := s.Field(j)

if field.Name == "ID" {
continue
}

gotDoubleEntry := c.isFieldHasTag(field, "dblentry")

var value string
fieldType := field.Type.Kind()
if fieldType == reflect.String {
value = elem.Field(j).String()
}
if fieldType == reflect.Bool {
value = fmt.Sprintf("%v", elem.Field(j).Bool())
}
if c.isFieldInt(field) {
value = fmt.Sprintf("%d", elem.Field(j).Int())
}

overwriteValue, ok := values[field.Name]
if ok {
value = overwriteValue
}

fieldHTML := c.getStructItemFieldHTML(field, structName, value, true)

if fieldHTML == "" {
fieldHTML = fieldHTMLs[field.Name]
}

htm += fmt.Sprintf("<p><label>%s</label>%s</p>", field.Name, fieldHTML)

// TODO: very hacky
if gotDoubleEntry {
htmAgain := fmt.Sprintf("<p><label>%s (repeat)</label>%s</p>", field.Name, fieldHTMLs[field.Name])
htm += reName.ReplaceAllString(htmAgain, fmt.Sprintf("name=\"%s___repeat\"", field.Name))
}
}

return htm
}

func (c *Controller) isFieldHasTag(field reflect.StructField, tag string) bool {
fieldTags := field.Tag.Get(c.tagName)
if fieldTags != "" {
fieldTags := strings.Split(fieldTags, " ")
for _, ft := range fieldTags {
if ft == tag {
return true
}
}
}
return false
}

func (c *Controller) getStructItemFieldHTML(field reflect.StructField, structName string, value string, forEdit bool) string {
h := ""
if c.intFieldValues != nil && c.isFieldInt(field) {
fv, ok := c.intFieldValues[structName+"_"+field.Name]
if ok {
if fv.Type == ValuesMultipleBitChoice {
for ok, ov := range fv.Values {
found := false
if value != "" {
i64, err := strconv.ParseInt(value, 10, 64)
if err == nil {
if i64&int64(ok) > 0 {
found = true
}
}
}
if forEdit {
checked := ""
if found {
checked = " checked"
}
h += fmt.Sprintf(`<input%s type="checkbox" name="%s" value="%d"/> %s`, checked, field.Name, ok, html.EscapeString(ov))
continue
}

// not for edit
if found {
if h != "" {
h += ", "
}
h += html.EscapeString(ov)
}
}
}
if fv.Type == ValuesSingleChoice {
if forEdit {
h += fmt.Sprintf(`<select name="%s">`, field.Name)
for ok, ov := range fv.Values {
selected := ""
if value == fmt.Sprintf("%d", ok) {
selected = " selected"
}
h += fmt.Sprintf(`<option%s value="%d">%s</option>`, selected, ok, html.EscapeString(ov))
}
h += "</select>"
} else {
for ok, ov := range fv.Values {
if value == fmt.Sprintf("%d", ok) {
h += html.EscapeString(ov)
}
}
}

}
}
}

if h != "" {
return h
}

if c.stringFieldValues != nil && field.Type.Kind() == reflect.String {
fv, ok := c.stringFieldValues[structName+"_"+field.Name]
if ok {
if fv.Type == ValuesSingleChoice {
if forEdit {
h = fmt.Sprintf(`<select name="%s">`, field.Name)
for ok, ov := range fv.Values {
selected := ""
if value == ok {
selected = " selected"
}
h += fmt.Sprintf(`<option%s value="%s">%s</option>`, selected, html.EscapeString(ok), html.EscapeString(ov))
}
h += "</select>"
} else {
for ok, ov := range fv.Values {
if value == ok {
h += html.EscapeString(ov)
}
}
}
}
}
}

return h
}

func (c *Controller) isFieldInt(field reflect.StructField) bool {
k := field.Type.Kind()
return k == reflect.Int || k == reflect.Int8 || k == reflect.Int16 || k == reflect.Int32 || k == reflect.Int64
}
68 changes: 68 additions & 0 deletions funcs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package crudui

import "reflect"

// IsFieldKindSupported checks if a field kind is supported by this module
func IsFieldKindSupported(k reflect.Kind) bool {
switch k {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return true
case reflect.String, reflect.Bool:
return true
case reflect.Float32, reflect.Float64:
return true
default:
return false
}
}

func isStructField(u interface{}, field string) bool {
v := reflect.ValueOf(u)
i := reflect.Indirect(v)
s := i.Type()

for j := 0; j < s.NumField(); j++ {
f := s.Field(j)
k := f.Type.Kind()

if !IsFieldKindSupported(k) {
continue
}

if f.Name == field {
return true
}
}

return false
}

func getStructName(u interface{}) string {
v := reflect.ValueOf(u)
i := reflect.Indirect(v)
s := i.Type()
return s.Name()
}

func getStructFieldNames(u interface{}) []string {
v := reflect.ValueOf(u)
i := reflect.Indirect(v)
s := i.Type()

names := []string{}

for j := 0; j < s.NumField(); j++ {
f := s.Field(j)
k := f.Type.Kind()

if !IsFieldKindSupported(k) {
continue
}

names = append(names, f.Name)
}

return names
}
40 changes: 40 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
module github.com/go-phings/crud-ui

go 1.23.4

require (
github.com/go-phings/struct-db-postgres v0.7.0
github.com/go-phings/struct-validator v0.4.7
github.com/lib/pq v1.10.9
github.com/ory/dockertest/v3 v3.11.0
)

require (
dario.cat/mergo v1.0.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/containerd/continuity v0.4.3 // indirect
github.com/docker/cli v26.1.4+incompatible // indirect
github.com/docker/docker v27.1.1+incompatible // indirect
github.com/docker/go-connections v0.5.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/go-phings/struct-sql-postgres v0.6.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/mikolajgs/struct-validator v0.4.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/term v0.5.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.0 // indirect
github.com/opencontainers/runc v1.1.13 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
golang.org/x/sys v0.27.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
Loading