1
0

REST API helpers for Go https://pkg.go.dev/github.com/annybs/go-rest

Aneurin Barker Snook 727a744d55 fix module name 10 сар өмнө
.github 7d4519f06f add test workflow 10 сар өмнө
.gitignore f2bd1255dd ensure go.sum not committed 10 сар өмнө
LICENSE.md 7e78d5e181 duplicate license to each package 11 сар өмнө
README.md 2204816567 fix link to license 10 сар өмнө
body.go 33eba7de84 wrap request read error as bad request 1 жил өмнө
body_test.go a9ef6b837b add request body read tests 1 жил өмнө
error.go 60fc78574e fix staticcheck suggestions 1 жил өмнө
error_test.go e3f3b16b84 add validation error type, fix tests, add number tests 1 жил өмнө
go.mod 727a744d55 fix module name 10 сар өмнө
headers.go 88c2216e76 remove errant print 11 сар өмнө
headers_test.go ca9e4765cb add rest authorization header support 11 сар өмнө

README.md

Go REST

Some handy functions for developing JSON-based REST APIs. In particular, it simplifies reading HTTP request bodies, writing HTTP response bodies, and handling errors.

Error handling

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.

Example

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.

License

See LICENSE.md