give me code snippet of a go 1.19 program that does the following:
Has a unique and exclusive rest endpoint "/api/deploy" with POST
in case any other path is called with any other http method, 404 is returned
the endpoint supports a request body with json format and with this schema:
{"project" :string, "version": string, time: "string", "jobId": number, token: string}
The application should validate the call as follows:
1- the types of each field should match, other wise return 400
2- the project value should be among a predefined list of strings (loaded from a text config file) otherwise return 400
3- the token should match and env variable called API_TOKEN, otherwise return 403
If all the validations above pass, the application should do the following
1- execute the following system command, the host on which the app runs is ubuntu bash:
cd"/opt/{project}" && make VERSION="${version}" refresh
The application should be verbose and log error or success messages locally
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Below is a Go program that meets the specified requirements. This program uses the net/http package for handling HTTP requests and the encoding/json package for JSON parsing. It also uses the os/exec package to execute system commands.
go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"strings"
)
// DeployRequest represents the request body schema
type DeployRequest struct {
Project string `json:"project"`
Version string `json:"version"`
Time string `json:"time"`
JobID int `json:"jobId"`
Token string `json:"token"`
}
// LoadProjects loads the predefined list of projects from a config file
func LoadProjects(filePath string) ([]string, error) {
data, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
projects := strings.Split(strings.TrimSpace(string(data)), "\n")
return projects, nil
}
// ValidateRequest validates the request body
func ValidateRequest(req DeployRequest, projects []string, apiToken string) (bool, int, string) {
if req.Project == "" || req.Version == "" || req.Time == "" || req.JobID == 0 || req.Token == "" {
return false, 400, "Invalid request body"
}
projectFound := false
for _, project := range projects {
if project == req.Project {
projectFound = true
break
}
}
if !projectFound {
return false, 400, "Invalid project"
}
if req.Token != apiToken {
return false, 403, "Invalid token"
}
return true, 0, ""
}
// DeployHandler handles the /api/deploy endpoint
func DeployHandler(projects []string, apiToken string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.NotFound(w, r)
return
}
var req DeployRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
valid, status, message := ValidateRequest(req, projects, apiToken)
if !valid {
http.Error(w, message, status)
return
}
cmd := exec.Command("bash", "-c", fmt.Sprintf("cd /opt/%s && make VERSION=%s refresh", req.Project, req.Version))
output, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Command execution failed: %s", err)
http.Error(w, "Command execution failed", http.StatusInternalServerError)
return
}
log.Printf("Command executed successfully: %s", output)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Deployment successful")
}
}
func main() {
apiToken := os.Getenv("API_TOKEN")
if apiToken == "" {
log.Fatal("API_TOKEN environment variable is not set")
}
projects, err := LoadProjects("projects.txt")
if err != nil {
log.Fatalf("Failed to load projects: %v", err)
}
http.HandleFunc("/api/deploy", DeployHandler(projects, apiToken))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
})
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Explanation:
DeployRequest Struct: Defines the structure of the JSON request body.
LoadProjects Function: Loads the predefined list of projects from a text file.
ValidateRequest Function: Validates the request body against the predefined rules.
DeployHandler Function: Handles the /api/deploy endpoint, validates the request, and executes the system command.
main Function: Sets up the HTTP server, loads the projects, and starts the server.
Configuration:
projects.txt: A text file containing the predefined list of projects, one per line.
API_TOKEN: An environment variable containing the API token.
Running the Program:
Create a projects.txt file with the list of projects.
Set the API_TOKEN environment variable.
Run the Go program.
sh
export API_TOKEN=your_api_token
go run main.go
This program will start an HTTP server on port 8080 and handle the /api/deploy endpoint as specified.