🌱🏠🧑‍💻 command line greenhouse client application: an interface to the greenhouse daemon https://greenhouse.server.garden/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

81 lines
2.0 KiB

package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
"strings"
)
func register(args []string) {
if len(args) == 0 {
fmt.Print(`
Error: an api token is required.
`)
displayHelpAndExit("register")
return
}
apiToken := args[0]
serverName := strings.Join(args[1:], " ")
if serverName == "" {
hostname, err := os.Hostname()
if err != nil {
fmt.Printf(`
Error: server name was not provided, and greenhouse wasn't able to figure out what your hostname is: %s
`, err)
os.Exit(1)
return
}
serverName = hostname
} else if !regexp.MustCompile("[a-zA-Z0-9_-]+").MatchString(serverName) {
fmt.Printf(`
Error: server name '%s' must only contain letters, numbers, dashes, and underscores. (matching [a-zA-Z0-9_-]+)
`, serverName)
displayHelpAndExit("register")
return
}
if !regexp.MustCompile("[a-zA-Z0-9]+").MatchString(apiToken) {
fmt.Printf(`
Error: invalid API token '%s'. Valid api tokens will only contain letters and numbers. (Base58-encoded, matching [a-zA-Z0-9]+)
`, apiToken)
displayHelpAndExit("register")
return
}
registerURL := fmt.Sprintf("%s/register/?serverName=%s", baseURL, serverName)
registerRequest, err := http.NewRequest("POST", registerURL, nil)
if err != nil {
fmt.Printf("\nUnexpected error creating POST request for %s: %s\n\n", registerURL, err)
os.Exit(1)
return
}
registerRequest.Header.Add("Authorization", fmt.Sprintf("Bearer %s", apiToken))
response, err := httpClient.Do(registerRequest)
if err != nil {
fmt.Printf("\nCouldn't reach greenhouse daemon at %s: %s\n\n", baseURL, err)
os.Exit(1)
return
}
if response.StatusCode != 200 {
responseBytes, err := ioutil.ReadAll(response.Body)
responseString := "http read error, failed to read response from greenhouse"
if err == nil {
responseString = string(responseBytes)
}
fmt.Printf("\nPOST %s returned HTTP %d:\n%s\n\n", registerURL, response.StatusCode, responseString)
os.Exit(1)
return
}
fmt.Printf("\nSuccess! This computer has been registered as a server. Server name: %s\n\n", serverName)
}