Skip to content

Instantly share code, notes, and snippets.

@yomusu
Created January 8, 2015 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yomusu/1a70e6fb4195d451f1d2 to your computer and use it in GitHub Desktop.
Save yomusu/1a70e6fb4195d451f1d2 to your computer and use it in GitHub Desktop.
Simple Web Server with Go
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