Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

main

v4.1.2+incompatible
gitee.com/lanyuguo/chi/_examples/rest

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

29 matches

Top ↑

REST ==== This example demonstrates a HTTP REST web service with some fixture data. Follow along the example and patterns.

Also check routes.json for the generated docs from passing the -routes flag

Boot the server: ---------------- $ go run main.go

Client requests: ---------------- $ curl http://localhost:3333/ root.

$ curl http://localhost:3333/articles [{"id":"1","title":"Hi"},{"id":"2","title":"sup"}]

$ curl http://localhost:3333/articles/1 {"id":"1","title":"Hi"}

$ curl -X DELETE http://localhost:3333/articles/1 {"id":"1","title":"Hi"}

$ curl http://localhost:3333/articles/1 "Not Found"

$ curl -X POST -d '{"id":"will-be-omitted","title":"awesomeness"}' http://localhost:3333/articles {"id":"97","title":"awesomeness"}

$ curl http://localhost:3333/articles/97 {"id":"97","title":"awesomeness"}

$ curl http://localhost:3333/articles [{"id":"2","title":"sup"},{"id":"97","title":"awesomeness"}]

Variables

ErrNotFound

var ErrNotFound = &ErrResponse{HTTPStatusCode: 404, StatusText: "Resource not found."}

Functions

AdminOnly

func AdminOnly(next http.Handler) http.Handler

AdminOnly middleware restricts access to just administrators.

ArticleCtx

func ArticleCtx(next http.Handler) http.Handler

ArticleCtx middleware is used to load an Article object from the URL parameters passed through as the request. In case the Article could not be found, we stop here and return a 404.

CreateArticle

func CreateArticle(w http.ResponseWriter, r *http.Request)

CreateArticle persists the posted Article and returns it back to the client as an acknowledgement.

DeleteArticle

func DeleteArticle(w http.ResponseWriter, r *http.Request)

DeleteArticle removes an existing Article from our persistent store.

ErrInvalidRequest

func ErrInvalidRequest(err error) render.Renderer

ErrRender

func ErrRender(err error) render.Renderer

GetArticle

func GetArticle(w http.ResponseWriter, r *http.Request)

GetArticle returns the specific Article. You'll notice it just fetches the Article right off the context, as its understood that if we made it this far, the Article must be on the context. In case its not due to a bug, then it will panic, and our Recoverer will save us.

ListArticles

func ListArticles(w http.ResponseWriter, r *http.Request)

NewArticleListResponse

func NewArticleListResponse(articles []*Article) []render.Renderer

SearchArticles

func SearchArticles(w http.ResponseWriter, r *http.Request)

SearchArticles searches the Articles data for a matching article. It's just a stub, but you get the idea.

UpdateArticle

func UpdateArticle(w http.ResponseWriter, r *http.Request)

UpdateArticle updates an existing Article in our persistent store.

Types

Article

type Article struct {
	ID     string `json:"id"`
	UserID int64  `json:"user_id"` // the author
	Title  string `json:"title"`
	Slug   string `json:"slug"`
}

Article data model. I suggest looking at https://upper.io for an easy and powerful data persistence adapter.

ArticleRequest

type ArticleRequest struct {
	*Article

	User *UserPayload `json:"user,omitempty"`

	ProtectedID string `json:"id"` // override 'id' json to have more control
}

ArticleRequest is the request payload for Article data model.

NOTE: It's good practice to have well defined request and response payloads so you can manage the specific inputs and outputs for clients, and also gives you the opportunity to transform data on input or output, for example on request, we'd like to protect certain fields and on output perhaps we'd like to include a computed field based on other values that aren't in the data model. Also, check out this awesome blog post on struct composition: http://attilaolah.eu/2014/09/10/json-and-struct-composition-in-go/

ArticleRequest.Bind

func (a *ArticleRequest) Bind(r *http.Request) error

ArticleResponse

type ArticleResponse struct {
	*Article

	User *UserPayload `json:"user,omitempty"`

	// We add an additional field to the response here.. such as this
	// elapsed computed property
	Elapsed int64 `json:"elapsed"`
}

ArticleResponse is the response payload for the Article data model. See NOTE above in ArticleRequest as well.

In the ArticleResponse object, first a Render() is called on itself, then the next field, and so on, all the way down the tree. Render is called in top-down order, like a http handler middleware chain.

NewArticleResponse

func NewArticleResponse(article *Article) *ArticleResponse

ArticleResponse.Render

func (rd *ArticleResponse) Render(w http.ResponseWriter, r *http.Request) error

ErrResponse

type ErrResponse struct {
	Err            error `json:"-"` // low-level runtime error
	HTTPStatusCode int   `json:"-"` // http response status code

	StatusText string `json:"status"`          // user-level status message
	AppCode    int64  `json:"code,omitempty"`  // application-specific error code
	ErrorText  string `json:"error,omitempty"` // application-level error message, for debugging
}

ErrResponse renderer type for handling all sorts of errors.

In the best case scenario, the excellent github.com/pkg/errors package helps reveal information on the error, setting it on Err, and in the Render() method, using it to set the application-specific error code in AppCode.

ErrResponse.Render

func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error

User

type User struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

User data model

UserPayload

type UserPayload struct {
	*User
	Role string `json:"role"`
}

NewUserPayloadResponse

func NewUserPayloadResponse(user *User) *UserPayload

UserPayload.Bind

func (u *UserPayload) Bind(r *http.Request) error

Bind on UserPayload will run after the unmarshalling is complete, its a good time to focus some post-processing after a decoding.

UserPayload.Render

func (u *UserPayload) Render(w http.ResponseWriter, r *http.Request) error

Dependency graph