i'm coming from Java, and there you always do something like:
Http http = new Http(...);
http.ListenAndServe();
So all information are stored in the local variable "http".
It's different in go. There most of the information is stored directly "in another package".
You do:
import "net/http"
...
http.ListenAndServe(...)
So you dont have to explicitly (well you could) instantiate a server struct. Just call a function from the package and all the structs will be created from there. (So compared to Java, it acts like static functions with static member variables to store all information ?)
So this is how you do it (everytime) in go ? Coming from Java, this is a little bit hard to understand. Especially when to use this method, when to use a factory pattern (like: NewHttpServer(...)
) and when to explicitly create a struct from another package ( like: var http http.Server = http.Server{...}
)
Everything might be possible, but what is the idiomatic golang code ?
Is there any good document/tutorial which explains it ?
I'd really suggest reading the Godoc for net/http
. The package is very feature-rich and lets you do what you want.
The behaviour of http.ListenAndServe
is to implicitly use a serve multiplexer known as DefaultServeMux
, on which you can register handlers with http.Handle
. So you can't deal with the server or multiplexer explicitly like this.
It sounds like what you want (a more Java-like solution) is to instantiate a server
s := &http.Server{
Addr: ":8080",
Handler: myHandler, // takes a path and a http.HandlerFunc
ReadTimeout: 10 * time.Second, // optional config
WriteTimeout: 10 * time.Second, // ...
MaxHeaderBytes: 1 << 20,
}
and call ListenAndServe
on that:
log.Fatal(s.ListenAndServe())
Both ways are totally idiomatic, I've seen them used quite frequently.
But seriously, don't take my word for it. Go look at the docs, they have lots of examples :)
I do not know if there is a hard-and-fast rule to answer your question. I normally use a factory method when one of these conditions holds: