Created
March 19, 2015 10:34
-
-
Save raugustinus/f638d783c42c6e49a04e to your computer and use it in GitHub Desktop.
simple http serve util to serve a single static file on a port
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os" | |
"fmt" | |
"net/http" | |
"io/ioutil" | |
) | |
func handler(w http.ResponseWriter, req *http.Request, path string) { | |
data, err := ioutil.ReadFile(path) | |
check(err) | |
w.Header().Set("Content-Type", "text/html") | |
fmt.Fprintf(w, "%s", data) | |
} | |
func check(e error) { | |
if e != nil { | |
fmt.Printf("error: %s", e) | |
os.Exit(2) | |
} | |
} | |
func main() { | |
port := os.Args[1] | |
file := os.Args[2] | |
if _, err := os.Stat(file); os.IsNotExist(err) { | |
fmt.Printf("no such file or directory: %s\n", file) | |
os.Exit(1) | |
} | |
fmt.Printf("Serving %s on http://localhost:%s\n", file, port) | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
handler(w, r, file) | |
}) | |
http.ListenAndServe(":"+port, nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
while learning go I needed a simple way to serve a static file over http. Instead of running a webserver like apache or nginx with configuration etc. I just wanted something the easiest solution to host a single file on a specified port.