httpflags

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 28, 2020 License: MIT Imports: 6 Imported by: 2

Documentation

Overview

Package httpflags provides a convenient way of filling struct fields from http request form values. Exposed struct fields should have special `flag` tag attached:

args := struct {
	Name    string `flag:"name"`
	Age     uint   `flag:"age"`
	Married bool   // this won't be exposed
}{
	// default values
	Name: "John Doe",
	Age:  34,
}

After declaring flags and their default values as above, call httpflags.Parse() inside http.Handler to fill struct fields from http request form values:

func myHandler(w http.ResponseWriter, r *http.Request) {
	args := struct {
		...
	}{}
	if err := httpflags.Parse(&args, r) ; err != nil {
		http.Error(w, "Bad request", http.StatusBadRequest)
		return
	}
	// use args fields here

Parse() calls ParseForm method of http.Request automatically, so it understands parsed values both from the URL field's query parameters and the POST or PUT form data.

Package httpflags supports all basic types supported by xxxVar functions from standard library flag package: int, int64, uint, uint64, float64, bool, string, time.Duration as well as types implementing flag.Value interface. Parse panics on non-empty `flag` tag on unsupported type field.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(dst interface{}, r *http.Request) error

Parse fills dst struct with values extracted from r.Form. dst should be a non-nil pointer to struct having its exported attributes tagged with 'flag' tag — see autoflags package documentation. r.ParseForm is called automatically. Only the first value of each key from r.Form is used.

Example
package main

import (
	"fmt"
	"net/http/httptest"

	"github.com/artyom/httpflags"
)

func main() {
	args := &struct {
		Name  string `flag:"name"`
		Age   int    `flag:"age"`
		Extra bool   `flag:"extra"`
	}{
		// default values:
		Age:   42,
		Extra: true,
	}
	req := httptest.NewRequest("GET", "/?name=John%20Doe&extra=false", nil)
	if err := httpflags.Parse(args, req); err != nil {
		fmt.Println(err)
	}
	fmt.Printf("updated args: %+v\n", args)

	req = httptest.NewRequest("GET", "/?badField=boom", nil)
	fmt.Println("parsing request with undefined field:", httpflags.Parse(args, req))
	fmt.Printf("args stay the same: %+v\n", args)
}
Output:

updated args: &{Name:John Doe Age:42 Extra:false}
parsing request with undefined field: <nil>
args stay the same: &{Name:John Doe Age:42 Extra:false}

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL