passing variable from middleware to end function - go

im using a middleware (CheckToken) to check a JWT and get the custom claim (Id) (it will be the id of the user on my DB) but i need to pass it to campaign.Attack (so i can know who is the user who is doing the "attack") but i cant find out a way to do it.
i tried to pass it as a parameter in next(w, req, claim.id) in token.go but i would need to touch the http.HandlerFunc function so this isnt a valid option.
any idea about how to pass the claim.id from CheckToken to campaign.Attack() ?
thank you
***** main.go*****
func main() {
router := mux.NewRouter()
router.HandleFunc("/attack", token.CheckToken(campaign.Attack)).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":3000", handlers.CORS(handlers.AllowedOrigins([]string{"*"}),
handlers.AllowedHeaders([]string{"Content-Type", "authorization"}))(router)))
}
******campaign.go*****
package campaign
import (
"log"
"net/http"
)
func init() {
}
func Attack(w http.ResponseWriter, req *http.Request) {
log.Println("attack")
//i need to get the claim.Id here
}
****token.go****
type MyCustomClaims struct {
Id int `json:"id"` //the Id of the user
jwt.StandardClaims
}
func CheckToken(next http.HandlerFunc) (MyCustomClaims, http.HandlerFunc) {
return MyCustomClaims{}, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
authorizationHeader := req.Header.Get("authorization")
if authorizationHeader != "" {
bearerToken := strings.Split(authorizationHeader, " ")
if len(bearerToken) == 2 {
token, err := jwt.ParseWithClaims(bearerToken[1], &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte("magicword"), nil
})
if token.Valid {
if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
//**************************
//***********i have the claims.id here and it works.*******
//**************************
log.Println(claims.Id)
//but i need to pass it or find a way to read it in campaign.Attack()
next(w, req)
} else {
log.Println(err)
}
} else if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
// Token is either expired or not active yet
}
}
}
}
})
}

Use context's method WithValue.
Instead next(w, req) write
ctx := context.WithValue(r.Context(), "claim_id", claims.Id)
next(w, req.WithContext(ctx))
and inside attack:
claim_id, ok := r.Context().Value("claim_id").(int)
if !ok {
return // I don't have context .. sorry
}
// use claim_id
What I haven't mention, how to create an unique key ... but sometimes in the future.

Look into CheckToken .. It should be middleware, and typical midleware pass http.Handler and maybe another argument and return another http.Handler (this is bit better than using http.HandlerFunc). Returned function typically call argument and do some action before or after this call.
func CheckToken(next http.Handler) http.Handler
{
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// and body the same as you have in the answer, but instead of next(w, req) put there two lines "WithValue"
}
}
and into begin of Attack put next few lines that I've already give you

Related

Why is the response body empty when running a test of mux API?

