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

Added Static File Handler #674

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
807faf9
Added Static File Handler
KedarisettiSreeVamsi Jun 2, 2024
b449cb4
changes to filepath and gofr file
KedarisettiSreeVamsi Jun 2, 2024
7c136e4
Added documentation and removed the example with small edits
KedarisettiSreeVamsi Jun 3, 2024
749f34a
Merge branch 'development' into staticFileHandler
Umang01-hash Jun 4, 2024
25c7cc2
Made changes to Doc file and removed config line
KedarisettiSreeVamsi Jun 4, 2024
fb04cc6
Merge branch 'staticFileHandler' of https://github.com/KedarisettiSre…
KedarisettiSreeVamsi Jun 4, 2024
6e5a7be
typo fix
KedarisettiSreeVamsi Jun 4, 2024
380aada
Merge branch 'development' into staticFileHandler
Umang01-hash Jun 6, 2024
fbbb2c6
Added test for static handling
KedarisettiSreeVamsi Jun 6, 2024
f4ec872
Merge branch 'staticFileHandler' of https://github.com/KedarisettiSre…
KedarisettiSreeVamsi Jun 6, 2024
761e814
minor changes
KedarisettiSreeVamsi Jun 6, 2024
b7605e6
Changes
KedarisettiSreeVamsi Jun 6, 2024
7105889
Merge branch 'development' into staticFileHandler
Umang01-hash Jun 7, 2024
b7f7cbf
made changes
KedarisettiSreeVamsi Jun 7, 2024
04e00b9
Merge branch 'staticFileHandler' of https://github.com/KedarisettiSre…
KedarisettiSreeVamsi Jun 7, 2024
a2b06f9
code quality checks
KedarisettiSreeVamsi Jun 7, 2024
1d34bcc
rework code quality checks
KedarisettiSreeVamsi Jun 7, 2024
0115e03
code quality clearance
KedarisettiSreeVamsi Jun 7, 2024
070f02a
Merge branch 'development' into staticFileHandler
Umang01-hash Jun 10, 2024
aa5288f
resolve review comments
Umang01-hash Jun 10, 2024
fc6a232
Merge branch 'development' of github.com:gofr-dev/gofr into staticFil…
Umang01-hash Jun 10, 2024
7d97572
Merge branch 'development' into staticFileHandler
aryanmehrotra Jun 10, 2024
4c52caf
refactor tests
aryanmehrotra Jun 10, 2024
e75d5b5
fix docs, tests, logs
srijan-27 Jun 11, 2024
9d8ff4b
Merge branch 'development' into staticFileHandler
srijan-27 Jun 11, 2024
cec9b74
Merge branch 'development' into staticFileHandler
aryanmehrotra Jun 12, 2024
ca1122b
add config to static file handling
KedarisettiSreeVamsi Jun 12, 2024
58ccbc0
update of test
KedarisettiSreeVamsi Jun 12, 2024
105543f
fixing for index file handling
KedarisettiSreeVamsi Jun 12, 2024
438bfa3
updates to documentation and code quality fixes
KedarisettiSreeVamsi Jun 12, 2024
0a5fb78
changes and fixes
KedarisettiSreeVamsi Jun 13, 2024
824b1bc
small typo in documentation
KedarisettiSreeVamsi Jun 13, 2024
8d8af7a
checking for public endpoint
KedarisettiSreeVamsi Jun 13, 2024
492dbab
fix linters
aryanmehrotra Jun 17, 2024
d4ee4f0
Merge branch 'development' into staticFileHandler
vipul-rawat Jun 19, 2024
8f0dd2c
changes as requested
KedarisettiSreeVamsi Jun 24, 2024
5aa6105
conflict check
KedarisettiSreeVamsi Jun 24, 2024
cd82021
resolve merge conflicts
aryanmehrotra Jun 25, 2024
e6bbd59
fix reveiw comments
aryanmehrotra Jun 25, 2024
9b9a6ba
fix issues in rendering file
aryanmehrotra Jun 25, 2024
39597ee
remove unwanted exported methods
aryanmehrotra Jun 25, 2024
d92b6f1
refactor implementatins
aryanmehrotra Jun 25, 2024
b25c4b6
unexport static file config function
aryanmehrotra Jun 25, 2024
886e3ef
remove unwanted files
aryanmehrotra Jun 25, 2024
aa6d989
Merge branch 'development' into staticFileHandler
aryanmehrotra Jun 26, 2024
8054eec
add test for invalid file and custom route
aryanmehrotra Jun 26, 2024
f725bc4
update invalid filepath test
aryanmehrotra Jun 26, 2024
d8be25c
add test and remove unwanted code
aryanmehrotra Jun 26, 2024
a45db0f
resolve linters
aryanmehrotra Jun 26, 2024
683952f
fix test
aryanmehrotra Jun 26, 2024
f2d186e
keep inline
aryanmehrotra Jun 26, 2024
bee9a39
Merge branch 'development' into staticFileHandler
aryanmehrotra Jun 26, 2024
fc4ffe3
fix reveiw comments
aryanmehrotra Jun 26, 2024
ec4be3f
Merge branch 'development' into staticFileHandler
aryanmehrotra Jun 26, 2024
c30629e
Merge branch 'development' into staticFileHandler
srijan-27 Jun 26, 2024
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
2 changes: 2 additions & 0 deletions examples/serving-static-files/configs/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
APP_NAME="serving-static-files"
HTTP_PORT=9000
10 changes: 10 additions & 0 deletions examples/serving-static-files/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package main

