package main import ( "io" "net/http" "regexp" "git.1e99.eu/1e99/chitchat/server/storage" ) func StoreHandler(store storage.Store, idRegex *regexp.Regexp, maxSize int) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { id := req.PathValue("id") matches := idRegex.MatchString(id) if !matches { res.WriteHeader(http.StatusBadRequest) return } switch req.Method { case http.MethodHead: err := store.Has(id) switch { case err == storage.ErrNotExists: res.WriteHeader(http.StatusNotFound) return case err != nil: res.WriteHeader(http.StatusInternalServerError) return } res.WriteHeader(http.StatusOK) case http.MethodGet: data, err := store.Get(id) switch { case err == storage.ErrNotExists: res.WriteHeader(http.StatusNotFound) return case err != nil: res.WriteHeader(http.StatusInternalServerError) return } res.WriteHeader(http.StatusOK) res.Write(data) case http.MethodPut: data, err := io.ReadAll(req.Body) if err != nil { res.WriteHeader(http.StatusBadGateway) return } if len(data) > maxSize { res.WriteHeader(http.StatusRequestEntityTooLarge) return } err = store.Put(id, data) switch { case err != nil: res.WriteHeader(http.StatusInternalServerError) return } res.WriteHeader(http.StatusNoContent) case http.MethodDelete: err := store.Delete(id) switch { case err == storage.ErrNotExists: res.WriteHeader(http.StatusNotFound) return case err != nil: res.WriteHeader(http.StatusInternalServerError) return } res.WriteHeader(http.StatusNoContent) default: res.WriteHeader(http.StatusMethodNotAllowed) } } }