I am trying to build and test a very basic API in Go to learn more about the language after following their tutorial. The API and the four routes defined work in Postman and the browser, but when trying to write the test for any of the routes, the ResponseRecorder doesn't have a body, so I cannot verify it is correct.
I followed the example here and it works, but when I change it for my route, there is no response.
Here is my main.go file.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
// A Person represents a user.
type Person struct {
ID string `json:"id,omitempty"`
Firstname string `json:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty"`
Location *Location `json:"location,omitempty"`
}
// A Location represents a Person's location.
type Location struct {
City string `json:"city,omitempty"`
Country string `json:"country,omitempty"`
}
var people []Person
// GetPersonEndpoint returns an individual from the database.
func GetPersonEndpoint(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(req)
for _, item := range people {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Person{})
}
// GetPeopleEndpoint returns all people from the database.
func GetPeopleEndpoint(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(people)
}
// CreatePersonEndpoint creates a new person in the database.
func CreatePersonEndpoint(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(req)
var person Person
_ = json.NewDecoder(req.Body).Decode(&person)
person.ID = params["id"]
people = append(people, person)
json.NewEncoder(w).Encode(people)
}
// DeletePersonEndpoint deletes a person from the database.
func DeletePersonEndpoint(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(req)
for index, item := range people {
if item.ID == params["id"] {
people = append(people[:index], people[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(people)
}
// SeedData is just for this example and mimics a database in the 'people' variable.
func SeedData() {
people = append(people, Person{ID: "1", Firstname: "John", Lastname: "Smith", Location: &Location{City: "London", Country: "United Kingdom"}})
people = append(people, Person{ID: "2", Firstname: "John", Lastname: "Doe", Location: &Location{City: "New York", Country: "United States Of America"}})
}
func main() {
router := mux.NewRouter()
SeedData()
router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET")
router.HandleFunc("/people/{id}", GetPersonEndpoint).Methods("GET")
router.HandleFunc("/people/{id}", CreatePersonEndpoint).Methods("POST")
router.HandleFunc("/people/{id}", DeletePersonEndpoint).Methods("DELETE")
fmt.Println("Listening on http://localhost:12345")
fmt.Println("Press 'CTRL + C' to stop server.")
log.Fatal(http.ListenAndServe(":12345", router))
}
Here is my main_test.go file.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func TestGetPeopleEndpoint(t *testing.T) {
req, err := http.NewRequest("GET", "/people", nil)
if err != nil {
t.Fatal(err)
}
// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
rr := httptest.NewRecorder()
handler := http.HandlerFunc(GetPeopleEndpoint)
// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
// directly and pass in our Request and ResponseRecorder.
handler.ServeHTTP(rr, req)
// Trying to see here what is in the response.
fmt.Println(rr)
fmt.Println(rr.Body.String())
// Check the status code is what we expect.
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
// Check the response body is what we expect - Commented out because it will fail because there is no body at the moment.
// expected := `[{"id":"1","firstname":"John","lastname":"Smith","location":{"city":"London","country":"United Kingdom"}},{"id":"2","firstname":"John","lastname":"Doe","location":{"city":"New York","country":"United States Of America"}}]`
// if rr.Body.String() != expected {
// t.Errorf("handler returned unexpected body: got %v want %v",
// rr.Body.String(), expected)
// }
}
I appreciate that I am probably making a beginner mistake, so please take mercy on me. I have read a number of blogs testing mux, but can't see what I have done wrong.
Thanks in advance for your guidance.
UPDATE
Moving my SeeData call to init() resolved the body being empty for the people call.
func init() {
SeedData()
}
However, I now have no body returned when testing a specific id.
func TestGetPersonEndpoint(t *testing.T) {
id := 1
path := fmt.Sprintf("/people/%v", id)
req, err := http.NewRequest("GET", path, nil)
if err != nil {
t.Fatal(err)
}
// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
rr := httptest.NewRecorder()
handler := http.HandlerFunc(GetPersonEndpoint)
// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
// directly and pass in our Request and ResponseRecorder.
handler.ServeHTTP(rr, req)
// Check request is made correctly and responses.
fmt.Println(path)
fmt.Println(rr)
fmt.Println(req)
fmt.Println(handler)
// expected response for id 1.
expected := `{"id":"1","firstname":"John","lastname":"Smith","location":{"city":"London","country":"United Kingdom"}}` + "\n"
if status := rr.Code; status != http.StatusOK {
message := fmt.Sprintf("The test returned the wrong status code: got %v, but expected %v", status, http.StatusOK)
t.Fatal(message)
}
if rr.Body.String() != expected {
message := fmt.Sprintf("The test returned the wrong data:\nFound: %v\nExpected: %v", rr.Body.String(), expected)
t.Fatal(message)
}
}
Moving my SeedData call to init() resolved the body being empty for the people call.
func init() {
SeedData()
}
Creating a new router instance resolved the issue with accessing a variable on a route.
rr := httptest.NewRecorder()
router := mux.NewRouter()
router.HandleFunc("/people/{id}", GetPersonEndpoint)
router.ServeHTTP(rr, req)
I think its because your test isn't including the router hence the path variables aren't being detected. Here, try this
// main.go
func router() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET")
router.HandleFunc("/people/{id}", GetPersonEndpoint).Methods("GET")
router.HandleFunc("/people/{id}", CreatePersonEndpoint).Methods("POST")
router.HandleFunc("/people/{id}", DeletePersonEndpoint).Methods("DELETE")
return router
}
and in your testcase, initiatize from the router method like below
handler := router()
// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
// directly and pass in our Request and ResponseRecorder.
handler.ServeHTTP(rr, req)
And now if you try accessing the path variable id, it should be present in the map retured by mux since mux registered it when you initiatlized the Handler from mux Router instance returned from router()
params := mux.Vars(req)
for index, item := range people {
if item.ID == params["id"] {
people = append(people[:index], people[index+1:]...)
break
}
}
Also like you mentioned, use the init function for one time setups.
// main.go
func init(){
SeedData()
}

Net/http Simple Dynamic Routes

I am looking for a simple way to create dynamic routes with net/http (no routers like mux etc.)
Here is my current code:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
pages := r.URL.Query()["q"]
if len(pages) == 0 {
fmt.Fprintf(w, "§§§§§§§§§§ You need to specify a page §§§§§§§§§§")
return
}
page := pages[0]
var a Page
err := db.QueryRow("SELECT * FROM pages where page = ?", page).Scan(&a.Page, &a.Date, &a.Url)
a.Year = time.Now().UTC().Year()
if err != nil {
if err == sql.ErrNoRows {
fmt.Fprintf(w, "Page %s not found", page)
return
} else {
fmt.Fprintf(w, "Some error happened")
return
}
}
http.Redirect(w, r, a.Url, 301)
})
So now the URL sample.com/?q= works dynamically.
My objective is to work without having to use r.URL.Query()["q"] so directly /pagename
This is not a duplicate of Go url parameters mapping because it is a single level (not nested levels) AND many answers in that question refer to using an external library.
If you don't want to use any third-party libraries, you have to handle the parsing of the path yourself.
For start, you can do this:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
page := r.URL.Path[1:]
// do whatever logic you want
// mind that the page could be "multi/level/path/" as well
})
You can use http.HandleFunc.
In this function, a pattern ending in a slash defines a subtree.
You can register a handler function with the pattern "/page/" like the below example.
package main
import (
"net/http"
"fmt"
)
func handler(w http.ResponseWriter, r *http.Request) {
if is_valid_page(r.URL) {
fmt.Fprint(w, "This is a valid page")
} else {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Error 404 - Page not found")
}
}
func is_valid_page(page string) {
// check here if page is valid from url
}
func main() {
http.HandleFunc("/page/", handler)
http.ListenAndServe(":8080", nil)
}
more info you can find here: https://golang.org/pkg/net/http/#ServeMux

