github.com/kyleu/dbaudit@v0.0.2-0.20240321155047-ff2f2c940496/app/controller/cutil/args.go (about)

     1  // Package cutil - Content managed by Project Forge, see [projectforge.md] for details.
     2  package cutil
     3  
     4  import (
     5  	"net/http"
     6  
     7  	"github.com/samber/lo"
     8  
     9  	"github.com/kyleu/dbaudit/app/util"
    10  )
    11  
    12  type Arg struct {
    13  	Key         string   `json:"key"`
    14  	Title       string   `json:"title"`
    15  	Description string   `json:"description,omitempty"`
    16  	Type        string   `json:"type,omitempty"`
    17  	Default     string   `json:"default,omitempty"`
    18  	Choices     []string `json:"choices,omitempty"`
    19  }
    20  
    21  type Args []*Arg
    22  
    23  type ArgResults struct {
    24  	Args    Args          `json:"args"`
    25  	Values  util.ValueMap `json:"values"`
    26  	Missing []string      `json:"missing,omitempty"`
    27  }
    28  
    29  func (a *ArgResults) HasMissing() bool {
    30  	return len(a.Missing) > 0
    31  }
    32  
    33  func CollectArgs(r *http.Request, args Args) *ArgResults {
    34  	ret := make(util.ValueMap, len(args))
    35  	var missing []string
    36  	lo.ForEach(args, func(arg *Arg, _ int) {
    37  		qa := r.URL.Query()
    38  		if !qa.Has(arg.Key) {
    39  			missing = append(missing, arg.Key)
    40  		}
    41  		ret[arg.Key] = qa.Get(arg.Key)
    42  	})
    43  	return &ArgResults{Args: args, Values: ret, Missing: missing}
    44  }