import (
"gofr.dev/pkg/gofr"
)

func main() {
app := gofr.New()
app.Run()
}
87 changes: 87 additions & 0 deletions examples/serving-static-files/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package main

import (
"bytes"
"io"
"net/http"
"strconv"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestFileServer(t *testing.T) {
const host = "http://localhost:9000"
go main()
time.Sleep(time.Second * 3)
tests := []struct {
desc string
method string
path string
body []byte
statusCode int
expectedBody string
expectedBodyLength int
expectedResponseHeaderType string
}{
{
desc: "check static files",
method: http.MethodGet,
path: "/public/",
statusCode: http.StatusOK,
expectedBody: "<pre>\n<a href=\"hardhat.jpeg\">hardhat.jpeg</a>\n<a href=\"industrial.jpeg\">industrial.jpeg</a>\n<a href=\"skross.png\">skross.png</a>\n</pre>\n",
},
{
desc: "check file content hardhat.jpeg",
method: http.MethodGet,
path: "/public/hardhat.jpeg",
statusCode: http.StatusOK,
expectedBodyLength: 14779,
expectedResponseHeaderType: "image/jpeg",
},
{
desc: "check file content industrial.jpeg",
method: http.MethodGet,
path: "/public/industrial.jpeg",
statusCode: http.StatusOK,
expectedBodyLength: 11228,
expectedResponseHeaderType: "image/jpeg",
},
{
desc: "check file content skross.png",
method: http.MethodGet,
path: "/public/skross.png",
statusCode: http.StatusOK,
expectedBodyLength: 76239,
expectedResponseHeaderType: "image/png",
},
{
desc: "check public endpoint",
method: http.MethodGet,
path: "/public",
statusCode: http.StatusNotFound,
},
}

for it, tc := range tests {
request, _ := http.NewRequest(tc.method, host+tc.path, bytes.NewBuffer(tc.body))
request.Header.Set("Content-Type", "application/json")
client := http.Client{}
resp, err := client.Do(request)
bodyBytes, _ := io.ReadAll(resp.Body)
body := string(bodyBytes)
assert.Nil(t, err, "TEST[%d], Failed.\n%s", it, tc.desc)
assert.Equal(t, tc.statusCode, resp.StatusCode, "TEST[%d], Failed with Status Body.\n%s", it, tc.desc)
if tc.expectedBody != "" {
assert.Equal(t, tc.expectedBody, body, "TEST [%d], Failed with Expected Body. \n%s", it, tc.desc)
}
if tc.expectedBodyLength != 0 {
contentLength, _ := strconv.Atoi(resp.Header.Get("Content-Length"))
assert.Equal(t, tc.expectedBodyLength, contentLength, "TEST [%d], Failed at Content-Length.\n %s", it, tc.desc)
}
if tc.expectedResponseHeaderType != "" {
assert.Equal(t, tc.expectedResponseHeaderType, resp.Header.Get("Content-Type"), "TEST [%d], Failed at Expected Content-Type.\n%s", it, tc.desc)
}
}
}
Binary file added examples/serving-static-files/public/hardhat.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/serving-static-files/public/skross.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
46 changes: 45 additions & 1 deletion pkg/gofr/gofr.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -76,7 +77,7 @@ func New() *App {
app.metricServer = newMetricServer(port)

// HTTP Server
port, err = strconv.Atoi(app.Config.Get("HTTP_PORT"))
port, err = strconv.Atoi(app.Config.GetOrDefault("HTTP_PORT", "6333"))
if err != nil || port <= 0 {
port = defaultHTTPPort
}
Expand All @@ -93,9 +94,52 @@ func New() *App {

app.subscriptionManager = newSubscriptionManager(app.container)

// static fileserver
currentWd, _ := os.Getwd()
checkDirectory := fmt.Sprintf("%s%spublic", currentWd, getFilePathSplitter())

if _, err := os.Stat(checkDirectory); !os.IsNotExist(err) {
Umang01-hash marked this conversation as resolved.
Show resolved Hide resolved
app.AddStaticFiles("public", checkDirectory)
srijan-27 marked this conversation as resolved.
Show resolved Hide resolved
}

return app
}

func getFilePathSplitter() string {
fileSplitter := ""

switch runtime.GOOS {
case "windows":
fileSplitter = "\\"
case "linux":
case "darwin":
case "android":
case "ios":
fileSplitter = "/"
}
return fileSplitter
}

func (a *App) AddStaticFiles(endpoint, filePath string) {
a.httpRegistered = true
dupFilePath := ""
fileSplitter := getFilePathSplitter()
if filePath[:2] == "./" {
dupFilePath, _ = os.Getwd()
dupFilePath += fileSplitter + filePath + fileSplitter
KedarisettiSreeVamsi marked this conversation as resolved.
Show resolved Hide resolved
} else {
dupFilePath = filePath
KedarisettiSreeVamsi marked this conversation as resolved.
Show resolved Hide resolved
}
if endpoint[0] != '/' {
KedarisettiSreeVamsi marked this conversation as resolved.
Show resolved Hide resolved
endpoint = "/" + endpoint
KedarisettiSreeVamsi marked this conversation as resolved.
Show resolved Hide resolved
}
if _, err := os.Stat(dupFilePath); err == nil {
KedarisettiSreeVamsi marked this conversation as resolved.
Show resolved Hide resolved
a.httpServer.router.AddStaticFiles(endpoint, dupFilePath)
} else {
a.container.Logger.Errorf("Couldn't register %s static endpoint", endpoint)
}
}

// NewCMD creates a command-line application.
func NewCMD() *App {
app := &App{}
Expand Down
5 changes: 5 additions & 0 deletions pkg/gofr/http/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ func (rou *Router) Add(method, pattern string, handler http.Handler) {
rou.Router.NewRoute().Methods(method).Path(pattern).Handler(h)
}

func (rou *Router) AddStaticFiles(endpoint, directory string) {
fileServer := http.FileServer(http.Dir(directory))
rou.Router.NewRoute().PathPrefix(endpoint + "/").Handler(http.StripPrefix(endpoint, fileServer))
}

// UseMiddleware registers middlewares to the router.
func (rou *Router) UseMiddleware(mws ...Middleware) {
middlewares := make([]mux.MiddlewareFunc, 0, len(mws))
Expand Down