Refactor api.go to use abstracted sendResponse and sendError - Also fix most go doc complaints

This commit is contained in:
Praneeth Bodduluri 2015-10-06 23:46:31 +05:30 committed by Pablo Carranza Vélez
parent fd012c35b4
commit 96d4aebb76
4 changed files with 44 additions and 43 deletions

View File

@ -24,6 +24,7 @@ type APIResponse struct {
Error string Error string
} }
//PurgeBody struct for the ApplicationId interfact
type PurgeBody struct { type PurgeBody struct {
ApplicationId interface{} ApplicationId interface{}
} }
@ -43,14 +44,14 @@ func jsonResponse(writer http.ResponseWriter, response interface{}, status int)
writer.Write(jsonBody) writer.Write(jsonBody)
} }
func parseJsonBody(destination interface{}, request *http.Request) error { func parseJSONBody(destination interface{}, request *http.Request) error {
decoder := json.NewDecoder(request.Body) decoder := json.NewDecoder(request.Body)
return decoder.Decode(&destination) return decoder.Decode(&destination)
} }
func parsePurgeBody(request *http.Request) (appId string, err error) { func parsePurgeBody(request *http.Request) (appId string, err error) {
var body PurgeBody var body PurgeBody
if err = parseJsonBody(&body, request); err != nil { if err = parseJSONBody(&body, request); err != nil {
return return
} }
switch v := body.ApplicationId.(type) { switch v := body.ApplicationId.(type) {
@ -72,13 +73,20 @@ func responseSender(writer http.ResponseWriter) func(interface{}, string, int) {
} }
} }
func PurgeHandler(writer http.ResponseWriter, request *http.Request) { func responseSenders(writer http.ResponseWriter) (sendResponse func(interface{}, string, int), sendError func(error)) {
log.Println("Purging /data") sendResponse = func(data interface{}, errorMsg string, statusCode int) {
jsonResponse(writer, APIResponse{data, errorMsg}, statusCode)
sendResponse := responseSender(writer) }
sendError := func(err error) { sendError = func(err error) {
sendResponse("Error", err.Error(), http.StatusInternalServerError) sendResponse("Error", err.Error(), http.StatusInternalServerError)
} }
return
}
// PurgeHandler Purges the data of the appID's application in the /data partition
func PurgeHandler(writer http.ResponseWriter, request *http.Request) {
log.Println("Purging /data")
sendResponse, sendError := responseSenders(writer)
sendBadRequest := func(errorMsg string) { sendBadRequest := func(errorMsg string) {
sendResponse("Error", errorMsg, http.StatusBadRequest) sendResponse("Error", errorMsg, http.StatusBadRequest)
} }
@ -109,25 +117,25 @@ func inASecond(theFunc func()) {
theFunc() theFunc()
} }
//RebootHandler Reboots the device using Systemd
func RebootHandler(writer http.ResponseWriter, request *http.Request) { func RebootHandler(writer http.ResponseWriter, request *http.Request) {
log.Println("Rebooting") log.Println("Rebooting")
sendResponse, _ := responseSenders(writer)
sendResponse := responseSender(writer)
sendResponse("OK", "", http.StatusAccepted) sendResponse("OK", "", http.StatusAccepted)
go inASecond(func() { systemd.Logind.Reboot(false) }) go inASecond(func() { systemd.Logind.Reboot(false) })
} }
//ShutdownHandler Shuts down the device using Systemd
func ShutdownHandler(writer http.ResponseWriter, request *http.Request) { func ShutdownHandler(writer http.ResponseWriter, request *http.Request) {
log.Println("Shutting down") log.Println("Shutting down")
sendResponse := responseSender(writer) sendResponse, _ := responseSenders(writer)
sendResponse("OK", "", http.StatusAccepted) sendResponse("OK", "", http.StatusAccepted)
go inASecond(func() { systemd.Logind.PowerOff(false) }) go inASecond(func() { systemd.Logind.PowerOff(false) })
} }
// This function returns all active IPs of the interfaces that arent docker/rce and loopback // This function returns all active IPs of the interfaces that arent docker/rce and loopback
func ipAddress() (ipAddresses []string, err error) { func ipAddress() (ipAddresses []string, err error) {
ifaces, err := net.Interfaces() ifaces, err := net.Interfaces()
if err != nil { if err != nil {
return ipAddresses, err return ipAddresses, err
@ -165,13 +173,9 @@ func ipAddress() (ipAddresses []string, err error) {
//IPAddressHandler is used to reply back with an array of the IPaddress used by the system. //IPAddressHandler is used to reply back with an array of the IPaddress used by the system.
func IPAddressHandler(writer http.ResponseWriter, request *http.Request) { func IPAddressHandler(writer http.ResponseWriter, request *http.Request) {
sendResponse := responseSender(writer) sendResponse, sendError := responseSenders(writer)
sendError := func(err string) {
sendResponse("Error", err, http.StatusInternalServerError)
}
if ipAddr, err := ipAddress(); err != nil { if ipAddr, err := ipAddress(); err != nil {
sendError("Invalid request") sendError(err)
} else { } else {
payload := make(map[string][]string) payload := make(map[string][]string)
payload["IPAddresses"] = ipAddr payload["IPAddresses"] = ipAddr
@ -181,28 +185,24 @@ func IPAddressHandler(writer http.ResponseWriter, request *http.Request) {
//VPNControl is used to control VPN service status with dbus //VPNControl is used to control VPN service status with dbus
func VPNControl(writer http.ResponseWriter, request *http.Request) { func VPNControl(writer http.ResponseWriter, request *http.Request) {
sendResponse, sendError := responseSenders(writer)
var body VPNBody var body VPNBody
if err := parseJsonBody(&body, request); err != nil { if err := parseJSONBody(&body, request); err != nil {
log.Println(err.Error()) log.Println(err)
responseSender(writer)("Error", err.Error(), http.StatusBadRequest) sendResponse("Error", err.Error(), http.StatusBadRequest)
return return
} }
action := systemd.Dbus.StopUnit
actionDescr := "VPN Disable"
if body.Enable { if body.Enable {
_, err := systemd.Dbus.StartUnit("openvpn-resin.service", "fail", nil) action = systemd.Dbus.StartUnit
if err != nil { actionDescr = "VPN Enable"
log.Println(err.Error())
responseSender(writer)("Error", err.Error(), http.StatusInternalServerError)
return
}
log.Println("VPN Enabled")
} else {
_, err := systemd.Dbus.StopUnit("openvpn-resin.service", "fail", nil)
if err != nil {
log.Println(err.Error())
responseSender(writer)("Error", err.Error(), http.StatusInternalServerError)
return
}
log.Println("VPN Disabled")
} }
responseSender(writer)("OK", "", http.StatusAccepted) if _, err := action("openvpn-resin.service", "fail", nil); err != nil {
log.Printf("%s: %s\n", actionDescr, err)
sendError(err)
return
}
log.Printf("%sd\n", actionDescr)
sendResponse("OK", "", http.StatusAccepted)
} }

View File

@ -17,9 +17,9 @@ var (
func init() { func init() {
var err error var err error
if Logind, err = login1.New(); err != nil { if Logind, err = login1.New(); err != nil {
log.Fatal("Failed to connect to host system bus") log.Fatalf("Failed to connect to host system bus: %s", err)
} }
if Dbus, err = dbus.New(); err != nil { if Dbus, err = dbus.New(); err != nil {
log.Fatal("Failed to connect to host DBUS ") log.Fatalf("Failed to connect to host DBUS: %s", err)
} }
} }

View File

@ -27,6 +27,8 @@ publish = do ->
# Redefine original function # Redefine original function
publish = (message) -> publish = (message) ->
# Disable sending logs for bandwidth control
return if disableLogs
if _.isString(message) if _.isString(message)
message = { message } message = { message }
@ -35,9 +37,7 @@ publish = do ->
# Stop pubnub logging loads of "Missing Message" errors, as they are quite distracting # Stop pubnub logging loads of "Missing Message" errors, as they are quite distracting
message: ' ' message: ' '
# Disable sending logs for bandwidth control pubnub.publish({ channel, message })
if not disableLogs
pubnub.publish({ channel, message })
# Replay queue now that we have initialised the publish function # Replay queue now that we have initialised the publish function
publish(args...) for args in publishQueue publish(args...) for args in publishQueue

View File

@ -131,8 +131,9 @@ exports.extendEnvVars = (env, uuid) ->
# Callback function to enable/disable tcp pings # Callback function to enable/disable tcp pings
exports.connectivityCheck = (val) -> exports.connectivityCheck = (val) ->
disableCheck(val == 'false') bool = val is 'false'
console.log('Connectivity check enabled: ' + val) disableCheck(bool)
console.log("Connectivity check enabled: #{not bool}")
# Callback function to enable/disable logs # Callback function to enable/disable logs
exports.resinLogControl = (val) -> exports.resinLogControl = (val) ->