DEV Community

petercour
petercour

Posted on

1

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:

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more