惊人go语言,image网站开发

【 声明:版权全部,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】

有过python web开发经验的朋友。相信对它的便利性肯定印象很深刻。

事实上利用go语言对web站点进行开发也是很easy的一件事情。

之前我对web开发的经验也为0。可是使用go语言之后,你能够在最短的时间内搭建一个站点。

为了学习的方便。大家能够直接从github上下载到本篇博客谈到的全部代码。同一时候,文章中的代码部分引用了《go语言编程》中的代码内容,在此一并表示感谢。本次内容的地址在。有兴趣的同学能够下载看一下。

从文件夹上看,代码的内容很简单。picture.go包括了全部的交互代码,list.html和upload.html则包括了使用到的模板文件。而uploads文件夹则保存了全部上传的image文件。

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

以下看看。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>

有过前端开发经验的朋友肯定一眼就看出来了,这事实上就是个简单的登录上传页面。那么list.html又是什么东西呢?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> List </title>
</head>

<body>
<ol>
        {{range $.images}}
        <li><a href="/view?
urlquery}}"> {{.|html}} </a> </li> {{end}} </ol> </body> </html>

上面的网页与其说是一个网页。倒不如说是一个模板。由于全部的images内容事实上都要从外界进行传递的,而这全部的内容才会构成一个真正的网页。不知道我说清晰了没有。

上面的站点简单而清晰,有兴趣的朋友能够好好看一看。

版权声明:本文博客原创文章。博客,未经同意,不得转载。