Skip to content

Commit

Permalink
Add an example for hot reloading
Browse files Browse the repository at this point in the history
  • Loading branch information
unitoftime committed Oct 30, 2024
1 parent 4d75407 commit ee19890
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
39 changes: 39 additions & 0 deletions example/hot/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package main

import (
"time"

"github.com/unitoftime/flow/example/hot/plugin"
"github.com/unitoftime/flow/hot"
)

// Steps:
// 1. run rebuild.sh to build the initial plugin *.so file
// 2. Run main.go
// 3. Change something in the HelloWorld function in ./plugin/plugin.go
// 4. run rebuild.sh to rebuild the plugin *.so file. the main() function below will detect, reload the symbol and run it once

// Note: You need to run rebuild.sh to build the plugin *.so file

func main() {
// You can directly import the plugin package to use it immediately
plugin.HelloWorld()

// This will search the provided directory for .so files and try to load them
p := hot.NewPlugin("./plugin/build/lib/")

for {
time.Sleep(1 * time.Second)
if !p.Check() { continue } // When this becomes true, it means a new plugin is loaded

// With our new plugin, we can lookup our symbol `HelloWorld`
sym, err := p.Lookup("HelloWorld")
if err != nil {
panic(err)
}
hello := sym.(func())

// Then we can call our Looked up symbol
hello()
}
}
16 changes: 16 additions & 0 deletions example/hot/plugin/plugin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package plugin

import (
"fmt"
)

// Note: Here you can change one function to the other while main.go is running.

func HelloWorld() {
fmt.Println("Hello World")
}


// func HelloWorld() {
// fmt.Println("Goodbye Moon")
// }
30 changes: 30 additions & 0 deletions example/hot/rebuild.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/bin/bash

set -e

PLUGIN_DIR=./plugin/
BUILD_DIR=./plugin/build/
BUILD_PKG_DIR=${BUILD_DIR}/pkg/
BUILD_LIB_DIR=${BUILD_DIR}/lib/

mkdir -p ${BUILD_PKG_DIR}
mkdir -p ${BUILD_LIB_DIR}

rm -f ${BUILD_LIB_DIR}/*.so

VAR=$RANDOM

# Note: I usually leave this uncommented, but I didnt want to accidentally wipe someones computer
#rm -rf ${BUILD_PKG_DIR}/*
mkdir -p ${BUILD_PKG_DIR}/tmp$VAR

cp ${PLUGIN_DIR}/*.go ${BUILD_PKG_DIR}/tmp$VAR

cd ${BUILD_PKG_DIR}/tmp$VAR
sed -i 's/package plugin/package main/g' *.go
cd -

go build -gcflags=all=-d=checkptr=0 -buildmode=plugin -o ${BUILD_LIB_DIR}/tmp$VAR.so ${BUILD_PKG_DIR}/tmp$VAR

echo "Finished Rebuild" $VAR
tree

0 comments on commit ee19890

Please sign in to comment.