Initial cloud-services repo - gateway service + pkg modules
This commit is contained in:
63
pkg/utils/json_resp.go
Normal file
63
pkg/utils/json_resp.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"fiskerinc.com/modules/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)
|
||||
}
|
||||
Reference in New Issue
Block a user