Serving static file using Golang

There will be times when you would need to serve contents of a single non-HTML file on a web server. The following is a simple and quick way.

If you want to serve the file payload.txt using Golang, save the following code to a file main.go.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {
    http.HandleFunc("/", ServeFile)
    http.ListenAndServe(":3000", nil)
}

func ServeFile(w http.ResponseWriter, r *http.Request) {
    data, err := ioutil.ReadFile("payload.txt")
    if err != nil {
        fmt.Println("File reading error", err)
        return
    }
    fmt.Fprintf(w, string(data))
}

Execute the code using go run main.go.

Remember: If you want to serve a different file or on a different port, change the code.