Skip to content

Commit 1572699

Browse files
committed
Initialize serve app functionality
1 parent b3d5de4 commit 1572699

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

app.go

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package pulse
2+
3+
import (
4+
"fmt"
5+
"github.com/common-nighthawk/go-figure"
6+
"github.com/valyala/fasthttp"
7+
"net"
8+
)
9+
10+
type (
11+
Pulse struct {
12+
config *Config
13+
server *fasthttp.Server
14+
router *Router
15+
}
16+
17+
Config struct {
18+
// AppName is the name of the app
19+
AppName string `json:"app_name"`
20+
21+
// Network is the network to use
22+
Network string `json:"network"`
23+
}
24+
)
25+
26+
const (
27+
// DefaultAppName is the default app name
28+
DefaultAppName = "Pulse"
29+
30+
// DefaultNetwork is the default network
31+
DefaultNetwork = "tcp"
32+
)
33+
34+
func New(config ...Config) *Pulse {
35+
app := &Pulse{
36+
config: &Config{},
37+
server: &fasthttp.Server{},
38+
}
39+
40+
if len(config) > 0 {
41+
app.config = &config[0]
42+
}
43+
44+
if app.config.AppName == "" {
45+
app.config.AppName = DefaultAppName
46+
}
47+
48+
if app.config.Network == "" {
49+
app.config.Network = DefaultNetwork
50+
}
51+
52+
return app
53+
}
54+
55+
func (f *Pulse) Run(address string) error {
56+
handler := RouterHandler(f.router)
57+
f.server.Handler = handler
58+
59+
// setup listener
60+
listener, err := net.Listen(f.config.Network, address)
61+
if err != nil {
62+
return fmt.Errorf("failed to listen: %v", err)
63+
}
64+
65+
// print startup message
66+
fmt.Println(f.startupMessage(listener.Addr().String()))
67+
68+
return f.server.Serve(listener)
69+
}
70+
71+
func (f *Pulse) startupMessage(addr string) string {
72+
myFigure := figure.NewFigure("PULSE", "", true)
73+
myFigure.Print()
74+
75+
var textOne = "=> Server started on <%s>" + "\n"
76+
var textTwo = "=> App Name: %s" + "\n"
77+
var textThree = "=> Press CTRL+C to stop" + "\n"
78+
79+
return fmt.Sprintf(textOne, addr) + fmt.Sprintf(textTwo, f.config.AppName) + fmt.Sprintf(textThree)
80+
}

app_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package pulse
2+
3+
import (
4+
"testing"
5+
)
6+
7+
var app *Pulse
8+
9+
func init() {
10+
app = New(Config{
11+
AppName: "Test App",
12+
})
13+
}
14+
15+
func TestPulse_Run(t *testing.T) {
16+
err := app.Run("127.0.0.1:8082")
17+
if err != nil {
18+
return
19+
}
20+
}

0 commit comments

Comments
 (0)