Go image網站開發
知識
07-22
從目錄上看,代碼的內容非常簡單。picture.go包含了所有的交互代碼,list.html和upload.html則包含了使用到的模板文件,而uploads目錄則保存了所有上傳的image文件。
1.picture.go代碼內容:
- package main
- import "io"
- import "log"
- import "os"
- import "net/http"
- import "html/template"
- import "io/ioutil"
- const (
- UPLOAD_DIR = "./uploads"
- )
- func uploadHandler (w http.ResponseWriter, r * http.Request) {
- if r.Method == "GET" {
- t, _ := template.ParseFiles("upload.html")
- t.Execute(w, nil)
- }else {
- f, h, _ := r.FormFile("image")
- filename := h.Filename
- defer f.Close()
- t, _ := os.Create(UPLOAD_DIR + "/" + filename)
- defer t.Close()
- _, err := io.Copy(t, f)
- if err != nil {
- 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-Type", "image")
- http.ServeFile(w, r, imagePath)
- }
- func listHandler(w http.ResponseWriter, r* http.Request) {
- fileInfoArr, _ := ioutil.ReadDir(UPLOAD_DIR)
- locals := make(map[string] interface{})
- images := []string{}
- for _, fileInfo := range fileInfoArr {
- images = append(images, fileInfo.Name())
- }
- locals["images"] = images
- t, _ := template.ParseFiles("list.html")
- t.Execute(w, locals)
- }
- func main() {
- http.HandleFunc("/upload", uploadHandler)
- http.HandleFunc("/view", viewHandler)
- http.HandleFunc("/", listHandler)
- err := http.ListenAndServe(":9090", nil)
- if err != nil {
- log.Fatal("ListenAndServe: ", err.Error())
- }
- }
其實這個網站主要就3個網頁。一個是顯示所有圖片的索引,一個是圖片顯示,另外一個就是圖片上傳頁面。
2.upload.html
- <!doctype html>
- <html>
- <head>
- <meta charset = "utf-8">
- <tilte> Uploader </title>
- </head>
- <body>
- <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>
- </body>
- </html>
3.list.html
- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- <title> List </title>
- </head>
- <body>
- <ol>
- {{range $.images}}
- <li><a href="/view?id={{.|urlquery}}"> {{.|html}} </a> </li>
- {{end}}
- </ol>
- </body>
- </html>


※git在push的時候出現許可權的問題
※dubbo源碼分析之遠程調用概述
TAG:程序員小新人學習 |