beta.blog

Go: How to write a WebServer for static files

by on Feb.10, 2019, under Programming

Go is an open source programming language that makes it easy to build simple, reliable, and efficient software. One may write a piece of code and cross-compile it for various other systems and architectures.

The following example code creates a webserver for static content using the Go programming language:

package main

import (
  "net/http"
  "fmt"
)

func main() {
  fmt.Printf("Any file from public directory will be served via http://localhost:40000/\n")

  http.Handle("/", http.FileServer(http.Dir("public")))

  if err := http.ListenAndServe(":40000", nil); err != nil {
    panic(err)
  }
}

Create the a directory named public and put a test file in it:

go-static-file-server-public-directory-structure

We may run the code with:

go run server.go

And access the test file via http://localhost:40000/incident.png after doing so.

After developing and testing the application, one may build a native binary for the operating system via:

go build

It’s also possible to cross-compile for different platforms (for instance macOS, Windows, Linux):

env GOOS=darwin GOARCH=amd64 go build
env GOOS=windows GOARCH=amd64 go build
env GOOS=linux GOARCH=amd64 go build

The cross-compiling commands above will produce 64-bit executables. If you need to create 32-bit executables (x86) instead, replace amd64 with 386. Or with arm, if you desire to compile for ARM instead.

:

Leave a Reply

*

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!