잠시만 기다려 주세요

     '애도와 추모가 책임있는 사람들에게 면죄부를 주어서는 안됩니다. -더불어 민주당 국회의원 김용민-'
전체검색 :  
이번주 로또 및 연금번호 발생!!   |  HOME   |  여기는?   |  바다물때표   |  알림 (16)  |  여러가지 팁 (1056)  |  추천 및 재미 (155)  |  자료실 (22)  |  
시사, 이슈, 칼럼, 평론, 비평 (606)  |  끄적거림 (129)  |  문예 창작 (705)  |  바람 따라 (69)  |  시나리오 (760)  |  드라마 대본 (248)  |  
살인!


    golang

golang - Go Web Apps Serving Static Files, 정적파일, 이미지 처리, html, js, css, 웹서버
이 름 : 바다아이   |   조회수 : 8784         짧은 주소 : https://www.bada-ie.com/su/?241591783608

Disclaimer: this is old content that’s horribly out of date and possibly very incorrect. I’ve
archived it here for historic purposes only. It’s smelly, most likely not relevant, and I was still very
much learning the language.

One feature of Go web applications I struggled with early on was how to serve my static (css, js, images, etc…)
content. Here’s the setup that ended up working for me!

My working GOPATH directory structure:

  • /src
    • /webapp
      • webapp.go - my go web application source
      • /static
        • /img
          • test.gif - static image file I want to render in the browser

The goal, when done, will be for the following url to return the test.gif test image,
assuming that the web application is listening on port 17901:

http://localhost:17901/static/img/test.gif

webapp.go

Here’s what webapp.go looks like before adding in static file support:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", homeHandler)
    panic(http.ListenAndServe(":17901", nil))
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "<html><head></head><body><h1>Welcome Home!</h1></body></html>")
}

This really is about as basic as it gets. A simple Go web application that only responds to root requests.
Point your browser to

 http://localhost:17901 

and you should see a big Welcome Home! However, if you try the following:

http://localhost:17901/static/img/test.gif

you should be greeted with a 404. Lets add static file support!

Adding Static Files

Add the following below your home handler:

http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, r.URL.Path[1:])
})

Couple things worth noting here. This is using the net/http package’s ServeFile function to serve our content.
Effectively anything that makes a request starting with the /static/ path will be handled by this function.
One thing I found I had to do in order for the request to be handled correctly was trim the leading ‘/’ using:

r.URL.Path[1:]

Also note that this will be looking for the requested file in a static folder relative to the executing application
i.e. just like my folder structure detailed above. If you want to move your static folder elsewhere you’ll need
to modify the ServeFile call accordingly. Now, open up your browser and lets try loading our image again:

http://localhost:17901/static/img/test.gif

You should now see your file image delivered directly to your browser! Adding stylesheets, scripts, etc.
will all work the same way now that we have this working.

Tidying Up

Lets modify our home page markup to serve up an anchor that will, when clicked, load up our test image.
Here’s the final code for webapp.go:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", homeHandler)
    http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, r.URL.Path[1:])
    })
    panic(http.ListenAndServe(":17901", nil))
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "<html><head></head><body><h1>Welcome Home!</h1>
<a href=\"/static/img/test.gif\">Show Image!</a></body></html>")
}

If you run the above you’ll see you now have an anchor on your home page that, when clicked, should load
the same test image as we loaded previously directly!



출처 : http://jessekallhoff.com/2013/04/14/go-web-apps-serving-static-files/
 
| |





      1 page / 6 page
번 호 카테고리 제 목 이름 조회수
179 golang golang , ... 바다아이 1732
178 golang golang , map . 바다아이 1336
177 golang Golang (, , data ) , ... 바다아이 1344
176 golang golang sort ... 바다아이 1573
175 golang golang html.EscapeString html.UnescapeString input value ... 바다아이 1703
174 golang golang go.mod go.sum . GOPATH SRC not module, 1.16 . 바다아이 4977
173 golang go 1.16 ... is not in GOROOT.. GOPATH .... . 바다아이 5883
172 golang , String Formatting 바다아이 7515
171 golang rand.Intn , random, , . 바다아이 6973
170 golang golang ... 바다아이 10062
169 golang golang gopath, goroot .. golang 바다아이 7652
168 golang golang ... Force download file example 바다아이 9434
167 golang golang , , cpu, memory, disk 바다아이 10733
166 golang golang , ... GOOS, GOARCH 바다아이 8510
165 golang golang checkbox ... 바다아이 8258
164 golang golang , , http .... 바다아이 8030
163 golang golang nil , nil , nil ... 바다아이 8377
162 golang 2 golang, go , .... golang .... 바다아이 11247
161 golang golang postgresql, mysql, mariadb ... ` Grave () .. .. 바다아이 8562
160 golang golang postgresql mysql, mariadb scan , null .. 바다아이 8707
159 golang golang , iconv 바다아이 11499
158 golang golang quote escape, unquote 바다아이 8907
157 golang golang , http errorLog , , ... 바다아이 9009
156 golang golang interface , 바다아이 8487
155 golang golang struct .... 바다아이 9153
154 golang golang map map , 바다아이 8679
153 golang golang map .... .... 바다아이 8197
152 golang golang slice copy 바다아이 8297
151 golang golang goto 바다아이 9158
150 golang golang slice sort , int, string, float64 바다아이 8639
| |









Copyright ⓒ 2001.12. bada-ie.com. All rights reserved.
이 사이트는 리눅스에서 firefox 기준으로 작성되었습니다. 기타 브라우저에서는 다르게 보일 수 있습니다.
[ Ubuntu + GoLang + PostgreSQL + Mariadb ]
서버위치 : 오라클 클라우드 춘천  실행시간 : 0.07324
to webmaster... gogo sea. gogo sea.