从目录上看,代码的内容非常简单。picture.go包含了所有的交互代码,list.html和upload.html则包含了使用到的模板文件,而uploads目录则保存了所有上传的image文件。

    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个网页。一个是显示所有图片的索引,一个是图片显示,另外一个就是图片上传页面。

    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>

    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网站开发 - 图1