Last active
May 30, 2020 13:12
-
-
Save D-sense/10d5be41411eedc2f1fd6d82e0d5f2c0 to your computer and use it in GitHub Desktop.
Ticket-Raffling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"math/rand" | |
"os" | |
"time" | |
) | |
type People struct { | |
People []Person `json:"users"` | |
} | |
type Person struct { | |
Email string `json:"email"` | |
FullName string `json:"full_name"` | |
} | |
func main() { | |
// load data from file | |
people, err := readFile("people.json") | |
if err != nil { | |
fmt.Println(err) | |
} | |
// randomise the seed | |
rand.Seed(time.Now().UnixNano()) | |
// shuffle the slice | |
rand.Shuffle(len(people.People), func(i, j int) { | |
people.People[i], people.People[j] = people.People[j], people.People[i] | |
}) | |
//randomise the winners | |
winner := rand.Int63n(int64(len(people.People)-1)) | |
fmt.Printf("Winner is: %s", people.People[winner]) | |
fmt.Println() | |
} | |
func readFile(file string) (People, error) { | |
jsonFile, err := os.Open(file) | |
if err != nil { | |
return People{}, err | |
} | |
defer jsonFile.Close() | |
byteData, err := ioutil.ReadAll(jsonFile) | |
if err != nil { | |
return People{}, err | |
} | |
var people People | |
err = json.Unmarshal(byteData, &people) | |
if err != nil { | |
return People{}, err | |
} | |
return people, nil | |
} | |
P.S (IMPORTANT): | |
The JSON file (you wuld have to get the data from the form being filled by members) should follow this format: | |
{ | |
"users": [ | |
{ | |
"email": "[email protected]", | |
"full_name": "Adeshina Hassan" | |
}, | |
{ | |
"email": "[email protected]", | |
"full_name": "Endy" | |
}, | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment