Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Listen method #117

Merged
merged 7 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 45 additions & 6 deletions route.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"net"
"net/http"
"net/http/httptest"
"time"
Expand Down Expand Up @@ -88,6 +89,44 @@ func (r *Route) GlobalMiddleware(middlewares ...httpcontract.Middleware) {
r.setMiddlewares(middlewares)
}

func (r *Route) Listen(l net.Listener) error {
r.outputRoutes()
color.Green().Println(termlink.Link("[HTTP] Listening and serving HTTP on", "http://"+l.Addr().String()))

r.server = &http.Server{
Addr: l.Addr().String(),
Handler: http.AllowQuerySemicolons(r.instance),
MaxHeaderBytes: r.config.GetInt("http.drivers.gin.header_limit", 4096) << 10,
}

if err := r.server.Serve(l); !errors.Is(err, http.ErrServerClosed) {
return err
}

return nil
}

func (r *Route) ListenTLS(l net.Listener) error {
return r.ListenTLSWithCert(l, r.config.GetString("http.tls.ssl.cert"), r.config.GetString("http.tls.ssl.key"))
}

func (r *Route) ListenTLSWithCert(l net.Listener, certFile, keyFile string) error {
r.outputRoutes()
color.Green().Println(termlink.Link("[HTTPS] Listening and serving HTTPS on", "https://"+l.Addr().String()))

r.tlsServer = &http.Server{
Addr: l.Addr().String(),
Handler: http.AllowQuerySemicolons(r.instance),
MaxHeaderBytes: r.config.GetInt("http.drivers.gin.header_limit", 4096) << 10,
}

if err := r.tlsServer.ServeTLS(l, certFile, keyFile); !errors.Is(err, http.ErrServerClosed) {
return err
}

return nil
}

