Skip to content

Instantly share code, notes, and snippets.

@artyom
Last active September 12, 2016 19:52
Show Gist options
  • Select an option

  • Save artyom/07657f9c5fd84ef0badd84b49ac034d8 to your computer and use it in GitHub Desktop.

Select an option

Save artyom/07657f9c5fd84ef0badd84b49ac034d8 to your computer and use it in GitHub Desktop.
package rest
import (
"flag"
"io/ioutil"
"net/url"
"github.com/artyom/autoflags"
)
// parseFields fills dst struct with values provided using flag parsing logic
// relying on autoflags package. dst must be a pointer to struct. Only the first
// value of each key from provided url.Values are used.
func parseFields(dst interface{}, vals url.Values) error {
fs := new(flag.FlagSet)
fs.SetOutput(ioutil.Discard)
autoflags.DefineFlagSet(fs, dst)
args := make([]string, 0, len(vals)*2)
for k := range vals {
args = append(args, "-"+k, vals.Get(k))
}
return fs.Parse(args)
}
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"github.com/artyom/autoflags"
)
// parseFields fills dst struct with values provided using flag parsing logic
// relying on autoflags package. dst must be a pointer to struct. Only the first
// value of each key from provided url.Values are used.
func parseFields(dst interface{}, vals url.Values) error {
fs := new(flag.FlagSet)
fs.SetOutput(ioutil.Discard)
autoflags.DefineFlagSet(fs, dst)
args := make([]string, 0, len(vals)*2)
for k := range vals {
args = append(args, "-"+k, vals.Get(k))
}
return fs.Parse(args)
}
func parseArgs(dst interface{}, r *http.Request) error {
if err := r.ParseForm(); err != nil {
return err
}
return parseFields(dst, r.Form)
}
func main() {
log.Fatal(http.ListenAndServe("localhost:8080", http.HandlerFunc(example)))
}
func example(w http.ResponseWriter, r *http.Request) {
args := &struct {
Name string `flag:"name"`
Age uint64 `flag:"age"`
}{}
if err := parseArgs(args, r); err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "%s is %d years old\n", args.Name, args.Age)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment