Go - Api.Route()

Creates a new route (path) within an API.

import (
  "fmt"

  "github.com/nitrictech/go-sdk/handler"
  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  api, err := nitric.NewApi("public")
  if err != nil {
    return
  }

  route := api.NewRoute("/hello")

  if err := nitric.Run(); err != nil {
    fmt.Println(err)
  }
}

Parameters

  • Name
    match
    Required
    Required
    Type
    string
    Description

    The path matcher to use for this route. Calling NewRoute on the same API more than once with the same matcher will return the same route object. Matchers accept path parameters in the form of a colon prefixed string. The string provided will be used as that path parameter's name when calling middleware and handlers. See create a route with path params

  • Name
    middleware
    Optional
    Optional
    Type
    ...HttpMiddleware
    Description

    The middleware (code) that should be run on all requests to this route. Useful for applying universal middleware such as CORS headers or Auth, across an entire route from a single place.

Examples

Create a route

import (
  "fmt"

  "github.com/nitrictech/go-sdk/handler"
  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  api, err := nitric.NewApi("public")
  if err != nil {
    return
  }

  route := api.NewRoute("/hello")

  if err := nitric.Run(); err != nil {
    fmt.Println(err)
  }
}

Create a route with path params

Route paths can include dynamic parameters. These values will automatically be parsed and provided in the context object for your middleware and handlers as a string.

For example, if you have a customers path and you want to include a customerId param you would define the route like this.

import (
  "fmt"

  "github.com/nitrictech/go-sdk/handler"
  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  api, err := nitric.NewApi("public")
  if err != nil {
    return
  }

  // Define route with customerId param
  route := api.NewRoute("/customers/:customerId")

  if err := nitric.Run(); err != nil {
    fmt.Println(err)
  }
}

Create a route with middleware

import (
  "fmt"

  "github.com/nitrictech/go-sdk/handler"
  "github.com/nitrictech/go-sdk/nitric"
)

func authMiddleware(ctx *handler.HttpContext, next handler.HttpHandler) (*handler.HttpContext, error) {
  // Perform auth validation
  return next(ctx)
}

func main() {
  api, err := nitric.NewApi("public")
  if err != nil {
    return
  }

  route := api.NewRoute("/hello", authMiddleware)

  if err := nitric.Run(); err != nil {
    fmt.Println(err)
  }
}