Answer the question
In order to leave comments, you need to log in
How to correctly pass data to http handler in golang?
I just understand golang (before that I worked on Rails).
So to speak, the magic of the rails left its mark.
I deal with the creation of a web application on go so far without fashionable frameworks (Martini and above).
In order to figure it out, I took this example https://github.com/haruyama/golang-goji-sample
here Goji + parts from Gorilla
That's what confused me - why all data is transferred to the controller (http handler) through the context that is filled in the middleware ? I saw this, probably in all the examples on the net. Why can't you just make a global variable, initialize it in main and just access it from the controller? Is there some hidden meaning in go or is it done that was convenient?
UPD: I found this interesting information in one article:
There's three ways that Go's web libraries/frameworks have attacked the problem of request contexts:
A global map, with *http.Request as the key, mutexes to synchronize writes, and middleware to cleanup old requests (gorilla/context)
A strictly per- request map by creating custom handler types (goji)
Structs, and creating middleware as methods with pointer receivers or passing the struct to your handlers (gocraft/web).
Answer the question
In order to leave comments, you need to log in
- it's not idiomatic to make symbols more global than necessary, request/connection space is sufficient for context, main space is redundant
- all types in Go are concurrently read-only safe out of the box
- by far the most idiomatic solution https://blog.golang.org/context godoc. org/code.google.com/p/go.net/context
the first two points are IMHO, the last one is the strategy of key language developers
Didn't work with Gorilla. But the meaning is probably the same. You define a function that accepts a Response and a Request. Then register it with http.HandleFunc.
package main
import (
"io"
"net/http"
"log"
)
// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "hello, world!\n")
}
func main() {
http.HandleFunc("/hello", HelloServer)
err := http.ListenAndServe(":12345", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question