43 lines
899 B
Go
43 lines
899 B
Go
package grabhttp
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io/fs"
|
|
"net/http"
|
|
)
|
|
|
|
type errorStruct struct {
|
|
Status string `json:"status"`
|
|
Error string `json:"error"`
|
|
}
|
|
|
|
func StaticHandler(f fs.FS) http.Handler {
|
|
return http.FileServer(http.FS(f))
|
|
}
|
|
|
|
func WriteJSON(i interface{}, status int, w http.ResponseWriter, r *http.Request) {
|
|
b, err := json.Marshal(i)
|
|
if err != nil {
|
|
ErrorJSON(err, http.StatusInternalServerError, w, r)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
w.Write(b)
|
|
w.Write([]byte("\n"))
|
|
}
|
|
|
|
func WriteHTML(b []byte, status int, w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/html")
|
|
w.WriteHeader(status)
|
|
w.Write(b)
|
|
w.Write([]byte("\n"))
|
|
}
|
|
|
|
func ErrorJSON(err error, status int, w http.ResponseWriter, r *http.Request) {
|
|
WriteJSON(errorStruct{
|
|
Status: "error",
|
|
Error: err.Error(),
|
|
}, status, w, r)
|
|
}
|