REST API helpers for Go https://pkg.go.dev/github.com/annybs/go-rest
|
пре 10 месеци | |
---|---|---|
.github | пре 10 месеци | |
.gitignore | пре 10 месеци | |
LICENSE.md | пре 11 месеци | |
README.md | пре 10 месеци | |
body.go | пре 1 година | |
body_test.go | пре 1 година | |
error.go | пре 1 година | |
error_test.go | пре 1 година | |
go.mod | пре 10 месеци | |
headers.go | пре 11 месеци | |
headers_test.go | пре 11 месеци |
Some handy functions for developing JSON-based REST APIs. In particular, it simplifies reading HTTP request bodies, writing HTTP response bodies, and handling errors.
You can use errors.Is()
to ascertain the type of errors thrown by validation functions, but for the most part, this isn't necessary because the write functions already do that.
package main
import (
"errors"
"math/rand"
"net/http"
"github.com/annybs/go/rest"
)
type Handler struct{}
func (*Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
n := rand.Intn(3)
if n == 0 {
rest.WriteResponseJSON(w, http.StatusOK, map[string]string{"status": "OK"})
} else if n == 1 {
rest.WriteErrorJSON(w, errors.New("the original error message is added to data.error"))
} else {
rest.WriteErrorJSON(w, rest.ErrNotFound)
}
}
func main() {
http.ListenAndServe("localhost:8000", &Handler{})
}
Open http://localhost:8000 in your browser and refresh a bunch of times to see the different possible responses.
See LICENSE.md