func (r *Route) Run(host ...string) error {
if len(host) == 0 {
defaultHost := r.config.GetString("http.host")
Expand All @@ -108,11 +147,11 @@ func (r *Route) Run(host ...string) error {
MaxHeaderBytes: r.config.GetInt("http.drivers.gin.header_limit", 4096) << 10,
}

if err := r.server.ListenAndServe(); errors.Is(err, http.ErrServerClosed) {
return nil
} else {
if err := r.server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
return err
}

return nil
}

func (r *Route) RunTLS(host ...string) error {
Expand Down Expand Up @@ -149,11 +188,11 @@ func (r *Route) RunTLSWithCert(host, certFile, keyFile string) error {
MaxHeaderBytes: r.config.GetInt("http.drivers.gin.header_limit", 4096) << 10,
}

if err := r.tlsServer.ListenAndServeTLS(certFile, keyFile); errors.Is(err, http.ErrServerClosed) {
return nil
} else {
if err := r.tlsServer.ListenAndServeTLS(certFile, keyFile); !errors.Is(err, http.ErrServerClosed) {
return err
}

return nil
}

func (r *Route) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
Expand Down
191 changes: 191 additions & 0 deletions route_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"mime/multipart"
"net"
"net/http"
"net/http/httptest"
"sync"
Expand Down Expand Up @@ -43,6 +44,196 @@ func TestFallback(t *testing.T) {
mockConfig.AssertExpectations(t)
}

func TestListen(t *testing.T) {
var (
err error
mockConfig *configmocks.Config
route *Route
)

tests := []struct {
name string
setup func(host string, port string) error
host string
port string
expectError error
}{
{
name: "success listen",
setup: func(host string, port string) error {
mockConfig.EXPECT().GetBool("app.debug").Return(true).Once()
mockConfig.EXPECT().GetInt("http.drivers.gin.header_limit", 4096).Return(4096).Once()
go func() {
l, err := net.Listen("tcp", host)
assert.Nil(t, err)
assert.Nil(t, route.Listen(l))
}()
time.Sleep(1 * time.Second)

return errors.New("error")
},
host: "127.0.0.1:3100",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
mockConfig = &configmocks.Config{}
mockConfig.EXPECT().GetBool("app.debug").Return(true).Once()
mockConfig.EXPECT().GetInt("http.drivers.gin.body_limit", 4096).Return(4096).Once()

route, err = NewRoute(mockConfig, nil)
assert.Nil(t, err)
route.Get("/", func(ctx contractshttp.Context) contractshttp.Response {
return ctx.Response().Json(200, contractshttp.Json{
"Hello": "Goravel",
})
})
if err := test.setup(test.host, test.port); err == nil {
time.Sleep(1 * time.Second)
hostUrl := "http://" + test.host
if test.port != "" {
hostUrl = hostUrl + ":" + test.port
}
resp, err := http.Get(hostUrl)
assert.Nil(t, err)
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
assert.Equal(t, "{\"Hello\":\"Goravel\"}", string(body))
}
mockConfig.AssertExpectations(t)
})
}
}

func TestListenTLS(t *testing.T) {
var (
err error
mockConfig *configmocks.Config
route *Route
)

tests := []struct {
name string
setup func(host string) error
host string
expectError error
}{
{
name: "success listen",
setup: func(host string) error {
mockConfig.EXPECT().GetInt("http.drivers.gin.header_limit", 4096).Return(4096).Once()
mockConfig.EXPECT().GetString("http.tls.ssl.cert").Return("test_ca.crt").Once()
mockConfig.EXPECT().GetString("http.tls.ssl.key").Return("test_ca.key").Once()
mockConfig.EXPECT().GetBool("app.debug").Return(true).Once()

go func() {
l, err := net.Listen("tcp", host)
assert.Nil(t, err)
assert.Nil(t, route.ListenTLS(l))
}()

return nil
},
host: "127.0.0.1:3101",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
mockConfig = configmocks.NewConfig(t)
mockConfig.EXPECT().GetBool("app.debug").Return(true).Once()
mockConfig.EXPECT().GetInt("http.drivers.gin.body_limit", 4096).Return(4096).Once()

route, err = NewRoute(mockConfig, nil)
assert.Nil(t, err)
route.Get("/", func(ctx contractshttp.Context) contractshttp.Response {
return ctx.Response().Json(200, contractshttp.Json{
"Hello": "Goravel",
})
})
if err := test.setup(test.host); err == nil {
time.Sleep(1 * time.Second)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://" + test.host)
assert.Nil(t, err)
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
assert.Equal(t, "{\"Hello\":\"Goravel\"}", string(body))
}
})
}
}

func TestListenTLSWithCert(t *testing.T) {
var (
err error
mockConfig *configmocks.Config
route *Route
)

tests := []struct {
name string
setup func(host string) error
host string
expectError error
}{
{
name: "success listen",
setup: func(host string) error {
mockConfig.EXPECT().GetInt("http.drivers.gin.header_limit", 4096).Return(4096).Once()
mockConfig.EXPECT().GetBool("app.debug").Return(true).Once()

go func() {
l, err := net.Listen("tcp", host)
assert.Nil(t, err)
assert.Nil(t, route.ListenTLSWithCert(l, "test_ca.crt", "test_ca.key"))
}()

return nil
},
host: "127.0.0.1:3101",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
mockConfig = configmocks.NewConfig(t)
mockConfig.EXPECT().GetBool("app.debug").Return(true).Once()
mockConfig.EXPECT().GetInt("http.drivers.gin.body_limit", 4096).Return(4096).Once()

route, err = NewRoute(mockConfig, nil)
assert.Nil(t, err)
route.Get("/", func(ctx contractshttp.Context) contractshttp.Response {
return ctx.Response().Json(200, contractshttp.Json{
"Hello": "Goravel",
})
})
if err := test.setup(test.host); err == nil {
time.Sleep(1 * time.Second)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://" + test.host)
assert.Nil(t, err)
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
assert.Equal(t, "{\"Hello\":\"Goravel\"}", string(body))
}
})
}
}

func TestRun(t *testing.T) {
var (
err error
Expand Down
Loading