contentserver/server/webserver.go
Stefan Martinov 0e44ca809d
Deterministic Log Messaging & Refactoring (#26)
* feat: remove apex log from dependency list & upgrade deps

* chore: remove commented out code

* chore: remove high cardinality metric labels

* chore: add stack trace to failed repo requests

* chore: remove logging and return error instead

* chore: change log messages for contentserver

* chore: add constistent messages to content update routine

* feat: add runtime id, and multierr validator

* chore: rename history

* chore: golint fixes

* chore: simplify (golinter)

* chore: update go version

* chore: remove unused dependencies for new go

* chore: move content update to else statement

* chore: remove go-spew

* chore: bump go version to 1.18

* chore: remove alpine dep for updated deps

* chore: update go version and improve build

* chore: minor reformatting
2022-05-26 15:09:11 +02:00

60 lines
1.3 KiB
Go

package server
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"go.uber.org/zap"
. "github.com/foomo/contentserver/logger"
"github.com/foomo/contentserver/repo"
)
type webServer struct {
path string
r *repo.Repo
}
// NewWebServer returns a shiny new web server
func NewWebServer(path string, r *repo.Repo) http.Handler {
return &webServer{
path: path,
r: r,
}
}
func (s *webServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
Log.Error("Panic in handle connection", zap.String("error", fmt.Sprint(r)))
}
}()
if r.Body == nil {
http.Error(w, "no body", http.StatusBadRequest)
return
}
jsonBytes, readErr := ioutil.ReadAll(r.Body)
if readErr != nil {
http.Error(w, "failed to read incoming request", http.StatusBadRequest)
return
}
h := Handler(strings.TrimPrefix(r.URL.Path, s.path+"/"))
if h == HandlerGetRepo {
s.r.WriteRepoBytes(w)
w.Header().Set("Content-Type", "application/json")
return
}
reply, errReply := handleRequest(s.r, h, jsonBytes, "webserver")
if errReply != nil {
http.Error(w, errReply.Error(), http.StatusInternalServerError)
return
}
_, err := w.Write(reply)
if err != nil {
Log.Error("failed to write webServer reply", zap.Error(err))
}
}