A simple JSON parser and encoding for your Go REST servers.
Report Bug
·
Request Feature
http-jparser
is a simple Go library used for parsing and validating JSON request body and JSON responding. The parser is compatible with any framework that exposes the HTTP
interface like go-chi. Under the hood, the library uses go-json for JSON encoding/decoding and go-validator for validation.
go get -u github.com/akhilmhdh/http-jparser
- Simple API
- Request body validation
- Compatibility with
net/http
- Uses go-json for fast encoding/decoding JSON
The following examples uses go-chi
package main
import (
"net/http"
jparser "github.com/akhilmhdh/http-jparser"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
type Response struct {
HTTPStatusCode int `json:"-"` // http response status code
Success bool `json:"success"` // flag to indicated failed to success
Message string `json:"message"` // user-level status message
AppCode int64 `json:"code,omitempty"` // application-specific error code
ErrorText interface{} `json:"error,omitempty"` // application-level error message, for debugging
Data interface{} `json:"data,omitempty"`
}
func (e *Response) GetStatusCode() int {
return e.HTTPStatusCode
}
type ReqBody struct {
Key string `json:"key" validate:"lowercase"`
Value string `json:"value"`
}
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
body := &Response{
HTTPStatusCode: 200,
Success: true,
Message: "Success Request Message",
}
jparser.Send(w, r, body)
})
r.Post("/", func(w http.ResponseWriter, r *http.Request) {
data := &ReqBody{}
// GET JSON request body
if err := jparser.Get(r, data); err != nil {
// To check if error is validation error or not
// if vErr, ok := err.(*jparser.ValidationErrors); ok {}
// ErrInvalidRequest can be a wrapper on Response to return error messages
jparser.Send(w, r, ErrInvalidRequest())
return
}
// success response
jparser.Send(w, r, &Response{
HTTPStatusCode: 200,
Message: "Data returned successfully",
Success: true,
Data: data,
})
})
http.ListenAndServe(":3000", r)
}
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature
) - Commit your Changes (
git commit -m 'Add some AmazingFeature'
) - Push to the Branch (
git push origin feature/AmazingFeature
) - Open a Pull Request