30 lines
968 B
Markdown
30 lines
968 B
Markdown
---
|
|
title: "A static file server in Go"
|
|
kind: article
|
|
slug: a-static-file-server-in-go
|
|
created_at: 2012-10-04
|
|
tags:
|
|
- 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:
|
|
|
|
:::go
|
|
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. |