Simplify Go Endpoints + Add Tests (#120)
This MR represents a major refactor of the Go codebase, as well as introducing tests for the handlers. The MR also introduces an endpoint to shutdown or restart the Go server, which may be useful for clients who want to refresh the state of the plugin after checking out branches. Finally, this MR adds a contributing document for users who want to make feature changes.
This commit is contained in:
committed by
GitHub
parent
10b0b596ae
commit
93fe3e8bd6
59
cmd/shutdown.go
Normal file
59
cmd/shutdown.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type killer struct{}
|
||||
|
||||
func (k killer) Signal() {}
|
||||
func (k killer) String() string {
|
||||
return "0"
|
||||
}
|
||||
|
||||
type ShutdownRequest struct {
|
||||
Restart bool `json:"restart"`
|
||||
}
|
||||
|
||||
/* shutdownHandler will shutdown the HTTP server and exit the process by signaling to the shutdown channel */
|
||||
func (a *api) shutdownHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
handleError(w, errors.New("Invalid request type"), "That request type is not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
handleError(w, err, "Could not read request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var shutdownRequest ShutdownRequest
|
||||
err = json.Unmarshal(body, &shutdownRequest)
|
||||
if err != nil {
|
||||
handleError(w, err, "Could not unmarshal data from request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var text = "Shut down server"
|
||||
if shutdownRequest.Restart {
|
||||
text = "Restarted server"
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
response := SuccessResponse{
|
||||
Message: text,
|
||||
Status: http.StatusOK,
|
||||
}
|
||||
|
||||
err = json.NewEncoder(w).Encode(response)
|
||||
if err != nil {
|
||||
handleError(w, err, "Could not encode response", http.StatusInternalServerError)
|
||||
} else {
|
||||
a.sigCh <- killer{}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user