add go fiber example

This commit is contained in:
Mauricio Siu
2024-06-30 20:14:30 -06:00
parent c251b5957b
commit e613f0cae5
10 changed files with 183 additions and 0 deletions

21
go-fiber-simple/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Hayden L
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

20
go-fiber-simple/README.md Normal file
View File

@@ -0,0 +1,20 @@
# Go Fiber Example
This repository contains an example of Go fiber application that is deployed on Dokploy.
1. **Use Git Provider in Your Application**:
- Repository: `https://github.com/Dokploy/examples.git`
- Branch: `main`
- Build path: `/go-fiber-simple`
4. **Click on Deploy**:
- Deploy your application by clicking the deploy button.
5. **Generate a Domain**:
- Click on generate domain button.
- A new domain will be generated for you.
- You can use this domain to access your application.
If you need further assistance, join our [Discord server](https://discord.com/invite/2tBnJ3jDJc).

View File

@@ -0,0 +1,19 @@
package main
import (
"net/http"
)
func (app *application) healthcheckHandler(w http.ResponseWriter, r *http.Request) {
data := map[string]string{
"status": "ok",
"version": version,
}
// No need to add acess control origin headers. On other routes, that may be necessary
err := app.writeJSON(w, http.StatusOK, data, nil)
if err != nil {
app.logger.Error(err.Error())
http.Error(w, "server error", http.StatusInternalServerError)
}
}

View File

@@ -0,0 +1,28 @@
package main
import (
"encoding/json"
"net/http"
)
// The writeJSON() method is a generic helper for writing JSON to a response
func (app *application) writeJSON(w http.ResponseWriter, sCode int, data any, headers http.Header) error {
marshalledJson, err := json.Marshal(data)
if err != nil {
return err
}
// Valid json requires newline
marshalledJson = append(marshalledJson, '\n')
for key, value := range headers {
w.Header()[key] = value
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(sCode)
w.Write(marshalledJson)
return nil
}

View File

@@ -0,0 +1,63 @@
package main
import (
"fmt"
"log/slog"
"net/http"
"os"
"strconv"
"time"
)
const version = "0.0.1"
type config struct {
port int
}
type application struct {
config config
logger *slog.Logger
}
func main() {
var cfg config
// Try to read environment variable for port (given by railway). Otherwise use default
port := os.Getenv("PORT")
intPort, err := strconv.Atoi(port)
if err != nil {
intPort = 4000
}
// Set the port to run the API on
cfg.port = intPort
// create the logger
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
// create the application
app := &application{
config: cfg,
logger: logger,
}
// create the server
srv := &http.Server{
Addr: fmt.Sprintf(":%d", cfg.port),
Handler: app.routes(),
IdleTimeout: 45 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelError),
}
logger.Info("server started", "addr", srv.Addr)
// Start the server
err = srv.ListenAndServe()
logger.Error(err.Error())
os.Exit(1)
}

View File

@@ -0,0 +1,16 @@
package main
import (
"net/http"
"github.com/julienschmidt/httprouter"
)
func (app *application) routes() *httprouter.Router {
router := httprouter.New()
// Define the available routes
router.HandlerFunc(http.MethodGet, "/v1/healthcheck", app.healthcheckHandler)
return router
}

5
go-fiber-simple/go.mod Normal file
View File

@@ -0,0 +1,5 @@
module goapi.railway.app
go 1.21.7
require github.com/julienschmidt/httprouter v1.3.0

2
go-fiber-simple/go.sum Normal file
View File

@@ -0,0 +1,2 @@
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=

View File

@@ -0,0 +1,5 @@
[phases.build]
cmds = ['''GOOS=linux GOARCH=amd64 go build -ldflags='-s' -o=./bin/linux_amd64/api ./cmd/api''']
[start]
cmd = './bin/linux_amd64/api'