finish logger-service

This commit is contained in:
vinchent 2024-08-29 13:24:36 +02:00
parent 46a36d0ab9
commit 523f7f8280
6 changed files with 172 additions and 3 deletions

View File

@ -0,0 +1,36 @@
package main
import (
"logger/data"
"net/http"
)
type JSONPayload struct {
Name string `json:"name"`
Data string `json:"data"`
}
func (app *Config) WriteLog(w http.ResponseWriter, r *http.Request) {
// read json into var
var requestPayload JSONPayload
app.readJSON(w, r, &requestPayload)
// insert data
event := data.LogEntry{
Name: requestPayload.Name,
Data: requestPayload.Data,
}
err := app.Models.LogEntry.Insert(event)
if err != nil {
app.errorJSON(w, err)
return
}
resp := jsonResponse{
Error: false,
Message: "logged",
}
app.writeJSON(w, http.StatusAccepted, resp)
}

View File

@ -0,0 +1,75 @@
package main
import (
"encoding/json"
"errors"
"io"
"net/http"
)
type jsonResponse struct {
Error bool `json:"error"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
func (app *Config) readJSON(w http.ResponseWriter, r *http.Request, data any) error {
maxBytes := 1048576 // one megabyte
r.Body = http.MaxBytesReader(w, r.Body, int64(maxBytes))
dec := json.NewDecoder(r.Body)
err := dec.Decode(data)
if err != nil {
return err
}
err = dec.Decode(&struct{}{})
if err != io.EOF {
return errors.New("body must have only a single JSON value")
}
return nil
}
func (app *Config) writeJSON(
w http.ResponseWriter,
status int,
data any,
headers ...http.Header,
) error {
out, err := json.Marshal(data)
if err != nil {
return err
}
if len(headers) > 0 {
for key, value := range headers[0] {
w.Header()[key] = value
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, err = w.Write(out)
if err != nil {
return err
}
return nil
}
func (app *Config) errorJSON(w http.ResponseWriter, err error, status ...int) error {
statusCode := http.StatusBadRequest
if len(status) > 0 {
statusCode = status[0]
}
var payload jsonResponse
payload.Error = true
payload.Message = err.Error()
return app.writeJSON(w, statusCode, payload)
}

View File

@ -2,7 +2,10 @@ package main
import ( import (
"context" "context"
"fmt"
"log" "log"
"logger/data"
"net/http"
"time" "time"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo"
@ -18,7 +21,9 @@ const (
var client *mongo.Client var client *mongo.Client
type Config struct{} type Config struct {
Models data.Models
}
func main() { func main() {
// connect to mongo // connect to mongo
@ -37,7 +42,23 @@ func main() {
} }
}() }()
client = &mongo.Client{} app := Config{
Models: data.New(client),
}
// start web server
go app.serve()
}
func (app *Config) serve() {
srv := &http.Server{
Addr: fmt.Sprintf(":%s", webPort),
Handler: app.routes(),
}
err := srv.ListenAndServe()
if err != nil {
log.Panic(err)
}
} }
func connectToMongo() (*mongo.Client, error) { func connectToMongo() (*mongo.Client, error) {

View File

@ -0,0 +1,29 @@
package main
import (
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
)
func (app *Config) routes() http.Handler {
mux := chi.NewRouter()
// specify who is allowed to connect
mux.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://*", "http://*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
}))
mux.Use(middleware.Heartbeat("/ping"))
mux.Post("/log", app.WriteLog)
return mux
}

View File

@ -2,7 +2,11 @@ module logger
go 1.22.5 go 1.22.5
require go.mongodb.org/mongo-driver v1.16.1 require (
github.com/go-chi/chi/v5 v5.1.0
github.com/go-chi/cors v1.2.1
go.mongodb.org/mongo-driver v1.16.1
)
require ( require (
github.com/golang/snappy v0.0.4 // indirect github.com/golang/snappy v0.0.4 // indirect

View File

@ -1,5 +1,9 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4=
github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=