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

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현