잠시만 기다려 주세요

     '왜 이재명은 자꾸만 국민들 보고 길바닥에 나가라고 하는 건가.. 정작 당신들은 뜨뜻한 곳에서 입만 나불거리고 있으면서...'
전체검색 :  
이번주 로또 및 연금번호 발생!!   |  HOME   |  여기는?   |  바다물때표   |  알림 (19)  |  여러가지 팁 (1095)  |  추천 및 재미 (163)  |  자료실 (28)  |  
시사, 이슈, 칼럼, 평론, 비평 (799)  |  끄적거림 (142)  |  문예 창작 (719)  |  바람 따라 (75)  |  시나리오 (760)  |  드라마 대본 (248)  |  
살인!


    golang

golang - Go Web Apps Serving Static Files, 정적파일, 이미지 처리, html, js, css, 웹서버
이 름 : 바다아이   |   조회수 : 10749         짧은 주소 : 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
번 호 카테고리 제 목 이름 조회수
180 golang golang ... 바다아이 142
179 golang golang , ... 바다아이 2727
178 golang golang , map . 바다아이 2112
177 golang Golang (, , data ) , ... 바다아이 2439
176 golang golang sort ... 바다아이 2810
175 golang golang html.EscapeString html.UnescapeString input value ... 바다아이 2734
174 golang golang go.mod go.sum . GOPATH SRC not module, 1.16 . 바다아이 6262
173 golang go 1.16 ... is not in GOROOT.. GOPATH .... . 바다아이 7416
172 golang , String Formatting 바다아이 8718
171 golang rand.Intn , random, , . 바다아이 8260
170 golang golang ... 바다아이 12007
169 golang golang gopath, goroot .. golang 바다아이 8977
168 golang golang ... Force download file example 바다아이 11007
167 golang golang , , cpu, memory, disk 바다아이 12072
166 golang golang , ... GOOS, GOARCH 바다아이 9719
165 golang golang checkbox ... 바다아이 9596
164 golang golang , , http .... 바다아이 9412
163 golang golang nil , nil , nil ... 바다아이 9491
162 golang 2 golang, go , .... golang .... 바다아이 12737
161 golang golang postgresql, mysql, mariadb ... ` Grave () .. .. 바다아이 10051
160 golang golang postgresql mysql, mariadb scan , null .. 바다아이 10123
159 golang golang , iconv 바다아이 12938
158 golang golang quote escape, unquote 바다아이 10355
157 golang golang , http errorLog , , ... 바다아이 10744
156 golang golang interface , 바다아이 9811
155 golang golang struct .... 바다아이 10533
154 golang golang map map , 바다아이 10013
153 golang golang map .... .... 바다아이 9344
152 golang golang slice copy 바다아이 9534
151 golang golang goto 바다아이 10718
| |









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