Set the root filesystem of http.FileServer based on a cookie in the request

router.PathPrefix("/test/").Handler(http.StripPrefix("/test/", http.FileServer(http.Dir("/assets/"))))
In this example, the root directory of the file server is set to /assets/. My goal is to set this root directory based on the cookie in the HTTP request. I know I am able to do something like this:
type AlternativeFileServer struct { }
func AlternativeFileServerFactory() http.Handler {
return AlternativeFileServer{}
}
func (aFs AlternativeFileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cookie, err := GetCookie(r)
if err != nil {
// handle error
}
var rootDirectory string
if cookie == "x" {
rootDirectory = "assets"
} else {
rootDirectory = "alternative"
}
path := filepath.join(rootDirectory, r.URL.Path) + ".png"
http.ServeFile(path)
}
func main() {
....
router.PathPrefix("/test/").Handler(http.StripPrefix("/test/", AlternativeFileServerFactory())
}
But I was hoping there was a better alternative where I could wrap the http.FileServer directly and dynamically set its root directory.
Is that possible?
One approach based on the comment thread:
type AltFileServer struct {
assertsFS http.Handler
altFS http.Handler
}
func NewAltFileServer() http.Handler {
return &AlternativeFileServer{
assetsFS: http.FileServer("assets"),
altFS: http.FileServer("alternative"),
}
}
func (fs *AltFileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cookie, err := GetCookie(r)
if err != nil {
// handle error
}
if cookie == "x" {
fs.assetsFS.ServeHTTP(w, r)
return
}
fs.altFS.ServeHTTP(w, r)
}
func main() {
....
router.PathPrefix("/test/").Handler(http.StripPrefix("/test/", NewAltFileServer())
}

Modify request header in middleware

Hopefully, this is an easy way to earn some rep. This seems very simple, so I must be doing something wrong and just cant see it.
I have a simple middleware which a transaction id and adds it to the request and response headers.
func HandleTransactionID(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
tid := uuid.NewV4()
req.Header.Set(TransIDHeader, TransIDPrefix + tid.String())
w.Header().Set(TransIDHeader, TransIDPrefix + tid.String())
fn(w, req)
}
}
In my unit tests, I've confirmed the response header is successfully set, but it doesn't appear the the request header is being set. I would assume that it is possible to modify the request headers, so ?
const (
WriteTestHeader = "WriterTransHeader"
RequestTestHeader = "ReqTransHeader"
)
func recorderFunc(w http.ResponseWriter, req *http.Request){
w.Header().Set(WriteTestHeader, w.Header().Get(TransIDHeader))
w.Header().Set(RequestTestHeader, req.Header.Get(TransIDHeader))
}
func TestHandleTransactionID(t *testing.T) {
recorder := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/foo", nil)
middleware.HandleTransactionID(recorderFunc)(recorder, req)
if req.Header.Get(RequestTestHeader) == "" {
t.Error("request header is nil")
}
if recorder.Header().Get(WriteTestHeader) == "" {
t.Error("response header is nil")
}
if req.Header.Get(RequestTestHeader) != recorder.Header().Get(WriteTestHeader) {
t.Errorf("header value mismatch: %s != %s",
req.Header.Get(RequestTestHeader),
recorder.Header().Get(WriteTestHeader))
}
}
In your test, req.Header.Get(RequestTestHeader) will always remain an empty string because you are not setting the Key as 'RequestTestHeader' in the request header but in the ResponseWriter w.Header().Set(RequestTestHeader, req.Header.Get(TransIDHeader))
On an unrelated note, It would be considered idomatic Go, to have your middleware function signature using the http.Handler interface, func HandleTransactionID(fn http.Handler) http.Handler.

Showing custom 404 error page with standard http package

Assuming that we have:
http.HandleFunc("/smth", smthPage)
http.HandleFunc("/", homePage)
User sees a plain "404 page not found" when they try a wrong URL. How can I return a custom page for that case?
Update concerning gorilla/mux
Accepted answer is ok for those using pure net/http package.
If you use gorilla/mux you should use something like this:
func main() {
r := mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(notFound)
}
And implement func notFound(w http.ResponseWriter, r *http.Request) as you want.
I usually do this:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/smth/", smthHandler)
http.ListenAndServe(":12345", nil)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
errorHandler(w, r, http.StatusNotFound)
return
}
fmt.Fprint(w, "welcome home")
}
func smthHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/smth/" {
errorHandler(w, r, http.StatusNotFound)
return
}
fmt.Fprint(w, "welcome smth")
}
func errorHandler(w http.ResponseWriter, r *http.Request, status int) {
w.WriteHeader(status)
if status == http.StatusNotFound {
fmt.Fprint(w, "custom 404")
}
}
Here I've simplified the code to only show custom 404, but I actually do more with this setup: I handle all the HTTP errors with errorHandler, in which I log useful information and send email to myself.
Following is the approach I choose. It is based on a code snippet which I cannot acknowledge since I lost the browser bookmark.
Sample code : (I put it in my main package)
type hijack404 struct {
http.ResponseWriter
R *http.Request
Handle404 func (w http.ResponseWriter, r *http.Request) bool
}
func (h *hijack404) WriteHeader(code int) {
if 404 == code && h.Handle404(h.ResponseWriter, h.R) {
panic(h)
}
h.ResponseWriter.WriteHeader(code)
}
func Handle404(handler http.Handler, handle404 func (w http.ResponseWriter, r *http.Request) bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
hijack := &hijack404{ ResponseWriter:w, R: r, Handle404: handle404 }
defer func() {
if p:=recover(); p!=nil {
if p==hijack {
return
}
panic(p)
}
}()
handler.ServeHTTP(hijack, r)
})
}
func fire404(res http.ResponseWriter, req *http.Request) bool{
fmt.Fprintf(res, "File not found. Please check to see if your URL is correct.");
return true;
}
func main(){
handler_statics := http.StripPrefix("/static/", http.FileServer(http.Dir("/Path_To_My_Static_Files")));
var v_blessed_handler_statics http.Handler = Handle404(handler_statics, fire404);
http.Handle("/static/", v_blessed_handler_statics);
// add other handlers using http.Handle() as necessary
if err := http.ListenAndServe(":8080", nil); err != nil{
log.Fatal("ListenAndServe: ", err);
}
}
Please customize the func fire404 to output your own version of message for error 404.
If you happen to be using Gorilla Mux, you may wish to replace the main function with below :
func main(){
handler_statics := http.StripPrefix("/static/", http.FileServer(http.Dir("/Path_To_My_Static_Files")));
var v_blessed_handler_statics http.Handler = Handle404(handler_statics, fire404);
r := mux.NewRouter();
r.PathPrefix("/static/").Handler(v_blessed_handler_statics);
// add other handlers with r.HandleFunc() if necessary...
http.Handle("/", r);
log.Fatal(http.ListenAndServe(":8080", nil));
}
Please kindly correct the code if it is wrong, since I am only a newbie to Go. Thanks.
Ancient thread, but I just made something to intercept http.ResponseWriter, might be relevant here.
package main
//GAE POC originally inspired by https://thornelabs.net/2017/03/08/use-google-app-engine-and-golang-to-host-a-static-website-with-same-domain-redirects.html
import (
"net/http"
)
func init() {
http.HandleFunc("/", handler)
}
// HeaderWriter is a wrapper around http.ResponseWriter which manipulates headers/content based on upstream response
type HeaderWriter struct {
original http.ResponseWriter
done bool
}
func (hw *HeaderWriter) Header() http.Header {
return hw.original.Header()
}
func (hw *HeaderWriter) Write(b []byte) (int, error) {
if hw.done {
//Silently let caller think they are succeeding in sending their boring 404...
return len(b), nil
}
return hw.original.Write(b)
}
func (hw *HeaderWriter) WriteHeader(s int) {
if hw.done {
//Hmm... I don't think this is needed...
return
}
if s < 400 {
//Set CC header when status is < 400...
//TODO: Use diff header if static extensions
hw.original.Header().Set("Cache-Control", "max-age=60, s-maxage=2592000, public")
}
hw.original.WriteHeader(s)
if s == 404 {
hw.done = true
hw.original.Write([]byte("This be custom 404..."))
}
}
func handler(w http.ResponseWriter, r *http.Request) {
urls := map[string]string{
"/example-post-1.html": "https://example.com/post/example-post-1.html",
"/example-post-2.html": "https://example.com/post/example-post-2.html",
"/example-post-3.html": "https://example.com/post/example-post-3.html",
}
w.Header().Set("Strict-Transport-Security", "max-age=15768000")
//TODO: Put own logic
if value, ok := urls[r.URL.Path]; ok {
http.Redirect(&HeaderWriter{original: w}, r, value, 301)
} else {
http.ServeFile(&HeaderWriter{original: w}, r, "static/"+r.URL.Path)
}
}
i think the clean way is this:
func main() {
http.HandleFunc("/calculator", calculatorHandler)
http.HandleFunc("/history", historyHandler)
http.HandleFunc("/", notFoundHandler)
log.Fatal(http.ListenAndServe(":80", nil))
}
if the address is not /calulator or /history, then it handles notFoundHandler function.
Maybe I'm wrong, but I just checked the sources: http://golang.org/src/pkg/net/http/server.go
It seems like specifying custom NotFound() function is hardly possible: NotFoundHandler() returns a hardcoded function called NotFound().
Probably, you should submit an issue on this.
As a workaround, you can use your "/" handler, which is a fallback if no other handlers were found (as it is the shortest one). So, check is page exists in that handler and return a custom 404 error.
You just need to create your own notFound handler and register it with HandleFunc for the path that you don't handle.
If you want the most control over your routing logic you will need to use a custom server and custom handler type of your own.
http://golang.org/pkg/net/http/#Handler
http://golang.org/pkg/net/http/#Server
This allows you to implement more complex routing logic than the HandleFunc will allow you to do.
you can define
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
if request.URL.Path != "/" {
writer.WriteHeader(404)
writer.Write([]byte(`not found, da xiong dei !!!`))
return
}
})
when access not found resource, it will execute to http.HandleFunc("/", xxx)
You can simply use something like:
func Handle404(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "404 error\n")
}
func main(){
http.HandleFunc("/", routes.Handle404)
}
If you need to get the standard one, just write:
func main(){
http.HandleFunc("/", http.NotFound)
}
And you'll get:
404 page not found

Resources