DEV Community

petercour
petercour

Posted on

Go Serve static files

#go

You may know the Go programming language, sometimes called Golang.

Golang is often used for network related programs. You can easily serve static files with Golang.

First import 3 modules:

import (
    "fmt"
    "log"
    "net/http"
)

The "net/http" module will give us webserver functionality. Need the "log" module for logging errors. Ok

Then create a handle function to map url requests to files served

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, r.URL.Path[1:])
    })

Total program:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, r.URL.Path[1:])
    })

    log.Fatal(http.ListenAndServe(":8082", nil))
}

More on Golang:

Top comments (0)