잠시만 기다려 주세요

     '대통령을 욕하는 것은 민주사회에서 주권을 가진 시민의 당연한 권리입니다. 대통령을 욕하는 것으로 주권자가 스트레스를 해소할 수 있다면 저는 기쁜 마음으로 들을 수 있습니다. - 노무현 -'
전체검색 :  
이번주 로또 및 연금번호 발생!!   |  HOME   |  여기는?   |  바다물때표   |  알림 (17)  |  여러가지 팁 (1082)  |  추천 및 재미 (158)  |  자료실 (24)  |  
시사, 이슈, 칼럼, 평론, 비평 (714)  |  끄적거림 (138)  |  문예 창작 (716)  |  바람 따라 (75)  |  시나리오 (760)  |  드라마 대본 (248)  |  
살인!


    golang

golang - Go Web Apps Serving Static Files, 정적파일, 이미지 처리, html, js, css, 웹서버
이 름 : 바다아이   |   조회수 : 10140         짧은 주소 : 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 , ... 바다아이 2363
178 golang golang , map . 바다아이 1807
177 golang Golang (, , data ) , ... 바다아이 2029
176 golang golang sort ... 바다아이 2375
175 golang golang html.EscapeString html.UnescapeString input value ... 바다아이 2365
174 golang golang go.mod go.sum . GOPATH SRC not module, 1.16 . 바다아이 5858
173 golang go 1.16 ... is not in GOROOT.. GOPATH .... . 바다아이 6878
172 golang , String Formatting 바다아이 8300
171 golang rand.Intn , random, , . 바다아이 7827
170 golang golang ... 바다아이 11394
169 golang golang gopath, goroot .. golang 바다아이 8521
168 golang golang ... Force download file example 바다아이 10445
167 golang golang , , cpu, memory, disk 바다아이 11576
166 golang golang , ... GOOS, GOARCH 바다아이 9229
165 golang golang checkbox ... 바다아이 9094
164 golang golang , , http .... 바다아이 8909
163 golang golang nil , nil , nil ... 바다아이 9077
162 golang 2 golang, go , .... golang .... 바다아이 12240
161 golang golang postgresql, mysql, mariadb ... ` Grave () .. .. 바다아이 9573
160 golang golang postgresql mysql, mariadb scan , null .. 바다아이 9611
159 golang golang , iconv 바다아이 12459
158 golang golang quote escape, unquote 바다아이 9898
157 golang golang , http errorLog , , ... 바다아이 10232
156 golang golang interface , 바다아이 9307
155 golang golang struct .... 바다아이 10087
154 golang golang map map , 바다아이 9612
153 golang golang map .... .... 바다아이 8944
152 golang golang slice copy 바다아이 9103
151 golang golang goto 바다아이 10210
150 golang golang slice sort , int, string, float64 바다아이 9804
| |









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