7

A static file server in Go

 3 years ago
source link: https://www.devroom.io/2012/10/04/a-static-file-server-in-go/?utm_campaign=Feed%3A+ariejan+%28ariejan%7Cdevroom.io%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

A static file server in Go

Posted: 2012-10-04 - Last updated: 2019-06-05

Tagged go

If you don’t know Go, you should really look into it. Today I was trying to figure out how to write a simple (and fast) static file server in Go.

As it turns out, this is very easy to do. Go contains (in the net/http package) a nice FileServer type that can server files from the directory you point it to.

Here’s a sweet and short example:

package main

import (
    "net/http"
    "log"
)

func main() {
    err := http.ListenAndServe(":4242", http.FileServer(http.Dir("public")))
    if err != nil {
        log.Printf("Error running web server for static assets: %v", err)
    }
}

By itself this is not very useful, but you can easily integrate this into any other http server you create, maybe for handling dynamic requests or doing web sockets.

My site is free of ads and trackers. I record privacy-respecting usage statistics with Fathom.

Was this post helpful to you? Why not ☕ Buy me a coffee

Copyright © 1999-2020 Ariejan de Vroom <[email protected]>

Live now; make now always the most precious time. Now will never come again.
    – Jean-Luc Picard


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK