routes

package
v0.0.0-...-8626fa4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 14, 2021 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package routes has the routes supported by the api with proper versioning done Suppose a route is /list, it belonged to v2 and current version is v2. Then route will be available as /list and /v2/list. If the current version is not v2 then the api will be exposed only as /list. For using routes with a server invoke the InitRoutes function.

Index

Examples

Constants

This section is empty.

Variables

View Source
var AppContextKey = appCtxKey{/* contains filtered or unexported fields */}

AppContextKey is the key with which the application is saved in the request context

View Source
var AppContextRequestChan = make(chan AppContextRequest)

AppContextRequestChan channel through which the app context routine takes requests from

Functions

func AddRoutes

func AddRoutes(r ...Route)

AddRoutes adds the routes to the routes variable

Example
package main

import (
	"context"
	"net/http"

	"github.com/cuttle-ai/websockets/routes"
)

func main() {
	//using add routes to create routes to handle requests
	routes.AddRoutes(routes.Route{
		Version: "v1",
		HandlerFunc: func(ctx context.Context, res http.ResponseWriter, req *http.Request) {
			// rest of the implementation
		},
		Pattern: "/hi",
	})
}
Output:

func AppContext

func AppContext(in chan AppContextRequest)

AppContext is the app context go routine running to

func CleanUpCheck

func CleanUpCheck(in chan AppContextRequest)

CleanUpCheck is the cleanup check to be used as a go routine which periodically sends cleanup requests to the AppContext go routines

func InitRoutes

func InitRoutes(s *http.ServeMux)

InitRoutes initializes the routes in the application

Example
package main

import (
	"context"
	"net/http"
	"os"
	"os/signal"

	"github.com/cuttle-ai/websockets/routes"

	"github.com/cuttle-ai/websockets/config"
	"github.com/cuttle-ai/websockets/log"
)

func main() {
	//creating a new server mux
	m := http.NewServeMux()

	//created the default server
	s := &http.Server{
		Addr:           ":" + config.Port,
		Handler:        m,
		ReadTimeout:    config.RequestRTimeout,
		WriteTimeout:   config.ResponseWTimeout,
		MaxHeaderBytes: 1 << 20,
	}

	//inited the routes
	routes.InitRoutes(m)

	//listen and serve to the server
	go func() {
		log.Info("Starting the User Subscription server at :" + config.Port)
		log.Error(s.ListenAndServe())
	}()

	//listening for syscalls
	var gracefulStop = make(chan os.Signal, 1)
	signal.Notify(gracefulStop, os.Interrupt)
	sig := <-gracefulStop

	//gracefulling exiting when request comes in
	log.Info("Received the interrupt", sig)
	log.Info("Shutting down the server")
	err := s.Shutdown(context.Background())
	if err != nil {
		log.Error("Couldn't end the server gracefully")
	}
}
Output:

func SendNotification

func SendNotification(ctx context.Context, res http.ResponseWriter, req *http.Request)

SendNotification will send notification to connected websockets client of the user

func SendRequest

func SendRequest(ch chan AppContextRequest, req AppContextRequest)

SendRequest is to send request to the channel. When this function used as go routines the blocking quenes can be solved

func WebSockets

func WebSockets(ctx context.Context, res http.ResponseWriter, req *http.Request)

WebSockets is the websockets connection handler

Types

type AppContextRequest

type AppContextRequest struct {
	//AppContext is the appcontext being requested
	AppContext *config.AppContext
	//Type is the type of request
	Type RequestType
	//Out is the ouput channel for get requests
	Out chan AppContextRequest
	//Exhausted flag states whether the app context exhausted
	Exhausted bool
	//Session is  the user session
	Session authConfig.Session
	//ID of the appcontext for the fetch requests
	ID int
	//Ws is the websockets connection
	Ws socketio.Conn
	//WsConns has the list of web socket connections for the user
	WsConns []socketio.Conn
}

AppContextRequest is the request to get, return or try clean up app contexts

type HandlerFunc

type HandlerFunc func(context.Context, http.ResponseWriter, *http.Request)

HandlerFunc is the Handler func with the context

Example
package main

import (
	"context"
	"net/http"

	"github.com/cuttle-ai/websockets/routes"
	"github.com/cuttle-ai/websockets/routes/response"
)

func main() {
	//Example for creating a simple handler function
	f := func(ctx context.Context, res http.ResponseWriter, req *http.Request) {
		response.Write(res, response.Message{Message: "hi"})
	}
	routes.AddRoutes(routes.Route{
		Version:     "v1",
		HandlerFunc: f,
		Pattern:     "/hi",
	})
}
Output:

Example (Context)
package main

import (
	"context"
	"net/http"
	"time"

	"github.com/cuttle-ai/websockets/routes"
	"github.com/cuttle-ai/websockets/routes/response"

	"github.com/cuttle-ai/websockets/log"
)

func main() {
	//Example for creating a simple handler function with context
	f := func(ctx context.Context, res http.ResponseWriter, req *http.Request) {

		//suppose there is a chan through a concurrent action happens
		tm := make(chan int)
		defer func() {
			//don't for get to close the channel
			close(tm)
		}()

		//kick start the concurrent action
		go func(ch chan int) {
			time.Sleep(1 * time.Second)
			ch <- 1
		}(tm)

		//wait for the results
		select {
		case <-tm:
			//we get the response
			response.Write(res, response.Message{Message: "hi"})
		case <-ctx.Done():
			//if timeout wins. Handle it gracefully.
			//No need to write the response
			log.Error("Timed out")
		}
	}
	routes.AddRoutes(routes.Route{
		Version:     "v1",
		HandlerFunc: f,
		Pattern:     "/hi",
	})
}
Output:

type RequestType

type RequestType int

RequestType is the type of the AppContext Request

const (
	//Get is to get an app context
	Get RequestType = 0
	//Finished is to return an app context
	Finished RequestType = 1
	//CleanUp is to clean up the non-authenticated app context
	CleanUp RequestType = 2
	//Fetch will return the context in the system by the context id
	Fetch RequestType = 3
	//FetchWs will fetch the websocket connections
	FetchWs RequestType = 4
)

type Route

type Route struct {
	//Version is the version of the route
	Version string
	//Pattern is the url pattern of the route
	Pattern string
	//HandlerFunc is the handler func of the route
	HandlerFunc HandlerFunc
}

Route is a route with explicit versions

func (Route) Exec

func (r Route) Exec(ctx context.Context, res http.ResponseWriter, req *http.Request)

Exec will execute the handler func. By default it will set response content type as as json. It will also cancel the context at the end. So no need of explicitly invoking the same in the handler funcs

func (Route) Register

func (r Route) Register(s *http.ServeMux)

Register registers the route with the default http handler func

func (Route) ServeHTTP

func (r Route) ServeHTTP(res http.ResponseWriter, req *http.Request)

ServeHTTP implements HandlerFunc of http package. It makes use of the context of request

Directories

Path Synopsis
Package response handles utilities for writing error and normal responses to the response writer
Package response handles utilities for writing error and normal responses to the response writer

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL