http.Handler is not called in golangGolang application auto build versioningGolang Gorilla mux with http.FileServer returning 404Golang Gorilla/sessionGolang http mux change handler functiongolang return static html file at specified routeglobal recover handler for golang http panicGo - Variable initialized and non nil, but nil for other functionsGolang sharing configurations between packagesGolang logging http responses (in addition to requests)Golang package undefined

What is a simple, physical situation where complex numbers emerge naturally?

How do I get a cleat that's stuck in a pedal, detached from the shoe, out?

Singlequote and backslash

Why would Lupin kill Pettigrew?

Cryptography and patents

Why is there a need to modify system call tables in Linux?

Beginner's snake game using PyGame

What people are called "кабан" and why?

Rotated Position of Integers

Applicants clearly not having the skills they advertise

How do I truncate a csv file?

Can an old DSLR be upgraded to match modern smartphone image quality

Are academic associations obliged to comply with the US government?

How to detach yourself from a character you're going to kill?

Is there a term for this?

Order by does not work as I expect

Estimate related to the Möbius function

Future enhancements for the finite element method

Have powerful mythological heroes ever run away or been deeply afraid?

What TV show or movie did I watch on TV years ago where diseased people are exiled to a spaceship?

Select row of data if next row contains zero

How crucial is a waifu game storyline?

Strange math syntax in old basic listing

Asking for something with different prices



http.Handler is not called in golang


Golang application auto build versioningGolang Gorilla mux with http.FileServer returning 404Golang Gorilla/sessionGolang http mux change handler functiongolang return static html file at specified routeglobal recover handler for golang http panicGo - Variable initialized and non nil, but nil for other functionsGolang sharing configurations between packagesGolang logging http responses (in addition to requests)Golang package undefined






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have the following middleware, first sets currentUser in gorilla/context to current user acquired from database, and the second checks if currentUser exists and redirects otherwise:



package main

import (
"database/sql"
"github.com/gorilla/context"
"log"
"net/http"
"server/helpers"
)

func withCurrentUser(db *sql.DB, next http.Handler) http.Handler
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)
userId := helpers.GetCurrentUserId(db, r)

if userId == nil
next.ServeHTTP(w, r)
return


row := db.QueryRow("SELECT username FROM User WHERE id=?", userId)
var username string

switch err := row.Scan(&username); err
case sql.ErrNoRows:
next.ServeHTTP(w, r)
return
case nil:
user := helpers.UserUserId: *userId, LoggedIn: true, Username: username
context.Set(r, "currentUser", user)
default:
log.Fatal(err)


next.ServeHTTP(w, r)
)


func loginRequired(next http.Handler) http.Handler
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)
user, ok := context.Get(r, "currentUser").(helpers.User)
log.Println(user, ok)
if !ok
http.Redirect(w, r, "/login", 301)
return

next.ServeHTTP(w, r)
)



Then when I register a route that requires authenticated user, I do the following:



router.Handle("/create_post",
withCurrentUser(db, loginRequired(http.HandlerFunc(createPostGet))),
).Methods(http.MethodGet)


Where createPostGet:



func createPostGet(w http.ResponseWriter, r *http.Request) 
tmpl := template.Must(template.ParseFiles("templates/createPost.html"))
user := context.Get(r, "currentUser").(helpers.User)
_ = tmpl.Execute(w, helpers.FormStructCurrentUser: user)



My problem is: even if user is authenticated and context is populated correctly, this route always redirects to login. I tried setting breakpoints inside loginRequired and adding log.Println (as you can see in code), and that function doesn't seem to be even called (no breakpoints stop, no log output, too).



What's happening and how to make sure loginRequired is called every time and checks context properly?



