diff options
Diffstat (limited to 'content/posts/004.md')
| -rw-r--r-- | content/posts/004.md | 14 |
1 files changed, 7 insertions, 7 deletions
diff --git a/content/posts/004.md b/content/posts/004.md index ebfaad2..e5d28b4 100644 --- a/content/posts/004.md +++ b/content/posts/004.md @@ -10,7 +10,7 @@ I write them like this for reasons that are probably fairly contextual. I've wri I've used `ints` instead of the `http.StatusXXXX` and omitted `JSON` tags in an attempt to try save up screen space. To begin with, you might have something like this: -``` +```go package main import ( @@ -33,7 +33,7 @@ func main() { Then you might get told off because you've just registered routes with the default mux, which isn't very testable. So you tweak it a little bit. -``` +```go package main import ( @@ -71,7 +71,7 @@ func main() { But now you need to do something real, you want to store and fetch data. -``` +```go package main import ( @@ -159,7 +159,7 @@ func main() { } ``` -``` +```shell ❯ curl -X POST localhost:8080 --header "Content-Type: application/json" -d '{"foo":"bar"}' {"ID":0,"Foo":"bar"} ❯ curl -X GET localhost:8080/0 @@ -173,7 +173,7 @@ This API is inconsistent. It sometimes returns `JSON`, and the others return str So let's try to standardise things. First, let's design some form of REST spec. -``` +```go type JSONResp[T any] struct { Resources []T Errs []ErrorResp @@ -187,7 +187,7 @@ type ErrorResp struct { We want to be able to support fetching multiple resources at once, if we can only fetch some resources, let's return them under `resources` and show the errors under `errs` Now, add some helpful functions to handle things. -``` +```go func Post[In any, Out any](successCode int, fn func(context.Context, In) ([]Out, []ErrorResp)) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { var v In @@ -229,7 +229,7 @@ And we've standardised all `POST` requests! This function can be used by all `POST` requests, ensuring they adhere to the spec. It also removes the repetitive code around marshalling and unmarshalling to `JSON` and handles errors in a consistent manner. The handler functions accept a `context` param and their expected struct input. -``` +```go func (s *Server) Register(mux *http.ServeMux) { ... mux.HandleFunc("POST /", Post(201, s.Post)) |
