驚人go語言(image網站開發)


【 聲明:版權所有,歡迎轉載,請勿用於商業用途。  聯繫信箱:feixiaoxing @163.com】html


    有過python web開發經驗的朋友。相信對它的便利性確定印象很深入。前端

事實上利用go語言對web站點進行開發也是很easy的一件事情。python

以前我對web開發的經驗也爲0。但是使用go語言以後,你可以在最短的時間內搭建一個站點。git

  

    爲了學習的方便。你們可以直接從github上下載到本篇博客談到的所有代碼。同一時候,文章中的代碼部分引用了《go語言編程》中的代碼內容,在此一併表示感謝。本次內容的地址在。有興趣的同窗可以下載看一下。github


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


    首先看看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()) } } app

  

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


    如下看看。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內容事實上都要從外界進行傳遞的,而這所有的內容纔會構成一個真正的網頁。不知道我說清晰了沒有。

    上面的站點簡單而清晰,有興趣的朋友可以好好看一看。

相關文章
相關標籤/搜索