Skip to content

crayoned/easystruct

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 

Repository files navigation

easystruct

Install

go install github.com/crayoned/easystruct@latest

Run

easystruct model.go

Generates new function FromRequest for all structs in specific file to mapping request into struct.

Supported data source:

  • header - req.Header
  • query - req.URL.Query()
  • formData - req.FormValue

Supported types:

  • all primitive numbers(ints, uints, floats)
  • slice of all primitive numbers
  • string, []string, []byte, []rune
  • bool

Struct fields have to contain tag description with name es. Tag template data_source=data_name. For example:

type SearchRequest struct {
  User   string `es:"header=x-user-id"`
  Limit  int    `es:"query=limit"`
  Search string `es:"query=search"`
} 

It generates new function like this:

func(sr *SearchRequest) FromRequest(r *http.Request) error {
	if sval := r.Header.Get("x-user-id"); sval != "" {
		sr.User = sval
	}
	if sval := r.URL.Query().Get("limit"); sval != "" {
		nval, err := strconv.Atoi(sval)
		if err != nil {
			return fmt.Errorf("query:limit: %w", err)
		}
		sr.Limit = int(nval)
	}
	if sval := r.URL.Query().Get("search"); sval != "" {
		sr.Search = sval
	}
	return nil
}

Then you can use it in your http handlers:

func processSearch(w http.ResponseWriter, r *http.Request) {
	var payload SearchRequest
	if err := payload.FromRequest(r); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	// do something with payload
}

About

Codogen to serialize request data into struct

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages