The first go Web program, call seven Qiniu storage audio API problem resolution; Condition search file contents, string concatenation + on the previous line

Source: Internet
Author: User
Tags crc32 key string

Package Main


Import (
"Html/template"
"IO"
"Io/ioutil"
"Log"
"Net/http"
"OS"
"Path"
"Runtime/debug"
)


Const (
Listdir = 0x0001
Upload_dir = "./uploads"
Template_dir = "./views"
)


Cache Storage All Template
var templates = Make (map[string]*template. Template)


Func init () {
Fileinfoarr, err: = Ioutil. ReadDir (Template_dir)
Check (ERR)
var templatename, TemplatePath string
For _, FileInfo: = Range Fileinfoarr {
templatename = Fileinfo.name ()
If ext: = path. EXT (templatename); Ext! = ". html" {
Continue
}
TemplatePath = Template_dir + "/" + templatename
Log. Println (templatename)
Log. Println ("Loading Template:", TemplatePath)
T: = template. Must (template. Parsefiles (TemplatePath))
Templates[templatename] = t
}


If const template
/*for _, Tmpl: = range []string{"Upload", "list"} {
Must ensure in case can ' t analytic would do error operate,if the template loading isn't successful, the program would exi T
T: = template. Must (template. Parsefiles (Tmpl + ". html"))
Templates[tmpl] = t
}*/
}
Func Check (err error) {
If err! = Nil {
Panic (ERR)
}
}
Func renderhtml (w http. Responsewriter, Tmpl string, locals map[string]interface{}) {
/*TT: = Templates[tmpl]
Log. Println ("Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", templates, Tmpl, TT) */
Log. PRINTLN (Locals)
ERR: = Templates[tmpl]. Execute (W, locals)


Check (ERR)
}
Func isexists (path string) bool {
_, Err: = OS. Stat (PATH)
Log. PRINTLN (ERR)
If Err = = Nil {
return True
}
return OS. Isexist (ERR)
}


Callback method,
Func Uploadhandler (w http. Responsewriter, R *http. Request) {
Log. Println (R.method)
if R.method = = "GET" {
Renderhtml (W, "upload.html", nil)
}
if R.method = = "POST" {
F, h, err: = R.formfile ("image")
Log. Println (F, H, err)
Check (ERR)
FileName: = H.filename
Defer F.close ()
Log. PRINTLN (upload_dir, filename)
T, err: = Ioutil. Tempfile (upload_dir, filename)
Log. Println (t)
Check (ERR)
Defer T.close ()
_, err = Io. Copy (T, f)//dst SRC
Check (ERR)
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
Log. Println (ImageId, ImagePath)
if exists: = Isexists (ImagePath);!exists {
http. NotFound (W, R)
Return
}
Log. Println ("222222222222")
W.header (). Set ("Content-type", "image")
http. Servefile (W, R, ImagePath)
}
Func Listhandler (w http. Responsewriter, R *http. Request) {
Fileinfoarr, err: = Ioutil. ReadDir ("./uploads")
Log. Println (Fileinfoarr)
Check (ERR)
If err! = Nil {
http. Error (W, err. Error (), HTTP. Statusinternalservererror)
Return
}
Locals: = Make (map[string]interface{})
Images: = []string{}
For _, FileInfo: = Range Fileinfoarr {
Log. Println (FileInfo)
Images = append (images, fileinfo.name ())
}
locals["Images"] = images//Here the map key is images, corresponding list.html inside $.images
Renderhtml (W, "list.html", locals)


}

Skillfully use closures to avoid error crashes when executing
Func Safehandler (fn http. Handlerfunc) http. Handlerfunc {


return func (w http. Responsewriter, R *http. Request) {
Defer func () {
Log. Println ("Can ' t past execute or finished execute")
If e, OK: = Recover (). (error); OK {
Log. PRINTLN ("50x error")
50x Error
http. Error (W, e.error (), HTTP. Statusinternalservererror)
Log. Println ("Warn:panic in%v.-%v", FN, E)
Log. Println (String (Debug. Stack ()))
}
}()


log. Println ("If no panic then first execute")
FN (W, R)
}
}
Func Staticdirhandler (Mux *http. Servemux, prefix string, staticdir string, flags int) {
Mux. Handlefunc (Prefix, func (w http. Responsewriter, R *http. Request) {
File: = Staticdir + R.url. Path[len (prefix)-1:]
if (Flags & listdir) = = 0 {
if exists: = isexists (file);!exists {
http. NotFound (W, R)
Return
}
}
http. Servefile (W, R, file)
})


}
Func Main () {
MUX: = http. Newservemux ()
Staticdirhandler (MUX, "/assets/", "./public", 0)
Mux. Handlefunc ("/", Safehandler (Listhandler))
Mux. Handlefunc ("/view", Safehandler (Viewhandler))
Mux. Handlefunc ("/upload", Safehandler (Uploadhandler))
ERR: = http. Listenandserve (": 8080", MUX)
If err! = Nil {
Log. Fatal ("Listenandserve:", err.) Error ())
}

}

Uoload.html


<meta charset= "Utf-8" >
<title>upload</title>
<body>
<form method= "POST" action= "/upload" enctype= "Multipart/form-data" >
Choosing an image to upload:<br>
<input name= "image" type= "file" >
<input type= "Submit" value= "Upload" >
</form>
</body>

List.html

<meta charset= "Utf-8" >
<title>list</title>
<body>
<ol>
{{Range $.images}}
<li><a href= "/view?id={{.| Urlquery}} ">{{.| Html}}</a></li>
{{End}}
</ol>
</body>

Note the file structure

PhotoWeb

-photoweb.go

-public

-js

-css

-images

-uploads

-views

-upload.html

-list.html


Resolve call Seven cow audio problem


The demo sample simply provides code to invoke the API, and cannot be changed directly by adding a parameter to the URL like image processing

If the URL is strong, you will be prompted to preprocess the audio transcoding. Asynchronous mode for general transcoding

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbmvlzgthbmu=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

OK, in the SDK code of Go, the results found that the API to the number of parameters is only a approximate, go API in the corresponding parameters. Not exactly the same as the official website.

We need putpolicy to search.


In Rs/token.go, see the corresponding deadline. grep ' xx ' *-R to view the contents of the file


Package Main


Import (
"FMT"
. "Github.com/qiniu/api/conf"
"Github.com/qiniu/api/fop"
"Github.com/qiniu/api/io"
"Github.com/qiniu/api/rs"
"Log"
)


Func init () {


Access_key = "Own ak"
Secret_key = "Own SK"
}


GET Upload access token
Func Uptoken (Bucketname string) string {
Putpolicy: = Rs. putpolicy{
Scope:bucketname,
Callbackurl:callbackurl,
Callbackbody:callbackbody,
Returnurl:returnurl,
Returnbody:returnbody,
Asyncops:asyncops,
Enduser:enduser,
Expires:expires,
expires:1406555272,//cutoff time stamp
Persistentops: "Avthumb/mp3",
Persistentnotifyurl: "Http://fake.com/qiniu/notify",
}
Return Putpolicy.token (Nil)
}


Func Main () {
Uploading Local Files
Upload ("a")


5.1 Getting file information
GetFileInfo ()


6.1.1 Viewing image properties
Imageattr ()


5.2 Deleting files
Delfile ()


}


6.1.1 Viewing image properties
Func imageattr () {
var imageUrl = "Http://needkane.qiniudn.com/kane2.jpg"
II: = FOP. imageinfo{}
Inforet, Err: = II. Call (nil, IMAGEURL)
If err! = Nil {
Error generated
Log. Println ("Fop Getimageinfo failed:", err)
Return
}


Log. Println (Inforet.height, Inforet.width, Inforet.colormodel, Inforet.format)
}


Func Makeimageinfourl (ImageUrl string) string {
II: = FOP. imageinfo{}
Return II. MakeRequest (IMAGEURL)
}


5.2 Deleting files
Func Delfile () {
Bucket: = "Needkane"
Key: = "Goupload.jpg"
var rscli = Rs. New (Nil)


ERR: = Rscli.delete (nil, bucket, key)
If err! = Nil {
Error generated
Log. Println ("Rs. Copy failed: ", err)
Return
}
}


5.1 Getting file information
Func GetFileInfo () {
var ret rs. Entry
Bucket: = "Needkane"
Key: = "Kane3.jpg"
var rscli = Rs. New (Nil)
var err error
RET, err = Rscli.stat (nil, bucket, key)


If err! = Nil {
Error generated
Log. Println ("Rs. Stat failed: ", err)
Return
}


Handling Return Values
Log. PRINTLN (ret)
}


Uploading Local Files
Func upload (key string) {
Uptoken: = Uptoken ("Needkane")
Fmt. Printf ("uptoken:%s\n", Uptoken)


var err error
var ret io. Putret
var extra = &io. putextra{
Params:params,
Mimetype:mietype,
CRC32:CRC32,
CHECKCRC:CHECKCRC,
}


var LocalFile = "/home/qboxtest/downloads/a.wav"


The RET variable is used to access the returned information, see IO for details. Putret
Uptoken the upload password generated for the Business Server
Key is the identity of the file store
LocalFile to local file name
Extra for additional information on uploading files. See IO for details. PutExtra, optional
Err = io. Putfile (Nil, &ret, Uptoken, Key, LocalFile, extra)


If err! = Nil {
Upload generates errors
Log. Print ("Io. Putfile failed: ", err)
Return
}


Upload successful, process return value
Log. Print (ret. Hash, ret. Key)


}

Viewing files with the file command


The first go Web program, call seven Qiniu storage audio API problem resolution; Condition search file contents, string concatenation + on the previous line

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.