A lightweight go library for parsing form data or json from an http.Request.

Forms

GoDoc

Forms is a lightweight, but incredibly useful go library for parsing form data from an http.Request. It supports multipart forms, url-encoded forms, json data, and url query parameters. It also provides helper methods for converting data into other types and a Validator object which can be used to validate the data. Forms is framework-agnostic and works directly with the http package.

Version 0.4.0

Development Status

Forms is being actively developed and is well-tested. However, since it is still a young library, it is not recommended for use in mission-critical production applications at this time. It is probably fine to use for low-traffic hobby sites, and in fact we encourage its use in those settings to help polish the API and find missing features and hidden bugs. Pull requests and issue reports are much appreciated :)

Forms follows semantic versioning but offers no guarantees of backwards compatibility until version 1.0. Keep in mind that breaking changes might occur. We will do our best to make the community aware of any non-trivial breaking changes beforehand. We recommend using a dependency vendoring tool such as godep to ensure that breaking changes will not break your application.

Installation

Install like you would any other package:

go get github.com/albrow/forms

Then include the package in your import statements:

import "github.com/albrow/forms"

Example Usage

Meant to be used inside the body of an http.HandlerFunc or any function that has access to an http.Request.

func CreateUserHandler(res http.ResponseWriter, req *http.Request) {
	// Parse request data.
	userData, err := forms.Parse(req)
	if err != nil {
		// Handle err
		// ...
	}

	// Validate
	val := userData.Validator()
	val.Require("username")
	val.LengthRange("username", 4, 16)
	val.Require("email")
	val.MatchEmail("email")
	val.Require("password")
	val.MinLength("password", 8)
	val.Require("confirmPassword")
	val.Equal("password", "confirmPassword")
	val.RequireFile("profileImage")
	val.AcceptFileExts("profileImage", "jpg", "png", "gif")
	if val.HasErrors() {
		// Write the errors to the response
		// Maybe this means formatting the errors as json
		// or re-rendering the form with an error message
		// ...
	}

	// Use data to create a user object
	user := &models.User {
		Username: userData.Get("username"),
		Email: userData.Get("email"),
		HashedPassword: hash(userData.Get("password")),
	}

	// Continue by saving the user to the database and writing
	// to the response
	// ...


	// Get the contents of the profileImage file
	imageBytes, err := userData.GetFileBytes("profileImage")
	if err != nil {
	  // Handle err
	}
	// Now you can either copy the file over to your server using io.Copy,
	// upload the file to something like amazon S3, or do whatever you want
	// with it.
}

Contributing

See CONTRIBUTING.md

License

Forms is licensed under the MIT License. See the LICENSE file for more information.

Similar Resources

Lightweight Router for Golang using net/http standard library with custom route parsing, handler and context.

Go-Lightweight-Router Lightweight Router for Golang using net/http standard library with custom route parsing, handler and context. Further developmen

Nov 3, 2021

⚔ Go package for data validation and filtering. support Map, Struct, Form data. Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器,支持自定义验证器、自定义消息、字段翻译。

