GetUserTemplateText attempts to retrieve the template text from a passed in URL or file path when inputData is more than one line. This function will attempt to load a file first, and if it fails, will try to get the data from the remote endpoint. The timeout for remote download file is 30 seconds.
(inputData string)
| 1202 | // data from the remote endpoint. |
| 1203 | // The timeout for remote download file is 30 seconds. |
| 1204 | func GetUserTemplateText(inputData string) (template string, err error) { |
| 1205 | // if the input data is more than one line, assume its a template and return that data. |
| 1206 | if strings.Contains(inputData, "\n") { |
| 1207 | return inputData, nil |
| 1208 | } |
| 1209 | |
| 1210 | // load data from file |
| 1211 | data, err := os.ReadFile(inputData) |
| 1212 | // return data if found and loaded |
| 1213 | if err == nil { |
| 1214 | return string(data), nil |
| 1215 | } |
| 1216 | |
| 1217 | // check for non "not found" errors |
| 1218 | if !os.IsNotExist(err) { |
| 1219 | return "", fmt.Errorf("failed to open file %s: %w", inputData, err) |
| 1220 | } |
| 1221 | |
| 1222 | // attempt to get data from url with timeout |
| 1223 | const downloadTimeout = 30 * time.Second |
| 1224 | ctx, cancel := context.WithTimeout(context.Background(), downloadTimeout) |
| 1225 | defer cancel() |
| 1226 | |
| 1227 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, inputData, http.NoBody) |
| 1228 | if err != nil { |
| 1229 | return "", fmt.Errorf("failed to create request GET %s: %w", inputData, err) |
| 1230 | } |
| 1231 | resp, err := http.DefaultClient.Do(req) |
| 1232 | if err != nil { |
| 1233 | return "", fmt.Errorf("failed to execute GET request data from %s: %w", inputData, err) |
| 1234 | } |
| 1235 | if resp != nil { |
| 1236 | defer func() { |
| 1237 | _ = resp.Body.Close() |
| 1238 | }() |
| 1239 | } |
| 1240 | if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 1241 | return "", fmt.Errorf("got non %d status code on GET %s", resp.StatusCode, inputData) |
| 1242 | } |
| 1243 | data, err = io.ReadAll(resp.Body) |
| 1244 | if err != nil { |
| 1245 | return "", fmt.Errorf("failed to read response body from GET %s: %w", inputData, err) |
| 1246 | } |
| 1247 | |
| 1248 | return string(data), nil |
| 1249 | } |
| 1250 | |
| 1251 | // LoadTemplates loads all of our template files into a text/template. The |
| 1252 | // path of template is relative to the templates directory. |