Simple Go web server that service files

74 views
Skip to first unread message

sunto...@gmail.com

unread,
May 6, 2019, 6:45:08 PM5/6/19
to golang-nuts
I'm learning Go web server programming and have copied the following example:


func Image(w http.ResponseWriter, r *http.Request) {
    f
, _ := os.Open("images/my.png")
   
. . .


It works fine when I'm starting the Go web server with `go run main.go &`. I.e., the file "images/my.png" is related to where I started "go run". 
However, it won't be the case when the Go web server is compiled and started the other way. 

What's the proper way to make sure it always works, including starting from docker container? 

THX!




Luis Furquim

unread,
May 7, 2019, 7:40:19 AM5/7/19
to golang-nuts
Hi

I think that this is the case that "proper way" means "the one that fits your needs".
Some solutions you may adopt:
a) (cd /path/to/my/server/directory ; go run main.go) &
b) use absolute pathnames: os.Open("/path/to/my/server/directory/images/my.png")
c) Load configuration from some file/db
d) command line flags, like:
.
.
.
import "flag"
.
.
.
var pathToMyServerDirectory string
.
.
.
flag.StringVar(&pathToMyServerDirectory,"path",".","Server root directory")
.
.
.

sunto...@gmail.com

unread,
May 7, 2019, 9:00:59 AM5/7/19
to golang-nuts


On Tuesday, May 7, 2019 at 7:40:19 AM UTC-4, Luis Furquim wrote:
Hi

I think that this is the case that "proper way" means "the one that fits your needs".

 Ah, yeah, that's true -- I thought that there are some canonical ways, but you are indeed right. 


Reply all
Reply to author
Forward
0 new messages