heartbeat

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2018 License: GPL-2.0 Imports: 17 Imported by: 1

README

heartbeat

Implement a simple hearbeat detect with HTTP protocol with secret.

For old version which use UDP protocol. see tag 1.0

Install

go get -v github.com/codeskyblue/heartbeat

Usage

Server and Client should have the same secret.

Server Example:

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/codeskyblue/heartbeat"
)

func main() {
	hbs := heartbeat.NewServer("my-secret", 15*time.Second) // secret: my-secret, timeout: 15s
	hbs.OnConnect = func(identifier string, r *http.Request) {
		fmt.Println(identifier, "is online")
	}
	hbs.OnDisconnect = func(identifier string) {
		fmt.Println(identifier, "is offline")
	}
	http.Handle("/heartbeat", hbs)
	http.ListenAndServe(":7000", nil)
}

Client Example:

package main

import (
	"time"

	"github.com/codeskyblue/heartbeat"
)

func main() {
	client := &heartbeat.Client{
		ServerAddr: "http://localhost:7000/heartbeat", // replace to your server addr
		Secret:     "my-secret",                       // must be save with server secret
		Identifier: "client-unique-name",
	}
	cancel := client.Beat(5 * time.Second)
	defer cancel() // cancel heartbeat
	// Do something else
	time.Sleep(10 * time.Second)
}

Protocol

  1. client get timestamp from server
  2. client send identifier, timestamp and hmac hash to server every interval
  3. server send back the new timestamp to client on each request

LICENSE

GNU 2.0

Documentation

Overview

Protocols between client and server

Client (HTTP Request) ->

Query: identifier (uniq string)
Query: timestamp (seconds since January 1, 1970 UTC.)
Query: hashmac

Server response ->

Body: {timestamp} {hashmac}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	Secret     string
	Identifier string
	ServerAddr string
	OnConnect  func()
	OnError    func(error)
}

func (*Client) Beat

func (c *Client) Beat(interval time.Duration) (cancel context.CancelFunc)

Beat send identifier and hmac hash to server every interval

type Server

type Server struct {
	OnConnect    func(identifier string, req *http.Request)
	OnReconnect  func(identifier string, req *http.Request)
	OnDisconnect func(identifier string)
	// contains filtered or unexported fields
}

func NewServer

func NewServer(secret string, timeout time.Duration) *Server

NewServer accept secret, Client must have the same secret, so they can work together.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Session

type Session struct {
	// contains filtered or unexported fields
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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