Go 1.16 embed
in this tutorial i will show you the new go 1.16 new file embed function, i will use this to serve a static website, make sure you have Go v1.16 install. on mac i recommend you to use Homebrew.
Go module init
first, create a folder, i call it goweb(you can call it what ever you want). Inside this folder run the command go mod init github.com/jason-shen/goweb
(you can change the front part to your github address).
Setup the embed assets
We need to import the newly available Go package call embed, then we need to add //go:embed assets/*
, as this points embed to to our assets folder, then we do the same for the file location of the html folder like this //go:embed www/index.html.
note: the //go:embed assets/ is not a comment, its the syntaxt embed requires
|
|
Let wire all this up in the main function
Now we start coding the main function, firstly we import all the require packages you see below, then we write the fs (file system) and the http server part, then we will put this on port 8080 for testing purpose, the fmt.print is to notify the user that the program does work and who them how to exit the program.
|
|
Create the html file and the asset folder
Now we are all set on the Go side of things, next we need to create the html file and the assets folder, for this example i am just gonna create a very simple index.html, and just going to have one image in the assets folder, and use it inside the index.html.
create a folder call www then create a new index.html
|
|
finally just use any image as you want or you can head over to my github and grab the image i used
Extra touch
Now if you run go run main.go
then head to https://localhost:8080
then you should see the webpage shows up, but we want to open the web automaticlly, how do we do that?
lets add an auto open function into our main function as below
|
|
here is the final code
|
|
Final step
now it all should be up and running, now we can build this project into a bin and move it to another location without the index.html and the assets fold.
without any dealt it should work, now you can distribe the single bin that has the html files embed, that makes life alot easier. until then thank you for reading.