fuzzyworld

quantum-inspiration / files / qrng.go

qrng.go

Blame: the commit that last changed each line · file · history

e58f6fff 2023-09-06 Pavel Safronov1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "os"
9)
10
11const (
12 qrngApiKeyEnvVar = "ANU_QRNG_KEY"
13)
14
15type apiResponse struct {
16 Success bool `json:"success"`
17 Type string `json:"type"`
18 Length string `json:"length"`
19 Data []uint8 `json:"data"`
20}
21
22func GetRandomNumbers(count int) ([]uint8, error) {
23 resp, err := getRandomFromQrng(count)
24 if err != nil {
25 return nil, err
26 }
27 return resp.Data, nil
28}
29
30func getRandomFromQrng(count int) (apiResponse, error) {
31 API_URL := "https://api.quantumnumbers.anu.edu.au"
32 API_KEY, keyFound := os.LookupEnv(qrngApiKeyEnvVar)
33 if !keyFound {
34 fmt.Printf("Error: API key not found in environment variable %s", qrngApiKeyEnvVar)
35 return apiResponse{}, fmt.Errorf("API key not found")
36 }
37
38 client := &http.Client{}
39 req, err := http.NewRequest("GET", fmt.Sprintf("%s?length=%d&type=uint8", API_URL, count), nil)
40 if err != nil {
41 fmt.Println("Error creating request:", err)
42 return apiResponse{}, err
43 }
44 req.Header.Set("x-api-key", API_KEY)
45
46 resp, err := client.Do(req)
47 if err != nil {
48 fmt.Println("Error executing request:", err)
49 return apiResponse{}, err
50 }
51 defer resp.Body.Close()
52
53 body, err := io.ReadAll(resp.Body)
54 if err != nil {
55 fmt.Println("Error reading response:", err)
56 return apiResponse{}, err
57 }
58
59 var response apiResponse
60 err = json.Unmarshal(body, &response)
61 if err != nil {
62 fmt.Println("Error unmarshalling JSON:", err)
63 return apiResponse{}, err
64 }
65
66 return response, nil
67}