返回首页 神奇的 Go 语言

image 网站开发

有过 Python Web 开发经验的朋友,相信对它的便利性肯定印象非常深刻。其实利用 Go 语言对 Web 网站进行开发也是非常容易的一件事情。之前我对 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?id={{.|urlquery}}"> {{.|html}} </a> </li>  
    {{end}}  

</ol>  
</body>  

</html>  

上面的网页与其说是一个网页,倒不如说是一个模板。因为所有的 images 内容其实都要从外界进行传递的,而这所有的内容才会构成一个真正的网页。

上一篇: 高级应用 下一篇: 聊天室的开发