Skip to content

Commit 417e888

Browse files
committed
initial commit
0 parents  commit 417e888

File tree

5 files changed

+92
-0
lines changed

5 files changed

+92
-0
lines changed

Diff for: go.mod

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
module github.com/surajmn1/rest-api
2+
3+
go 1.18
4+
5+
require github.com/go-chi/chi v1.5.4

Diff for: go.sum

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
github.com/go-chi/chi v1.5.4 h1:QHdzF2szwjqVV4wmByUnTcsbIg7UGaQ0tPF2t5GcAIs=
2+
github.com/go-chi/chi v1.5.4/go.mod h1:uaf8YgoFazUOkPBG7fxPftUylNumIev9awIWOENIuEg=

Diff for: main.go

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package main
2+
3+
import (
4+
"log"
5+
"net/http"
6+
"os"
7+
"plugin"
8+
9+
"github.com/go-chi/chi"
10+
)
11+
12+
type PluginAPI interface {
13+
RegisterRoutes(router chi.Router)
14+
}
15+
16+
func main() {
17+
// Create a new Chi router
18+
router := chi.NewRouter()
19+
20+
// Load the plugin
21+
p, err := plugin.Open("./plugins/myplugin.so")
22+
if err != nil {
23+
log.Fatal(err)
24+
}
25+
26+
// Lookup the plugin's symbol
27+
symbol, err := p.Lookup("Plugin")
28+
if err != nil {
29+
log.Fatal(err)
30+
}
31+
32+
// Assert that the symbol implements PluginAPI interface
33+
pluginAPI, ok := symbol.(PluginAPI)
34+
if !ok {
35+
log.Fatal("Invalid plugin")
36+
}
37+
38+
// Register routes from the plugin
39+
pluginAPI.RegisterRoutes(router)
40+
41+
// Start the server
42+
port := os.Getenv("PORT")
43+
if port == "" {
44+
port = "8080"
45+
}
46+
47+
log.Printf("Server listening on port %s", port)
48+
log.Fatal(http.ListenAndServe(":"+port, router))
49+
}

Diff for: plugins/myplugin.go

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"net/http"
7+
"strconv"
8+
9+
"github.com/go-chi/chi"
10+
)
11+
12+
type MyPlugin struct{}
13+
14+
func (p *MyPlugin) RegisterRoutes(router chi.Router) {
15+
router.Get("/", func(w http.ResponseWriter, r *http.Request) {
16+
w.Write([]byte("Hello from the plugin using Chi!"))
17+
})
18+
19+
router.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
20+
id := chi.URLParam(r, "id")
21+
userID, err := strconv.Atoi(id)
22+
if err != nil {
23+
http.Error(w, "Invalid user ID", http.StatusBadRequest)
24+
return
25+
}
26+
27+
// Perform operations with the user ID
28+
// ...
29+
30+
w.Write([]byte("User ID: " + fmt.Sprint(userID)))
31+
})
32+
33+
log.Println("Plugin routes registered")
34+
}
35+
36+
var Plugin MyPlugin

Diff for: plugins/myplugin.so

7.27 MB
Binary file not shown.

0 commit comments

Comments
 (0)