UPD: It doesn't seem to persist, I recompiled the app a few times and now it's working. Anyway, what might be the reason for such behavior (I'm positive I saved everything the first time).



UPD 2: I found out that the problem is connected to browser caching, but I still have no idea why it happens. When I disable browser caching, everything works and function is called every time, but while browser cache is enabled, the function isn't called at all. Any ideas?










share|improve this question






























    0















    I have the following middleware, first sets currentUser in gorilla/context to current user acquired from database, and the second checks if currentUser exists and redirects otherwise:



    package main

    import (
    "database/sql"
    "github.com/gorilla/context"
    "log"
    "net/http"
    "server/helpers"
    )

    func withCurrentUser(db *sql.DB, next http.Handler) http.Handler
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)
    userId := helpers.GetCurrentUserId(db, r)

    if userId == nil
    next.ServeHTTP(w, r)
    return


    row := db.QueryRow("SELECT username FROM User WHERE id=?", userId)
    var username string

    switch err := row.Scan(&username); err
    case sql.ErrNoRows:
    next.ServeHTTP(w, r)
    return
    case nil:
    user := helpers.UserUserId: *userId, LoggedIn: true, Username: username
    context.Set(r, "currentUser", user)
    default:
    log.Fatal(err)


    next.ServeHTTP(w, r)
    )


    func loginRequired(next http.Handler) http.Handler
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)
    user, ok := context.Get(r, "currentUser").(helpers.User)
    log.Println(user, ok)
    if !ok
    http.Redirect(w, r, "/login", 301)
    return

    next.ServeHTTP(w, r)
    )



    Then when I register a route that requires authenticated user, I do the following:



    router.Handle("/create_post",
    withCurrentUser(db, loginRequired(http.HandlerFunc(createPostGet))),
    ).Methods(http.MethodGet)


    Where createPostGet:



    func createPostGet(w http.ResponseWriter, r *http.Request) 
    tmpl := template.Must(template.ParseFiles("templates/createPost.html"))
    user := context.Get(r, "currentUser").(helpers.User)
    _ = tmpl.Execute(w, helpers.FormStructCurrentUser: user)



    My problem is: even if user is authenticated and context is populated correctly, this route always redirects to login. I tried setting breakpoints inside loginRequired and adding log.Println (as you can see in code), and that function doesn't seem to be even called (no breakpoints stop, no log output, too).



    What's happening and how to make sure loginRequired is called every time and checks context properly?



    UPD: It doesn't seem to persist, I recompiled the app a few times and now it's working. Anyway, what might be the reason for such behavior (I'm positive I saved everything the first time).



    UPD 2: I found out that the problem is connected to browser caching, but I still have no idea why it happens. When I disable browser caching, everything works and function is called every time, but while browser cache is enabled, the function isn't called at all. Any ideas?










    share|improve this question


























      0












      0








      0








      I have the following middleware, first sets currentUser in gorilla/context to current user acquired from database, and the second checks if currentUser exists and redirects otherwise:



      package main

      import (
      "database/sql"
      "github.com/gorilla/context"
      "log"
      "net/http"
      "server/helpers"
      )

      func withCurrentUser(db *sql.DB, next http.Handler) http.Handler
      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)
      userId := helpers.GetCurrentUserId(db, r)

      if userId == nil
      next.ServeHTTP(w, r)
      return


      row := db.QueryRow("SELECT username FROM User WHERE id=?", userId)
      var username string

      switch err := row.Scan(&username); err
      case sql.ErrNoRows:
      next.ServeHTTP(w, r)
      return
      case nil:
      user := helpers.UserUserId: *userId, LoggedIn: true, Username: username
      context.Set(r, "currentUser", user)
      default:
      log.Fatal(err)


      next.ServeHTTP(w, r)
      )


      func loginRequired(next http.Handler) http.Handler
      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)
      user, ok := context.Get(r, "currentUser").(helpers.User)
      log.Println(user, ok)
      if !ok
      http.Redirect(w, r, "/login", 301)
      return

      next.ServeHTTP(w, r)
      )



      Then when I register a route that requires authenticated user, I do the following:



      router.Handle("/create_post",
      withCurrentUser(db, loginRequired(http.HandlerFunc(createPostGet))),
      ).Methods(http.MethodGet)


      Where createPostGet:



      func createPostGet(w http.ResponseWriter, r *http.Request) 
      tmpl := template.Must(template.ParseFiles("templates/createPost.html"))
      user := context.Get(r, "currentUser").(helpers.User)
      _ = tmpl.Execute(w, helpers.FormStructCurrentUser: user)



      My problem is: even if user is authenticated and context is populated correctly, this route always redirects to login. I tried setting breakpoints inside loginRequired and adding log.Println (as you can see in code), and that function doesn't seem to be even called (no breakpoints stop, no log output, too).



      What's happening and how to make sure loginRequired is called every time and checks context properly?



      UPD: It doesn't seem to persist, I recompiled the app a few times and now it's working. Anyway, what might be the reason for such behavior (I'm positive I saved everything the first time).



      UPD 2: I found out that the problem is connected to browser caching, but I still have no idea why it happens. When I disable browser caching, everything works and function is called every time, but while browser cache is enabled, the function isn't called at all. Any ideas?










      share|improve this question
















      I have the following middleware, first sets currentUser in gorilla/context to current user acquired from database, and the second checks if currentUser exists and redirects otherwise:



      package main

      import (
      "database/sql"
      "github.com/gorilla/context"
      "log"
      "net/http"
      "server/helpers"
      )

      func withCurrentUser(db *sql.DB, next http.Handler) http.Handler
      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)
      userId := helpers.GetCurrentUserId(db, r)

      if userId == nil
      next.ServeHTTP(w, r)
      return


      row := db.QueryRow("SELECT username FROM User WHERE id=?", userId)
      var username string

      switch err := row.Scan(&username); err
      case sql.ErrNoRows:
      next.ServeHTTP(w, r)
      return
      case nil:
      user := helpers.UserUserId: *userId, LoggedIn: true, Username: username
      context.Set(r, "currentUser", user)
      default:
      log.Fatal(err)


      next.ServeHTTP(w, r)
      )


      func loginRequired(next http.Handler) http.Handler
      return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)
      user, ok := context.Get(r, "currentUser").(helpers.User)
      log.Println(user, ok)
      if !ok
      http.Redirect(w, r, "/login", 301)
      return

      next.ServeHTTP(w, r)
      )



      Then when I register a route that requires authenticated user, I do the following:



      router.Handle("/create_post",
      withCurrentUser(db, loginRequired(http.HandlerFunc(createPostGet))),
      ).Methods(http.MethodGet)


      Where createPostGet:



      func createPostGet(w http.ResponseWriter, r *http.Request) 
      tmpl := template.Must(template.ParseFiles("templates/createPost.html"))
      user := context.Get(r, "currentUser").(helpers.User)
      _ = tmpl.Execute(w, helpers.FormStructCurrentUser: user)



      My problem is: even if user is authenticated and context is populated correctly, this route always redirects to login. I tried setting breakpoints inside loginRequired and adding log.Println (as you can see in code), and that function doesn't seem to be even called (no breakpoints stop, no log output, too).



      What's happening and how to make sure loginRequired is called every time and checks context properly?



      UPD: It doesn't seem to persist, I recompiled the app a few times and now it's working. Anyway, what might be the reason for such behavior (I'm positive I saved everything the first time).



      UPD 2: I found out that the problem is connected to browser caching, but I still have no idea why it happens. When I disable browser caching, everything works and function is called every time, but while browser cache is enabled, the function isn't called at all. Any ideas?







      go middleware gorilla






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 24 at 15:51







      Nikitin Roman

















      asked Mar 24 at 11:15









      Nikitin RomanNikitin Roman

      9161841




      9161841






















          1 Answer
          1






          active

          oldest

          votes


















          1














          OMG, that was stupid. I was using 301 redirect code in loginRequired, so redirect was permanent and browser didn't even make requests.






          share|improve this answer























          • Ouch! We've all been there!

            – colminator
            Mar 25 at 0:37











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55323218%2fhttp-handler-is-not-called-in-golang%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          OMG, that was stupid. I was using 301 redirect code in loginRequired, so redirect was permanent and browser didn't even make requests.






          share|improve this answer























          • Ouch! We've all been there!

            – colminator
            Mar 25 at 0:37















          1














          OMG, that was stupid. I was using 301 redirect code in loginRequired, so redirect was permanent and browser didn't even make requests.






          share|improve this answer























          • Ouch! We've all been there!

            – colminator
            Mar 25 at 0:37













          1












          1








          1







          OMG, that was stupid. I was using 301 redirect code in loginRequired, so redirect was permanent and browser didn't even make requests.






          share|improve this answer













          OMG, that was stupid. I was using 301 redirect code in loginRequired, so redirect was permanent and browser didn't even make requests.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 24 at 16:55









          Nikitin RomanNikitin Roman

          9161841




          9161841












          • Ouch! We've all been there!

            – colminator
            Mar 25 at 0:37

















          • Ouch! We've all been there!

            – colminator
            Mar 25 at 0:37
















          Ouch! We've all been there!

          – colminator
          Mar 25 at 0:37





          Ouch! We've all been there!

          – colminator
          Mar 25 at 0:37

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55323218%2fhttp-handler-is-not-called-in-golang%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript