How to Build a Simple Web Server in Golang to Serve Static HTML Pages

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Quick little demonstration of how to server static HTML pages using Golang. This example assumes both your index.html and webserver.go files are in the same directory:

// REFERENCE (Simple Static Web Server in Go): https://stackoverflow.com/questions/26559557/how-do-you-serve-a-static-html-file-using-a-go-web-server
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("./")))
http.ListenAndServe(":3000", nil)
}
view raw webserver.go hosted with ❤ by GitHub
<!DOCTYPE html>
<html>
<body>
<h1>My Super Sweet Homepage</h1>
<button onclick="doStuff()">CLICK HERE</button>
<script>
function doStuff() {
alert("do stuff!");
}
</script>
</body>
</html>
view raw index.html hosted with ❤ by GitHub

Need routes to other pages? Check out this example I have posted on GitHub: SimpleGolangWebServer

Need to serve up JSON instead of HTML? Check out this example by Tom Hudson: simple-json-api.go

 

topherPedersen