當前位置:
首頁 > 知識 > Go image網站開發

Go image網站開發

從目錄上看,代碼的內容非常簡單。picture.go包含了所有的交互代碼,list.html和upload.html則包含了使用到的模板文件,而uploads目錄則保存了所有上傳的image文件。

1.picture.go代碼內容:

  1. package main
  2. import "io"
  3. import "log"
  4. import "os"
  5. import "net/http"
  6. import "html/template"
  7. import "io/ioutil"
  8. const (
  9. UPLOAD_DIR = "./uploads"
  10. )
  11. func uploadHandler (w http.ResponseWriter, r * http.Request) {
  12. if r.Method == "GET" {
  13. t, _ := template.ParseFiles("upload.html")
  14. t.Execute(w, nil)
  15. }else {
  16. f, h, _ := r.FormFile("image")
  17. filename := h.Filename
  18. defer f.Close()
  19. t, _ := os.Create(UPLOAD_DIR + "/" + filename)
  20. defer t.Close()
  21. _, err := io.Copy(t, f)
  22. if err != nil {
  23. return
  24. }
  25. http.Redirect(w, r, "view?id=" + filename, http.StatusFound)
  26. }
  27. }
  28. func viewHandler(w http.ResponseWriter, r* http.Request) {
  29. imageId := r.FormValue("id")
  30. imagePath := UPLOAD_DIR + "/" + imageId
  31. w.Header().Set("Content-Type", "image")
  32. http.ServeFile(w, r, imagePath)
  33. }
  34. func listHandler(w http.ResponseWriter, r* http.Request) {
  35. fileInfoArr, _ := ioutil.ReadDir(UPLOAD_DIR)
  36. locals := make(map[string] interface{})
  37. images := []string{}
  38. for _, fileInfo := range fileInfoArr {
  39. images = append(images, fileInfo.Name())
  40. }
  41. locals["images"] = images
  42. t, _ := template.ParseFiles("list.html")
  43. t.Execute(w, locals)
  44. }
  45. func main() {
  46. http.HandleFunc("/upload", uploadHandler)
  47. http.HandleFunc("/view", viewHandler)
  48. http.HandleFunc("/", listHandler)
  49. err := http.ListenAndServe(":9090", nil)
  50. if err != nil {
  51. log.Fatal("ListenAndServe: ", err.Error())
  52. }
  53. }

其實這個網站主要就3個網頁。一個是顯示所有圖片的索引,一個是圖片顯示,另外一個就是圖片上傳頁面。

2.upload.html

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset = "utf-8">
  5. <tilte> Uploader </title>
  6. </head>
  7. <body>
  8. <form method="post" action="/upload" enctype="multipart/form-data">
  9. Choose an image to upload: <input name="image" type="file" />
  10. <input type="submit" value="Upload" />
  11. </form>
  12. </body>
  13. </html>

3.list.html

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title> List </title>
  6. </head>
  7. <body>
  8. <ol>
  9. {{range $.images}}
  10. <li><a href="/view?id={{.|urlquery}}"> {{.|html}} </a> </li>
  11. {{end}}
  12. </ol>
  13. </body>
  14. </html>

Go image網站開發

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

git在push的時候出現許可權的問題
dubbo源碼分析之遠程調用概述

TAG:程序員小新人學習 |