https://github.com/mna/httpparms
Package httpparms provides helper functions and mechanisms to load the content of an HTTP request into a Go struct.
https://github.com/mna/httpparms
Last synced: 5 months ago
JSON representation
Package httpparms provides helper functions and mechanisms to load the content of an HTTP request into a Go struct.
- Host: GitHub
- URL: https://github.com/mna/httpparms
- Owner: mna
- License: bsd-3-clause
- Created: 2016-07-23T20:35:58.000Z (about 10 years ago)
- Default Branch: master
- Last Pushed: 2023-09-22T15:14:15.000Z (almost 3 years ago)
- Last Synced: 2025-12-18T04:05:03.001Z (7 months ago)
- Language: Go
- Size: 15.6 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# httpparms [][godoc] [](https://semaphoreci.com/mna/httpparms)
Package httpparms provides helper functions and types to load the content of an HTTP request into a Go struct. It supports loading the query string parameters, the form-encoded body and the JSON-encoded body. If the struct implements the `Validator` interface, it also validates the values.
See the [godoc][] for full documentation.
## Installation
```
$ go get github.com/PuerkitoBio/httpparms
```
Use `-u` to update, `-t` to install test dependencies.
## Example
```
type parmTest struct {
S string
I int `schema:"-"`
Q string `schema:"q" json:"q_value"`
}
func (pt *parmTest) Validate() error {
if pt.S == "" {
return errors.New("parameter `s` is required")
}
if pt.I > 2 {
return errors.New("parameter `i` is too big")
}
return nil
}
var parser = &httpparms.Parser{
// use github.com/gorilla/schema as form decoder
Form: schema.NewDecoder().Decode,
}
func myHandler(w http.ResponseWriter, r *http.Request) {
var pt parmTest
if err := parser.ParseQueryJSON(r, &pt); err != nil {
// Optionally get the parameter names in error with
// parms := parser.ParametersFromErr(err)
// and use this in the error message.
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// process the request with valid parameters...
}
```
## License
The [BSD 3-clause][bsd] license, see LICENSE file.
[bsd]: http://opensource.org/licenses/BSD-3-Clause
[godoc]: http://godoc.org/github.com/PuerkitoBio/httpparms