Randomly select an emoji/emoticon from a slice in a html template

I would like to randomly select from a slice, but print it in the html/template.
Here’s what I have so far:
package main

import (
	"fmt"
	"math/rand"
	"time"
)

type map struct {
	emojiSlice	[]string
}

func main() {
	rand.Seed(time.Now().Unix())
	Map: map{
	emojiSlice := []string{"πŸ˜€", "😟", "πŸ€“", "πŸ™ƒ", "πŸ˜†"}
}
	n := rand.Int() % len(emojiSlice)
}

But then what, how to I print it on my local server? Like this?{{.emojiSlice[randomEmoji]}}

Nothing’s working :frowning:

Thanks

Your program looks to not be valid Go, in a way that makes me think you should do some exercises with the language. :slight_smile: There is a nice learning resource at https://tour.golang.org/welcome/1 - did you check it out?

Hey @lennybeadle, I just wrote an example for you to help you do what you want.

I’ve annotated the whole process to help you understand what it’s doing, however, if you are somewhat unfamiliar with Go, I would first go through the Go tour in the link that Jakob posted above.

Edit: This page is also a good small introduction to building a website with Go and also shows how to use templates: https://golang.org/doc/articles/wiki/

package main

import (
	"html/template"
	"log"
	"math/rand"
	"net/http"
	"time"
)

// Create the index page's source code.
var indexSrc = `{{.}}`

// Create a new template from the indexSrc.
//
// Can use ParseFiles instead of Parse to render a file instead of a string.
var tmpls = template.Must(template.New("tmpl").Parse(indexSrc))

// Create a slice of emojis.
var emojiSlice = []string{"πŸ˜€", "😟", "πŸ€“", "πŸ™ƒ", "πŸ˜†"}

func main() {
	// Seed the random number generator.
	rand.Seed(time.Now().UnixNano())

	// Handle the / page on the server.
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Execute the tmpl template, passing it data, in this case a
        // random emojiSlice string, then also checking for errors.
		if err := tmpls.Execute(w, emojiSlice[rand.Int()%len(emojiSlice)]); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})

	// Start the server on http://localhost:9000
	log.Fatal(http.ListenAndServe(":9000", nil))
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.