Created
April 12, 2022 09:48
-
-
Save abiiranathan/6634b438a6ddd1c86dc94f13941c95e7 to your computer and use it in GitHub Desktop.
A file server written in go
This file contains hidden or 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 ( | |
"flag" | |
"log" | |
"net/http" | |
"path/filepath" | |
) | |
var ( | |
path = flag.String("path", ".", "path to the folder to serve. Defaults to the current folder") | |
port = flag.String("port", "8080", "port to serve on. Defaults to 8080") | |
) | |
func main() { | |
flag.Parse() | |
dirname, err := filepath.Abs(*path) | |
if err != nil { | |
log.Fatalf("Could not get absolute path to directory: %s: %s", dirname, err.Error()) | |
} | |
log.Printf("Serving %s on port %s", dirname, *port) | |
err = Serve(dirname, *port) | |
if err != nil { | |
log.Fatalf("Could not serve directory: %s: %s", dirname, err.Error()) | |
} | |
} | |
func Serve(dirname string, port string) error { | |
fs := http.FileServer(http.Dir(dirname)) | |
http.Handle("/", fs) | |
return http.ListenAndServe(":"+port, nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment