miha
(Miha)
April 17, 2019, 2:16pm
1
Hi
i have HandlFunc: http.HandleFunc("/welcome", ValidateToken(Welcome))
func ValidateToken(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
next.Serv(w,r)
}}
> func Welcome(w http.ResponseWriter, r *http.Request) {
> fmt.Println("welcoma page")
> w.Write([]byte("sads"))
> }
How can I return something from ValidateToken, so that will be able to use it in Welcome func?
I am validation something in ValidateToken and then I need this info also in Welcome function.
thank you.
miha
You could use a global var or maybe a receiver…
Anothe roption is use the context package.
Take a look at 5 Useful Ways to Use Closures in Go . Specifically #3 .
package main
import (
"fmt"
"net/http"
)
type Database struct {
Url string
}
func NewDatabase(url string) Database {
return Database{url}
}
func main() {
db := NewDatabase("localhost:5432")
http.HandleFunc("/hello", hello(db))
http.ListenAndServe(":3000", nil)
}
func hello(db Database) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, db.Url)
}
}
system
(system)
Closed
July 18, 2019, 11:54am
4
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.