https://github.com/kpurdon/apiresponse
A simple helper for writing JSON formatted responses in an HTTP API.
https://github.com/kpurdon/apiresponse
api golang http json
Last synced: about 1 year ago
JSON representation
A simple helper for writing JSON formatted responses in an HTTP API.
- Host: GitHub
- URL: https://github.com/kpurdon/apiresponse
- Owner: kpurdon
- License: mit
- Created: 2018-12-11T18:29:12.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-03-11T01:30:38.000Z (about 7 years ago)
- Last Synced: 2025-01-02T13:28:05.397Z (over 1 year ago)
- Topics: api, golang, http, json
- Language: Go
- Homepage:
- Size: 24.4 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://circleci.com/gh/kpurdon/apiresponse)
[](https://codecov.io/gh/kpurdon/apiresponse)
[](http://godoc.org/github.com/kpurdon/apiresponse)
[](https://goreportcard.com/report/github.com/kpurdon/apiresponse)
apiresponse
-----
A simple helper for writing JSON formatted responses in an HTTP API.
## Examples
### Initialize a Responder and Write
``` go
func Foo(w http.ResponseWriter, r *http.Request) {
responder := apiresponse.NewResponder(w)
responder.OK()
}
```
results in
``` json
HTTP/1.1 200 OK
Content-Length: 38
Content-Type: application/json
Date: Thu, 13 Dec 2018 18:56:14 GMT
{
"status_code": 200,
"status_text": "OK"
}
```
### Initialize a Responder and Write with a Header
``` go
func Foo(w http.ResponseWriter, r *http.Request) {
responder := apiresponse.NewResponder(w)
responder.WithHeader("Test-Key", "test/value")
responder.OK()
}
```
results in
``` json
HTTP/1.1 200 OK
Content-Length: 38
Content-Type: application/json
Date: Thu, 13 Dec 2018 18:56:17 GMT
Test-Key: test/value
{
"status_code": 200,
"status_text": "OK"
}
```
### Initialize a Responder and Write with Data
``` go
func Foo(w http.ResponseWriter, r *http.Request) {
responder := apiresponse.NewResponder(w)
data := struct{Name string}{Name:"test"}
responder.WithData(data)
responder.OK()
}
```
results in
``` json
HTTP/1.1 200 OK
Content-Length: 15
Content-Type: application/json
Date: Thu, 13 Dec 2018 18:56:21 GMT
{
"Name": "test"
}
```