Copper
  • Intro to Copper
  • Getting Started
    • Installation
    • Create Project
      • Go Templates
      • Tailwind
      • React
      • React + Tailwind
      • REST API
  • Guides
    • HackerNews Clone
    • Deploy with Fly.io
  • The Basics
    • Directory Structure
    • Dependency Injection
  • Core
    • App Lifecycle
    • Configuration
    • Error Handling
    • Logging
  • HTTP
    • Routing
    • Read & Write JSON
    • HTML Views
    • Middleware
  • SQL
    • Queries
    • Migrations
Powered by GitBook
On this page

Was this helpful?

  1. HTTP

Routing

Routers

Routers are simple Go structs that implement the chttp.Router interface. Routers can be used to define and group together HTTP routes.

type Router interface {
    Routes() []Route
}

By default, Copper provides pkg/app/router.go. Create more routers as your project grows to organize and group routes.

Add a router to a package using the Copper CLI -

$ copper scaffold:router <package>

Create Routes

In a package with an existing Router, you can add a route to it using the Copper CLI -

copper scaffold:route \
    -handler=HandleRocketLaunch \
    -path=/rockets/{id}/launch \
    -method=Post \
    <package>

Sample Router

pkg/rockets/router.go
package rockets

import (..)

type NewRouterParams struct {
	RW     *chttp.ReaderWriter
	Logger clogger.Logger
}

func NewRouter(p NewRouterParams) *Router {
	return &Router{
		rw:     p.RW,
		logger: p.Logger,
	}
}

// Router struct implements the `chttp.Router` interface. It holds all the
// dependencies needed for its handlers.
type Router struct {
	rw     *chttp.ReaderWriter
	logger clogger.Logger
}

// Routes returns a list of chttp.Route managed by this Router.
func (ro *Router) Routes() []chttp.Route {
	return []chttp.Route{
		{
			Path:    "/rockets/{id}/launch",
			Methods: []string{http.MethodPost},
			Handler: ro.HandleRocketLaunch,
		},
	}
}

// HandleRocketLaunch is invoked when a POST request is made to the 
// "/rockets/{id}/launch" endpoint
func (ro *Router) HandleRocketLaunch(w http.ResponseWriter, r *http.Request) {
	// Handle request here..
}
PreviousLoggingNextRead & Write JSON

Last updated 2 years ago

Was this helpful?