Docs / ArchitectureKit / Guides / Setting Up an HTTP API

Setting Up an HTTP API

To expose commands and queries over HTTP, use the httpapi package:

import "github.com/thenativeweb/architecturekit-golang/architecturekit/httpapi"

Define a type that describes who is making a request, and a function that determines it from the request. Then call the NewAPI function with the store and this function, and create a mux:

type User struct {
  ID          string
  IsLibrarian bool
}

func userFrom(r *http.Request) (User, error) {
  // ...
}

api := httpapi.NewAPI(store, userFrom)
mux := http.NewServeMux()

If the function returns an error, the request is answered with 401 Unauthorized, and neither a command nor a query is run.

For an application without authentication, call the NewPublicAPI function instead. Commands and queries then receive httpapi.NoUser as user:

api := httpapi.NewPublicAPI(store)

Determining the User#

To determine the user in a handler of your own, call the UserOf function. If the user cannot be determined, it returns an error that wraps httpapi.ErrUnauthorized:

mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) {
  user, err := httpapi.UserOf(r, api)
  if err != nil {
    // ...
  }

  // ...
})