64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
package utils
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"net/http"
|
|
|
|
"github.com/fiskerinc/cloud-services/pkg/common"
|
|
)
|
|
|
|
// LinkResult makes result with link and timestamp
|
|
func LinkResult(link string, timestamp int64) common.JSONLink {
|
|
return common.JSONLink{
|
|
Link: link,
|
|
Timestamp: timestamp,
|
|
}
|
|
}
|
|
|
|
// ErrorResult makes error result
|
|
func ErrorResult(status int, message string) common.JSONError {
|
|
return common.JSONError{
|
|
Error: http.StatusText(status),
|
|
Message: message,
|
|
}
|
|
}
|
|
|
|
// RespJSON sends back JSON response
|
|
func RespJSON(w http.ResponseWriter, status int, resp interface{}) {
|
|
js, _ := json.Marshal(resp)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
// CORS headers for local debugging
|
|
/*
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
w.Header().Set("Access-Control-Allow-Headers", "*")
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Methods", "*")
|
|
*/
|
|
|
|
w.WriteHeader(status)
|
|
w.Write(js)
|
|
}
|
|
|
|
// RespLink JSON response with download link
|
|
func RespLink(w http.ResponseWriter, link string, timestamp int64) {
|
|
resp := LinkResult(link, timestamp)
|
|
RespJSON(w, http.StatusOK, &resp)
|
|
}
|
|
|
|
// RespError JSON error response
|
|
func RespError(w http.ResponseWriter, status int, message string) {
|
|
resp := ErrorResult(status, message)
|
|
RespJSON(w, status, &resp)
|
|
}
|
|
|
|
// Forward a response
|
|
func ForwardResponse(w http.ResponseWriter, resp *http.Response) {
|
|
w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
|
|
w.WriteHeader(resp.StatusCode)
|
|
|
|
body, _ := ioutil.ReadAll(resp.Body)
|
|
w.Write(body)
|
|
}
|