go语言入门教程-使用go开发一个图片展示网站

不说废话直接贴代码,代码有注释。

package main

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

const( UPLOAD_DIR="d:/uploads")

//这是上传图片的handler
func uploadHandler(w http.ResponseWriter, r *http.Request){
	if r.Method =="GET"{
		//将html写入到类型为http.ResponseWriter的w实例中
		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\" />"+
			"</from></html>")
		return
	}
	if r.Method =="POST"{
		//r.FormFile用来获取接受的请求的文件句柄。
		f,h,err :=r.FormFile("image")
		if err !=nil{
			http.Error(w,err.Error(),http.StatusInternalServerError)
			return
		}
		filename :=h.Filename
		fmt.Println(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)
	}
}

func viewHandler(w http.ResponseWriter,r *http.Request){
	imageId :=r.FormValue("id")
	imagePath:=UPLOAD_DIR +"/"+imageId
	w.Header().Set("Content-Tpye","image")
	//读取图片,并将图片写入到http.ResponseWriter
	http.ServeFile(w,r,imagePath)
}

func  listHandler(w http.ResponseWriter,r *http.Request){
    //遍历指定目录,他读取目录并返回排好序的文件以及子目录名
	FileInfoArr,err :=ioutil.ReadDir("d:/uploads")
	if err !=nil{
		http.Error(w,err.Error(),http.StatusInternalServerError)
		return
	}
	var listHtml string
	for _,fileInfo :=range FileInfoArr{
		imgid :=fileInfo.Name
		fmt.Println(reflect.TypeOf(imgid))
		listHtml +="<li><a href=\"/view?id="+imgid()+"\">"+imgid()+"</a></li>"
	}
	io.WriteString(w,"<html>"+listHtml+"</html>")
}

func  main(){
	//服务注册
	http.HandleFunc("/",listHandler)
	http.HandleFunc("/upload",uploadHandler)
	http.HandleFunc("/view",viewHandler)
	//创建server服务
	err :=http.ListenAndServe(":8080",nil)
	if err != nil{
		log.Fatal("ListenAndServer",err.Error())
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42730079/article/details/89535874
今日推荐