Skip to content

Commit

Permalink
Add gitlab server mock to serve json testdata
Browse files Browse the repository at this point in the history
  • Loading branch information
cluttrdev committed May 16, 2024
1 parent 72b378e commit 294b529
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions test/mock/gitlab/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package gitlab_mock

import (
"encoding/json"
"fmt"
"net/http"
"path"
"strings"
)

type FileHandler struct {
Root http.FileSystem
}

func (f *FileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
upath := r.URL.Path
if !strings.HasPrefix(upath, "/") {
upath = "/" + upath
r.URL.Path = upath
}
serveFile(w, r, f.Root, path.Clean(upath))
}

func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name string) {
f, err := fs.Open(name + ".json")
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
fmt.Fprintln(w, fmt.Sprintf(`{"message": "%s"}`, err))
return
}
defer f.Close()

var data interface{}
if err := json.NewDecoder(f).Decode(&data); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, fmt.Sprintf(`{"message": "%s"}`, err))
return
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)
}

0 comments on commit 294b529

Please sign in to comment.