Validate The package is a generic Go data validate and filter tool library. Support quick validate Map, Struct, Request(Form, JSON, url.Values, Upload

Dec 28, 2022

Goget will send a http request, and show the request time, status, response, and save response to a file

Goget will send a http request, and show the request time, status, response, and save response to a file

Feb 9, 2022

Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.

Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.

Validate golang request data with simple rules. Highly inspired by Laravel's request validation. Installation Install the package using $ go get githu

Dec 29, 2022

Custom generic HTTP handler providing automatic JSON decoding/encoding of HTTP request/response to your concrete types

gap Custom generic HTTP handler providing automatic JSON decoding/encoding of HTTP request/response to your concrete types. gap.Wrap allows to use the

Aug 28, 2022

This library provides an ASTERIX Frame(binary data) decoding/parsing(json,xml) capabilities for Go.

GoAsterix This library provides an ASTERIX Frame(binary data) decoding/parsing(json,xml) capabilities for Go. ASTERIX ASTERIX (All Purpose Structured

Dec 13, 2022

Arjuns-urgent-notification-backend - A simple Golang app that handles form JSON POST requests

Arjun's Urgent Notification Backend This is intended to let people urgently noti

Jan 7, 2022

Prometheus Common Data Exporter can parse JSON, XML, yaml or other format data from various sources (such as HTTP response message, local file, TCP response message and UDP response message) into Prometheus metric data.

Prometheus Common Data Exporter can parse JSON, XML, yaml or other format data from various sources (such as HTTP response message, local file, TCP response message and UDP response message) into Prometheus metric data.

Prometheus Common Data Exporter Prometheus Common Data Exporter 用于将多种来源(如http响应报文、本地文件、TCP响应报文、UDP响应报文)的Json、xml、yaml或其它格式的数据,解析为Prometheus metric数据。

May 18, 2022

github-actions-merger is github actions that merges pull request with commit message including pull request labels.

github-actions-merger github-actions-merger is github actions that merges pull request with commit message including pull request labels. Usage Write

Dec 7, 2022

Add request id to a request's context

RequestID 🔎 This is a very simple piece of middleware for adding request/correlation IDs to the context of a http request. By default, this module wi

Dec 4, 2021

Forms is a fast, powerful, flexible, sortable web form rendering library written in golang.

forms Description forms makes form creation and handling easy. It allows the creation of form without having to write HTML code or bother to make the

Oct 2, 2022

Bxog is a simple and fast HTTP router for Go (HTTP request multiplexer).

Bxog is a simple and fast HTTP router for Go (HTTP request multiplexer). Usage An example of using the multiplexer: package main import ( "io" "net

Dec 26, 2022

Parsing JSON is a hassle in golang

GoJSON Parsing JSON is a hassle in golang. This package will allow you to parse and search elements in a json without structs. Install gojson go get g

Nov 12, 2021

Golang port of simdjson: parsing gigabytes of JSON per second

Golang port of simdjson: parsing gigabytes of JSON per second

This is a Golang port of simdjson, a high performance JSON parser developed by Daniel Lemire and Geoff Langdale. It makes extensive use of SIMD instructions to achieve parsing performance of gigabytes of JSON per second.

Dec 30, 2022

Easy JSON parsing, stringifying, and accesing

Easy JSON parsing, stringifying, and accesing

Nov 23, 2021

Rdelf2json - CLI application for parsing ELF and converting to json

rdelf2json CLI application for parsing ELF and converting to json Install go ins

Jan 22, 2022

a package for decode form's values into struct in Go

formam A Go package to decode HTTP form and query parameters. The only requirement is Go 1.10 or later. Features Infinite nesting for maps, structs an

Nov 25, 2022

Simple application written in Go that combines two wordlists and a list of TLDs to form domain names and check if they are already registered.

Domainerator Domainerator was my first Go application. It combines two wordlists (prefixes and suffixes) and a list of TLDs to form domain names and c

Sep 16, 2022

A Form Encoding & Decoding Package for Go

form A Form Encoding & Decoding Package for Go, written by Alvaro J. Genial. Synopsis This library is designed to allow seamless, high-fidelity encodi

Nov 23, 2022
Comments
  • feature: add maximum data size to Parse signature

    feature: add maximum data size to Parse signature

    currently when parsing multipart/form-data requests, the size of data is locked in at 2048. For image uploads this might be a little low; is it possible to add the maximum size to the functions signature? Or perhaps a ParseMax(*http.Request, uint) function?

  • Allow for validating files in multipart forms

    Allow for validating files in multipart forms

    It would be cool if go-data-parser could perform basic validations for files uploaded via multipart form. Reading and validating the data might be overly-complex, but the following features seem reasonable:

    1. Validate the existence of a file in the form a la the current KeyExists method.
    2. Validate the mime type of the file, i.e. check if it is a jpeg file.
  • Add RequireAll function & test

    Add RequireAll function & test

    Simple multiple arguments Require(). Not sure if RequireAll must return *ValidationResult. RequireAll() might also replace Require() without breaking compatibility.

  • Intent to Break Backwards Compatibility

    Intent to Break Backwards Compatibility

    I wanted to let the community know that I intend to make major changes to this library in the near future which will not be backwards compatible. I have updated the README with versioning information and recommend that for serious applications you use a dependency vendoring tool, such as godep.

    The biggest change is that validation methods will be chainable, as they are in go-humble/form. IMO chainable methods read better and reduce code clutter. We could go from this:

    val.Require("age")
    val.TypeInt("age")
    val.Greater("age", 0)
    

    To this:

    form.Validate("age").Required().Int().GreaterThan(0)
    

    As a consequence, instead of calling Message at the end of a validation method, we will need to introduce new methods for adding custom messages. Currently I am thinking to mimic go-humble/form and introduce methods with the f suffix for adding custom messages.

    // Requiredf is like Required but allows you to specify a custom error message.
    // The arguments format and args work exactly like they do in fmt.Sprintf.
    func (val *Validation) Requiredf(format string, args ...interface{}) *Validation
    

    In addition, method names will be more consistent. I want the methods to read nicely without introducing too much verbosity.

Related tags
A Form Encoding & Decoding Package for Go

form A Form Encoding & Decoding Package for Go, written by Alvaro J. Genial. Synopsis This library is designed to allow seamless, high-fidelity encodi

Nov 23, 2022
Go library for parsing and submitting HTML forms

gosubmit Description Docs are available here: https://godoc.org/github.com/jeremija/gosubmit Helps filling out plain html forms during testing. Will a

Nov 14, 2022
gorilla/csrf provides Cross Site Request Forgery (CSRF) prevention middleware for Go web applications & services 🔒

gorilla/csrf gorilla/csrf is a HTTP middleware library that provides cross-site request forgery (CSRF) protection. It includes: The csrf.Protect middl

Dec 26, 2022
Reflectionless data binding for Go's net/http (not actively maintained)
Reflectionless data binding for Go's net/http (not actively maintained)

binding Reflectionless data binding for Go's net/http Features HTTP request data binding Data validation (custom and built-in) Error handling Benefits

Nov 18, 2022
Trims, sanitizes & scrubs data based on struct tags (go, golang)

Conform- keep user input in check (go, golang) Trim, sanitize, and modify struct string fields in place, based on tags. Update Jan 12, 2016 -- Now als

Dec 20, 2022
Data validation, cleaning and error collection for golang

GoForms - form data validation, cleaning and error reporting The goforms library is a proof-of-concept for a data validation, cleaning and error colle

Jan 14, 2022
Mantil-template-form-to-dynamodb - Receive form data and write it to a DynamoDB table
Mantil-template-form-to-dynamodb - Receive form data and write it to a DynamoDB table

This template is an example of serverless integration between Google Forms and DynamoDB

Jan 17, 2022
Mcopa - A library allows for parsing an email message into a more convenient form than the net/mail provides

Mail content parsing This library allows for parsing an email message into a mor

Jan 1, 2022
ByNom is a Go package for parsing byte sequences, suitable for parsing text and binary data

ByNom is a Go package for parsing byte sequences. Its goal is to provide tools to build safe byte parsers without compromising the speed or memo

May 5, 2021
Request: a HTTP request library for Go with interfaces and mocks for unit tests

Requester Request is a HTTP request library for Go with interfaces and mocks for

Jan 10, 2022