Answer the question
In order to leave comments, you need to log in
How to create multiple file servers in golang?
Here is my code
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"strings"
)
func main() {
const jsonStream = `
{"Port": "8080", "Dir": "/home/v-smerti/localhost/public/file_server"}
{"Port": "8081", "Dir": "/home/v-smerti/localhost/public/file"}
`
type Message struct {
Port, Dir string
}
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
var m Message
if err := dec.Decode(&m); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
go http.ListenAndServe(m.Port, http.FileServer(http.Dir(m.Dir)))
}
}
8080: /home/v-smerti/localhost/public/file_server
panic: listen tcp: missing port in address 8080
goroutine 1 [running]:
main.main()
/home/v-smerti/localhost/api/src/file_server/main.go:29 +0x431
goroutine 17 [syscall, locked to thread]:
runtime.goexit()
/usr/lib/go/src/runtime/asm_386.s:1662 +0x1
exit status 2
# command-line-arguments
./main.go:23: cannot use bs (type []byte) as type string in argument to strings.NewReader
Answer the question
In order to leave comments, you need to log in
only for "purely academic purposes"
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"strings"
)
func main() {
const jsonStream = `
{"Port": ":8080", "Dir": "/home/v-smerti/localhost/public/file_server"}
{"Port": ":8081", "Dir": "/home/v-smerti/localhost/public/file"}
`
type Message struct {
Port, Dir string
}
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
var m Message
if err := dec.Decode(&m); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
go http.ListenAndServe(m.Port, http.FileServer(http.Dir(m.Dir)))
}
forever := make(chan struct{})
<-forever
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question