Last active
September 12, 2016 19:52
-
-
Save artyom/07657f9c5fd84ef0badd84b49ac034d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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