---
title: "go web"
author: "aircoder"
date: "2013-08-19T01:36:02Z"
tags: []
categories: ["Web前端"]
slug: "go-web"
draft: false
lastmod: "2013-08-19T01:36:02Z"
id: 1926862
url: "https://aircoder.iteye.com/blog/1926862"
---

package main
import (
"io"
"io/ioutil"
"log"
"os"
"net/http"
)

const (
UPLOAD_DIR = "uploads"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		io.WriteString(w, "<html><form method=\"POST\" action=\"/upload\" "+
		" enctype=\"multipart/form-data\">"+
		"Choose an image to upload: <input name=\"image\" type=\"file\" />"+
		"<input type=\"submit\" value=\"Upload\" />"+
		"</form></html>")
	return
	}

	if r.Method == "POST" {
		f, h, err := r.FormFile("image")
		if err != nil {
			http.Error(w, err.Error(),
			http.StatusInternalServerError)
			return
		}
	filename := h.Filename
	defer f.Close()
	t, err := os.Create(UPLOAD_DIR + "/" + filename)
	if err != nil {
	log.Println("create dir has error");

	http.Error(w, err.Error(),
	http.StatusInternalServerError)
	return
	}
	defer t.Close()
	if _, err := io.Copy(t, f); err != nil {
	http.Error(w, err.Error(),
	http.StatusInternalServerError)
	return
	}
	http.Redirect(w, r, "/view?id="+filename,
	http.StatusFound)
	}
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
	imageId := r.FormValue("id")
	imagePath := UPLOAD_DIR + "/" + imageId
	if exists := isExists(imagePath);!exists {
	http.NotFound(w, r)
	return
	}
	w.Header().Set("Content-Type", "image")
	http.ServeFile(w, r, imagePath)

}

func isExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
	return true
	}
	return os.IsExist(err)
}


func listHandler(w http.ResponseWriter, r *http.Request) {
	fileInfoArr, err := ioutil.ReadDir("uploads")
	if err != nil {
		http.Error(w, err.Error(),
		http.StatusInternalServerError)
	return
	}
	var listHtml string

	for _, fileInfo := range fileInfoArr {
	imgid := fileInfo.Name()
	listHtml += "<li><a href=\"/view?id="+imgid+"\">imgid</a></li>"
	}
	io.WriteString(w, "<html><ol>"+listHtml+"</ol></html>")
}


func main() {
http.HandleFunc("/", listHandler)

http.HandleFunc("/upload", uploadHandler)
http.HandleFunc("/view", viewHandler)

err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}