码迷,mamicode.com
首页 > 其他好文 > 详细

Go.网络篇-2

时间:2017-12-09 23:49:39      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:nan   direct   list   mit   method   inf   ##   port   response   

package main

import (
	"io/ioutil"
	"os"
	"io"
	"log"
	"net/http"
)

const (
	UPLOAD_DIR = "./upload"
)

func main(){
	http.HandleFunc("/",listHandler)
	http.HandleFunc("/upload",uploadHandler)	
	http.HandleFunc("/view",viewHandler)	
	err := http.ListenAndServe("127.0.0.1:8080",nil)
	
	if err != nil {
		log.Fatal("ListenAndServe:", err.Error())
	}	
}

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>")		
	}

	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 {
			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)
	}

	return
}

func viewHandler(w http.ResponseWriter, r *http.Request){

	id := r.FormValue("id")
	path := UPLOAD_DIR + "/" + id 

	if !hasfile(path) {
		http.NotFound(w,r)
		return
	}

	w.Header().Set("Content-Type","image")
	http.ServeFile(w,r,path)
}

func hasfile(path string) bool {

	_,err := os.Stat(path)
	if err == nil {
		return true
	}

	return os.IsExist(err)
}

func listHandler(w http.ResponseWriter, r *http.Request){
	fileInfo,err := ioutil.ReadDir("./upload")

	if err != nil {
		http.Error(w,err.Error(),http.StatusInternalServerError)
		return
	}

	var html string 
	html += "<html><ol>"
	for _,info := range fileInfo {
		id := info.Name()
		html += "<li><a href=\"view?id=" + id + "\">" + id + "</a></li>"
	}
	html += "</ol></html>"

	io.WriteString(w,html)
}

## 简单的图片管理网站

Go.网络篇-2

标签:nan   direct   list   mit   method   inf   ##   port   response   

原文地址:http://www.cnblogs.com/welanshan/p/7821611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!