Created
January 8, 2015 09:09
-
-
Save yomusu/1a70e6fb4195d451f1d2 to your computer and use it in GitHub Desktop.
Simple Web Server with 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 ( | |
"bufio" | |
"io" | |
"log" | |
"net/http" | |
"os" | |
) | |
func main() { | |
http.HandleFunc("/web/", staticFileHandler) | |
http.ListenAndServe(":8085", nil) | |
} | |
// staticファイルを転送するハンドラ | |
func staticFileHandler(w http.ResponseWriter, r *http.Request) { | |
fname := "c:/webroot" + r.RequestURI | |
file, ferr := os.OpenFile(fname, os.O_RDONLY, 0600) | |
defer file.Close() | |
if ferr != nil { | |
log.Println("not found file:" + fname) | |
w.WriteHeader(http.StatusNotFound) | |
return | |
} | |
reader := bufio.NewReader(file) | |
buf := make([]byte, 1024, 1024) | |
LOOP: | |
for { | |
n, err := reader.Read(buf) | |
switch { | |
case err == nil: | |
w.Write(buf[:n]) | |
case err == io.EOF: | |
log.Println("static file=" + fname) | |
break LOOP | |
case err != nil: | |
log.Printf("file error occured. err=%s\n", err) | |
break LOOP | |
} | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment